PackageManagerService.java revision a440d94d0ffe084026b24a16f7684efe1b1baff8
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 @Nullable ComponentName mIntentFilterVerifierComponent;
606    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
607
608    private int mIntentFilterVerificationToken = 0;
609
610    /** Component that knows whether or not an ephemeral application exists */
611    final ComponentName mEphemeralResolverComponent;
612    /** The service connection to the ephemeral resolver */
613    final EphemeralResolverConnection mEphemeralResolverConnection;
614
615    /** Component used to install ephemeral applications */
616    final ComponentName mEphemeralInstallerComponent;
617    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
618    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
619
620    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
621            = new SparseArray<IntentFilterVerificationState>();
622
623    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
624            new DefaultPermissionGrantPolicy(this);
625
626    // List of packages names to keep cached, even if they are uninstalled for all users
627    private List<String> mKeepUninstalledPackages;
628
629    private static class IFVerificationParams {
630        PackageParser.Package pkg;
631        boolean replacing;
632        int userId;
633        int verifierUid;
634
635        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
636                int _userId, int _verifierUid) {
637            pkg = _pkg;
638            replacing = _replacing;
639            userId = _userId;
640            replacing = _replacing;
641            verifierUid = _verifierUid;
642        }
643    }
644
645    private interface IntentFilterVerifier<T extends IntentFilter> {
646        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
647                                               T filter, String packageName);
648        void startVerifications(int userId);
649        void receiveVerificationResponse(int verificationId);
650    }
651
652    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
653        private Context mContext;
654        private ComponentName mIntentFilterVerifierComponent;
655        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
656
657        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
658            mContext = context;
659            mIntentFilterVerifierComponent = verifierComponent;
660        }
661
662        private String getDefaultScheme() {
663            return IntentFilter.SCHEME_HTTPS;
664        }
665
666        @Override
667        public void startVerifications(int userId) {
668            // Launch verifications requests
669            int count = mCurrentIntentFilterVerifications.size();
670            for (int n=0; n<count; n++) {
671                int verificationId = mCurrentIntentFilterVerifications.get(n);
672                final IntentFilterVerificationState ivs =
673                        mIntentFilterVerificationStates.get(verificationId);
674
675                String packageName = ivs.getPackageName();
676
677                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
678                final int filterCount = filters.size();
679                ArraySet<String> domainsSet = new ArraySet<>();
680                for (int m=0; m<filterCount; m++) {
681                    PackageParser.ActivityIntentInfo filter = filters.get(m);
682                    domainsSet.addAll(filter.getHostsList());
683                }
684                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
685                synchronized (mPackages) {
686                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
687                            packageName, domainsList) != null) {
688                        scheduleWriteSettingsLocked();
689                    }
690                }
691                sendVerificationRequest(userId, verificationId, ivs);
692            }
693            mCurrentIntentFilterVerifications.clear();
694        }
695
696        private void sendVerificationRequest(int userId, int verificationId,
697                IntentFilterVerificationState ivs) {
698
699            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
702                    verificationId);
703            verificationIntent.putExtra(
704                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
705                    getDefaultScheme());
706            verificationIntent.putExtra(
707                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
708                    ivs.getHostsString());
709            verificationIntent.putExtra(
710                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
711                    ivs.getPackageName());
712            verificationIntent.setComponent(mIntentFilterVerifierComponent);
713            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
714
715            UserHandle user = new UserHandle(userId);
716            mContext.sendBroadcastAsUser(verificationIntent, user);
717            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
718                    "Sending IntentFilter verification broadcast");
719        }
720
721        public void receiveVerificationResponse(int verificationId) {
722            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
723
724            final boolean verified = ivs.isVerified();
725
726            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
727            final int count = filters.size();
728            if (DEBUG_DOMAIN_VERIFICATION) {
729                Slog.i(TAG, "Received verification response " + verificationId
730                        + " for " + count + " filters, verified=" + verified);
731            }
732            for (int n=0; n<count; n++) {
733                PackageParser.ActivityIntentInfo filter = filters.get(n);
734                filter.setVerified(verified);
735
736                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
737                        + " verified with result:" + verified + " and hosts:"
738                        + ivs.getHostsString());
739            }
740
741            mIntentFilterVerificationStates.remove(verificationId);
742
743            final String packageName = ivs.getPackageName();
744            IntentFilterVerificationInfo ivi = null;
745
746            synchronized (mPackages) {
747                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
748            }
749            if (ivi == null) {
750                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
751                        + verificationId + " packageName:" + packageName);
752                return;
753            }
754            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
755                    "Updating IntentFilterVerificationInfo for package " + packageName
756                            +" verificationId:" + verificationId);
757
758            synchronized (mPackages) {
759                if (verified) {
760                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
761                } else {
762                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
763                }
764                scheduleWriteSettingsLocked();
765
766                final int userId = ivs.getUserId();
767                if (userId != UserHandle.USER_ALL) {
768                    final int userStatus =
769                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
770
771                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
772                    boolean needUpdate = false;
773
774                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
775                    // already been set by the User thru the Disambiguation dialog
776                    switch (userStatus) {
777                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
778                            if (verified) {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
780                            } else {
781                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
782                            }
783                            needUpdate = true;
784                            break;
785
786                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
787                            if (verified) {
788                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
789                                needUpdate = true;
790                            }
791                            break;
792
793                        default:
794                            // Nothing to do
795                    }
796
797                    if (needUpdate) {
798                        mSettings.updateIntentFilterVerificationStatusLPw(
799                                packageName, updatedStatus, userId);
800                        scheduleWritePackageRestrictionsLocked(userId);
801                    }
802                }
803            }
804        }
805
806        @Override
807        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
808                    ActivityIntentInfo filter, String packageName) {
809            if (!hasValidDomains(filter)) {
810                return false;
811            }
812            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
813            if (ivs == null) {
814                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
815                        packageName);
816            }
817            if (DEBUG_DOMAIN_VERIFICATION) {
818                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
819            }
820            ivs.addFilter(filter);
821            return true;
822        }
823
824        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
825                int userId, int verificationId, String packageName) {
826            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
827                    verifierUid, userId, packageName);
828            ivs.setPendingState();
829            synchronized (mPackages) {
830                mIntentFilterVerificationStates.append(verificationId, ivs);
831                mCurrentIntentFilterVerifications.add(verificationId);
832            }
833            return ivs;
834        }
835    }
836
837    private static boolean hasValidDomains(ActivityIntentInfo filter) {
838        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
839                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
840                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
841    }
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 @Nullable String mRequiredVerifierPackage;
978    final @Nullable 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            if (!mOnlyCore) {
2366                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2367                mRequiredInstallerPackage = getRequiredInstallerLPr();
2368                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2369                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2370                        mIntentFilterVerifierComponent);
2371            } else {
2372                mRequiredVerifierPackage = null;
2373                mRequiredInstallerPackage = null;
2374                mIntentFilterVerifierComponent = null;
2375                mIntentFilterVerifier = null;
2376            }
2377
2378            mInstallerService = new PackageInstallerService(context, this);
2379
2380            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2381            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2382            // both the installer and resolver must be present to enable ephemeral
2383            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2384                if (DEBUG_EPHEMERAL) {
2385                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2386                            + " installer:" + ephemeralInstallerComponent);
2387                }
2388                mEphemeralResolverComponent = ephemeralResolverComponent;
2389                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2390                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2391                mEphemeralResolverConnection =
2392                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2393            } else {
2394                if (DEBUG_EPHEMERAL) {
2395                    final String missingComponent =
2396                            (ephemeralResolverComponent == null)
2397                            ? (ephemeralInstallerComponent == null)
2398                                    ? "resolver and installer"
2399                                    : "resolver"
2400                            : "installer";
2401                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2402                }
2403                mEphemeralResolverComponent = null;
2404                mEphemeralInstallerComponent = null;
2405                mEphemeralResolverConnection = null;
2406            }
2407
2408            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2409        } // synchronized (mPackages)
2410        } // synchronized (mInstallLock)
2411
2412        // Now after opening every single application zip, make sure they
2413        // are all flushed.  Not really needed, but keeps things nice and
2414        // tidy.
2415        Runtime.getRuntime().gc();
2416
2417        // The initial scanning above does many calls into installd while
2418        // holding the mPackages lock, but we're mostly interested in yelling
2419        // once we have a booted system.
2420        mInstaller.setWarnIfHeld(mPackages);
2421
2422        // Expose private service for system components to use.
2423        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2424    }
2425
2426    @Override
2427    public boolean isFirstBoot() {
2428        return !mRestoredSettings;
2429    }
2430
2431    @Override
2432    public boolean isOnlyCoreApps() {
2433        return mOnlyCore;
2434    }
2435
2436    @Override
2437    public boolean isUpgrade() {
2438        return mIsUpgrade;
2439    }
2440
2441    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2442        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2443
2444        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2445                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2446        if (matches.size() == 1) {
2447            return matches.get(0).getComponentInfo().packageName;
2448        } else {
2449            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2450            return null;
2451        }
2452    }
2453
2454    private @NonNull String getRequiredInstallerLPr() {
2455        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2456        intent.addCategory(Intent.CATEGORY_DEFAULT);
2457        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2458
2459        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2460                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2461        if (matches.size() == 1) {
2462            return matches.get(0).getComponentInfo().packageName;
2463        } else {
2464            throw new RuntimeException("There must be exactly one installer; found " + matches);
2465        }
2466    }
2467
2468    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2469        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2470
2471        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2472                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2473        ResolveInfo best = null;
2474        final int N = matches.size();
2475        for (int i = 0; i < N; i++) {
2476            final ResolveInfo cur = matches.get(i);
2477            final String packageName = cur.getComponentInfo().packageName;
2478            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2479                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2480                continue;
2481            }
2482
2483            if (best == null || cur.priority > best.priority) {
2484                best = cur;
2485            }
2486        }
2487
2488        if (best != null) {
2489            return best.getComponentInfo().getComponentName();
2490        } else {
2491            throw new RuntimeException("There must be at least one intent filter verifier");
2492        }
2493    }
2494
2495    private @Nullable ComponentName getEphemeralResolverLPr() {
2496        final String[] packageArray =
2497                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2498        if (packageArray.length == 0) {
2499            if (DEBUG_EPHEMERAL) {
2500                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2501            }
2502            return null;
2503        }
2504
2505        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2506        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2507                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2508
2509        final int N = resolvers.size();
2510        if (N == 0) {
2511            if (DEBUG_EPHEMERAL) {
2512                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2513            }
2514            return null;
2515        }
2516
2517        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2518        for (int i = 0; i < N; i++) {
2519            final ResolveInfo info = resolvers.get(i);
2520
2521            if (info.serviceInfo == null) {
2522                continue;
2523            }
2524
2525            final String packageName = info.serviceInfo.packageName;
2526            if (!possiblePackages.contains(packageName)) {
2527                if (DEBUG_EPHEMERAL) {
2528                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2529                            + " pkg: " + packageName + ", info:" + info);
2530                }
2531                continue;
2532            }
2533
2534            if (DEBUG_EPHEMERAL) {
2535                Slog.v(TAG, "Ephemeral resolver found;"
2536                        + " pkg: " + packageName + ", info:" + info);
2537            }
2538            return new ComponentName(packageName, info.serviceInfo.name);
2539        }
2540        if (DEBUG_EPHEMERAL) {
2541            Slog.v(TAG, "Ephemeral resolver NOT found");
2542        }
2543        return null;
2544    }
2545
2546    private @Nullable ComponentName getEphemeralInstallerLPr() {
2547        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2548        intent.addCategory(Intent.CATEGORY_DEFAULT);
2549        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2550
2551        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2552                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2553        if (matches.size() == 0) {
2554            return null;
2555        } else if (matches.size() == 1) {
2556            return matches.get(0).getComponentInfo().getComponentName();
2557        } else {
2558            throw new RuntimeException(
2559                    "There must be at most one ephemeral installer; found " + matches);
2560        }
2561    }
2562
2563    private void primeDomainVerificationsLPw(int userId) {
2564        if (DEBUG_DOMAIN_VERIFICATION) {
2565            Slog.d(TAG, "Priming domain verifications in user " + userId);
2566        }
2567
2568        SystemConfig systemConfig = SystemConfig.getInstance();
2569        ArraySet<String> packages = systemConfig.getLinkedApps();
2570        ArraySet<String> domains = new ArraySet<String>();
2571
2572        for (String packageName : packages) {
2573            PackageParser.Package pkg = mPackages.get(packageName);
2574            if (pkg != null) {
2575                if (!pkg.isSystemApp()) {
2576                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2577                    continue;
2578                }
2579
2580                domains.clear();
2581                for (PackageParser.Activity a : pkg.activities) {
2582                    for (ActivityIntentInfo filter : a.intents) {
2583                        if (hasValidDomains(filter)) {
2584                            domains.addAll(filter.getHostsList());
2585                        }
2586                    }
2587                }
2588
2589                if (domains.size() > 0) {
2590                    if (DEBUG_DOMAIN_VERIFICATION) {
2591                        Slog.v(TAG, "      + " + packageName);
2592                    }
2593                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2594                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2595                    // and then 'always' in the per-user state actually used for intent resolution.
2596                    final IntentFilterVerificationInfo ivi;
2597                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2598                            new ArrayList<String>(domains));
2599                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2600                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2601                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2602                } else {
2603                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2604                            + "' does not handle web links");
2605                }
2606            } else {
2607                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2608            }
2609        }
2610
2611        scheduleWritePackageRestrictionsLocked(userId);
2612        scheduleWriteSettingsLocked();
2613    }
2614
2615    private void applyFactoryDefaultBrowserLPw(int userId) {
2616        // The default browser app's package name is stored in a string resource,
2617        // with a product-specific overlay used for vendor customization.
2618        String browserPkg = mContext.getResources().getString(
2619                com.android.internal.R.string.default_browser);
2620        if (!TextUtils.isEmpty(browserPkg)) {
2621            // non-empty string => required to be a known package
2622            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2623            if (ps == null) {
2624                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2625                browserPkg = null;
2626            } else {
2627                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2628            }
2629        }
2630
2631        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2632        // default.  If there's more than one, just leave everything alone.
2633        if (browserPkg == null) {
2634            calculateDefaultBrowserLPw(userId);
2635        }
2636    }
2637
2638    private void calculateDefaultBrowserLPw(int userId) {
2639        List<String> allBrowsers = resolveAllBrowserApps(userId);
2640        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2641        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2642    }
2643
2644    private List<String> resolveAllBrowserApps(int userId) {
2645        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2646        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2647                PackageManager.MATCH_ALL, userId);
2648
2649        final int count = list.size();
2650        List<String> result = new ArrayList<String>(count);
2651        for (int i=0; i<count; i++) {
2652            ResolveInfo info = list.get(i);
2653            if (info.activityInfo == null
2654                    || !info.handleAllWebDataURI
2655                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2656                    || result.contains(info.activityInfo.packageName)) {
2657                continue;
2658            }
2659            result.add(info.activityInfo.packageName);
2660        }
2661
2662        return result;
2663    }
2664
2665    private boolean packageIsBrowser(String packageName, int userId) {
2666        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2667                PackageManager.MATCH_ALL, userId);
2668        final int N = list.size();
2669        for (int i = 0; i < N; i++) {
2670            ResolveInfo info = list.get(i);
2671            if (packageName.equals(info.activityInfo.packageName)) {
2672                return true;
2673            }
2674        }
2675        return false;
2676    }
2677
2678    private void checkDefaultBrowser() {
2679        final int myUserId = UserHandle.myUserId();
2680        final String packageName = getDefaultBrowserPackageName(myUserId);
2681        if (packageName != null) {
2682            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2683            if (info == null) {
2684                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2685                synchronized (mPackages) {
2686                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2687                }
2688            }
2689        }
2690    }
2691
2692    @Override
2693    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2694            throws RemoteException {
2695        try {
2696            return super.onTransact(code, data, reply, flags);
2697        } catch (RuntimeException e) {
2698            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2699                Slog.wtf(TAG, "Package Manager Crash", e);
2700            }
2701            throw e;
2702        }
2703    }
2704
2705    void cleanupInstallFailedPackage(PackageSetting ps) {
2706        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2707
2708        removeDataDirsLI(ps.volumeUuid, ps.name);
2709        if (ps.codePath != null) {
2710            if (ps.codePath.isDirectory()) {
2711                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2712            } else {
2713                ps.codePath.delete();
2714            }
2715        }
2716        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2717            if (ps.resourcePath.isDirectory()) {
2718                FileUtils.deleteContents(ps.resourcePath);
2719            }
2720            ps.resourcePath.delete();
2721        }
2722        mSettings.removePackageLPw(ps.name);
2723    }
2724
2725    static int[] appendInts(int[] cur, int[] add) {
2726        if (add == null) return cur;
2727        if (cur == null) return add;
2728        final int N = add.length;
2729        for (int i=0; i<N; i++) {
2730            cur = appendInt(cur, add[i]);
2731        }
2732        return cur;
2733    }
2734
2735    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2736        if (!sUserManager.exists(userId)) return null;
2737        final PackageSetting ps = (PackageSetting) p.mExtras;
2738        if (ps == null) {
2739            return null;
2740        }
2741
2742        final PermissionsState permissionsState = ps.getPermissionsState();
2743
2744        final int[] gids = permissionsState.computeGids(userId);
2745        final Set<String> permissions = permissionsState.getPermissions(userId);
2746        final PackageUserState state = ps.readUserState(userId);
2747
2748        return PackageParser.generatePackageInfo(p, gids, flags,
2749                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2750    }
2751
2752    @Override
2753    public void checkPackageStartable(String packageName, int userId) {
2754        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2755
2756        synchronized (mPackages) {
2757            final PackageSetting ps = mSettings.mPackages.get(packageName);
2758            if (ps == null) {
2759                throw new SecurityException("Package " + packageName + " was not found!");
2760            }
2761
2762            if (ps.frozen) {
2763                throw new SecurityException("Package " + packageName + " is currently frozen!");
2764            }
2765
2766            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2767                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2768                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2769            }
2770        }
2771    }
2772
2773    @Override
2774    public boolean isPackageAvailable(String packageName, int userId) {
2775        if (!sUserManager.exists(userId)) return false;
2776        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2777        synchronized (mPackages) {
2778            PackageParser.Package p = mPackages.get(packageName);
2779            if (p != null) {
2780                final PackageSetting ps = (PackageSetting) p.mExtras;
2781                if (ps != null) {
2782                    final PackageUserState state = ps.readUserState(userId);
2783                    if (state != null) {
2784                        return PackageParser.isAvailable(state);
2785                    }
2786                }
2787            }
2788        }
2789        return false;
2790    }
2791
2792    @Override
2793    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2794        if (!sUserManager.exists(userId)) return null;
2795        flags = updateFlagsForPackage(flags, userId, packageName);
2796        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2797        // reader
2798        synchronized (mPackages) {
2799            PackageParser.Package p = mPackages.get(packageName);
2800            if (DEBUG_PACKAGE_INFO)
2801                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2802            if (p != null) {
2803                return generatePackageInfo(p, flags, userId);
2804            }
2805            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2806                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2807            }
2808        }
2809        return null;
2810    }
2811
2812    @Override
2813    public String[] currentToCanonicalPackageNames(String[] names) {
2814        String[] out = new String[names.length];
2815        // reader
2816        synchronized (mPackages) {
2817            for (int i=names.length-1; i>=0; i--) {
2818                PackageSetting ps = mSettings.mPackages.get(names[i]);
2819                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2820            }
2821        }
2822        return out;
2823    }
2824
2825    @Override
2826    public String[] canonicalToCurrentPackageNames(String[] names) {
2827        String[] out = new String[names.length];
2828        // reader
2829        synchronized (mPackages) {
2830            for (int i=names.length-1; i>=0; i--) {
2831                String cur = mSettings.mRenamedPackages.get(names[i]);
2832                out[i] = cur != null ? cur : names[i];
2833            }
2834        }
2835        return out;
2836    }
2837
2838    @Override
2839    public int getPackageUid(String packageName, int userId) {
2840        return getPackageUidEtc(packageName, 0, userId);
2841    }
2842
2843    @Override
2844    public int getPackageUidEtc(String packageName, int flags, int userId) {
2845        if (!sUserManager.exists(userId)) return -1;
2846        flags = updateFlagsForPackage(flags, userId, packageName);
2847        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2848
2849        // reader
2850        synchronized (mPackages) {
2851            final PackageParser.Package p = mPackages.get(packageName);
2852            if (p != null) {
2853                return UserHandle.getUid(userId, p.applicationInfo.uid);
2854            }
2855            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2856                final PackageSetting ps = mSettings.mPackages.get(packageName);
2857                if (ps != null) {
2858                    return UserHandle.getUid(userId, ps.appId);
2859                }
2860            }
2861        }
2862
2863        return -1;
2864    }
2865
2866    @Override
2867    public int[] getPackageGids(String packageName, int userId) {
2868        return getPackageGidsEtc(packageName, 0, userId);
2869    }
2870
2871    @Override
2872    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2873        if (!sUserManager.exists(userId)) return null;
2874        flags = updateFlagsForPackage(flags, userId, packageName);
2875        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2876                "getPackageGids");
2877
2878        // reader
2879        synchronized (mPackages) {
2880            final PackageParser.Package p = mPackages.get(packageName);
2881            if (p != null) {
2882                PackageSetting ps = (PackageSetting) p.mExtras;
2883                return ps.getPermissionsState().computeGids(userId);
2884            }
2885            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2886                final PackageSetting ps = mSettings.mPackages.get(packageName);
2887                if (ps != null) {
2888                    return ps.getPermissionsState().computeGids(userId);
2889                }
2890            }
2891        }
2892
2893        return null;
2894    }
2895
2896    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2897        if (bp.perm != null) {
2898            return PackageParser.generatePermissionInfo(bp.perm, flags);
2899        }
2900        PermissionInfo pi = new PermissionInfo();
2901        pi.name = bp.name;
2902        pi.packageName = bp.sourcePackage;
2903        pi.nonLocalizedLabel = bp.name;
2904        pi.protectionLevel = bp.protectionLevel;
2905        return pi;
2906    }
2907
2908    @Override
2909    public PermissionInfo getPermissionInfo(String name, int flags) {
2910        // reader
2911        synchronized (mPackages) {
2912            final BasePermission p = mSettings.mPermissions.get(name);
2913            if (p != null) {
2914                return generatePermissionInfo(p, flags);
2915            }
2916            return null;
2917        }
2918    }
2919
2920    @Override
2921    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2922        // reader
2923        synchronized (mPackages) {
2924            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2925            for (BasePermission p : mSettings.mPermissions.values()) {
2926                if (group == null) {
2927                    if (p.perm == null || p.perm.info.group == null) {
2928                        out.add(generatePermissionInfo(p, flags));
2929                    }
2930                } else {
2931                    if (p.perm != null && group.equals(p.perm.info.group)) {
2932                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2933                    }
2934                }
2935            }
2936
2937            if (out.size() > 0) {
2938                return out;
2939            }
2940            return mPermissionGroups.containsKey(group) ? out : null;
2941        }
2942    }
2943
2944    @Override
2945    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2946        // reader
2947        synchronized (mPackages) {
2948            return PackageParser.generatePermissionGroupInfo(
2949                    mPermissionGroups.get(name), flags);
2950        }
2951    }
2952
2953    @Override
2954    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2955        // reader
2956        synchronized (mPackages) {
2957            final int N = mPermissionGroups.size();
2958            ArrayList<PermissionGroupInfo> out
2959                    = new ArrayList<PermissionGroupInfo>(N);
2960            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2961                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2962            }
2963            return out;
2964        }
2965    }
2966
2967    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2968            int userId) {
2969        if (!sUserManager.exists(userId)) return null;
2970        PackageSetting ps = mSettings.mPackages.get(packageName);
2971        if (ps != null) {
2972            if (ps.pkg == null) {
2973                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2974                        flags, userId);
2975                if (pInfo != null) {
2976                    return pInfo.applicationInfo;
2977                }
2978                return null;
2979            }
2980            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2981                    ps.readUserState(userId), userId);
2982        }
2983        return null;
2984    }
2985
2986    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2987            int userId) {
2988        if (!sUserManager.exists(userId)) return null;
2989        PackageSetting ps = mSettings.mPackages.get(packageName);
2990        if (ps != null) {
2991            PackageParser.Package pkg = ps.pkg;
2992            if (pkg == null) {
2993                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
2994                    return null;
2995                }
2996                // Only data remains, so we aren't worried about code paths
2997                pkg = new PackageParser.Package(packageName);
2998                pkg.applicationInfo.packageName = packageName;
2999                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3000                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3001                pkg.applicationInfo.uid = ps.appId;
3002                pkg.applicationInfo.initForUser(userId);
3003                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3004                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3005            }
3006            return generatePackageInfo(pkg, flags, userId);
3007        }
3008        return null;
3009    }
3010
3011    @Override
3012    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3013        if (!sUserManager.exists(userId)) return null;
3014        flags = updateFlagsForApplication(flags, userId, packageName);
3015        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3016        // writer
3017        synchronized (mPackages) {
3018            PackageParser.Package p = mPackages.get(packageName);
3019            if (DEBUG_PACKAGE_INFO) Log.v(
3020                    TAG, "getApplicationInfo " + packageName
3021                    + ": " + p);
3022            if (p != null) {
3023                PackageSetting ps = mSettings.mPackages.get(packageName);
3024                if (ps == null) return null;
3025                // Note: isEnabledLP() does not apply here - always return info
3026                return PackageParser.generateApplicationInfo(
3027                        p, flags, ps.readUserState(userId), userId);
3028            }
3029            if ("android".equals(packageName)||"system".equals(packageName)) {
3030                return mAndroidApplication;
3031            }
3032            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3033                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3034            }
3035        }
3036        return null;
3037    }
3038
3039    @Override
3040    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3041            final IPackageDataObserver observer) {
3042        mContext.enforceCallingOrSelfPermission(
3043                android.Manifest.permission.CLEAR_APP_CACHE, null);
3044        // Queue up an async operation since clearing cache may take a little while.
3045        mHandler.post(new Runnable() {
3046            public void run() {
3047                mHandler.removeCallbacks(this);
3048                int retCode = -1;
3049                synchronized (mInstallLock) {
3050                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3051                    if (retCode < 0) {
3052                        Slog.w(TAG, "Couldn't clear application caches");
3053                    }
3054                }
3055                if (observer != null) {
3056                    try {
3057                        observer.onRemoveCompleted(null, (retCode >= 0));
3058                    } catch (RemoteException e) {
3059                        Slog.w(TAG, "RemoveException when invoking call back");
3060                    }
3061                }
3062            }
3063        });
3064    }
3065
3066    @Override
3067    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3068            final IntentSender pi) {
3069        mContext.enforceCallingOrSelfPermission(
3070                android.Manifest.permission.CLEAR_APP_CACHE, null);
3071        // Queue up an async operation since clearing cache may take a little while.
3072        mHandler.post(new Runnable() {
3073            public void run() {
3074                mHandler.removeCallbacks(this);
3075                int retCode = -1;
3076                synchronized (mInstallLock) {
3077                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3078                    if (retCode < 0) {
3079                        Slog.w(TAG, "Couldn't clear application caches");
3080                    }
3081                }
3082                if(pi != null) {
3083                    try {
3084                        // Callback via pending intent
3085                        int code = (retCode >= 0) ? 1 : 0;
3086                        pi.sendIntent(null, code, null,
3087                                null, null);
3088                    } catch (SendIntentException e1) {
3089                        Slog.i(TAG, "Failed to send pending intent");
3090                    }
3091                }
3092            }
3093        });
3094    }
3095
3096    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3097        synchronized (mInstallLock) {
3098            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3099                throw new IOException("Failed to free enough space");
3100            }
3101        }
3102    }
3103
3104    /**
3105     * Return if the user key is currently unlocked.
3106     */
3107    private boolean isUserKeyUnlocked(int userId) {
3108        if (StorageManager.isFileBasedEncryptionEnabled()) {
3109            final IMountService mount = IMountService.Stub
3110                    .asInterface(ServiceManager.getService("mount"));
3111            if (mount == null) {
3112                Slog.w(TAG, "Early during boot, assuming locked");
3113                return false;
3114            }
3115            final long token = Binder.clearCallingIdentity();
3116            try {
3117                return mount.isUserKeyUnlocked(userId);
3118            } catch (RemoteException e) {
3119                throw e.rethrowAsRuntimeException();
3120            } finally {
3121                Binder.restoreCallingIdentity(token);
3122            }
3123        } else {
3124            return true;
3125        }
3126    }
3127
3128    /**
3129     * Update given flags based on encryption status of current user.
3130     */
3131    private int updateFlagsForEncryption(int flags, int userId) {
3132        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3133                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3134            // Caller expressed an explicit opinion about what encryption
3135            // aware/unaware components they want to see, so fall through and
3136            // give them what they want
3137        } else {
3138            // Caller expressed no opinion, so match based on user state
3139            if (isUserKeyUnlocked(userId)) {
3140                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3141            } else {
3142                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3143            }
3144        }
3145        return flags;
3146    }
3147
3148    /**
3149     * Update given flags when being used to request {@link PackageInfo}.
3150     */
3151    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3152        boolean triaged = true;
3153        if ((flags & PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3154                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS) != 0) {
3155            // Caller is asking for component details, so they'd better be
3156            // asking for specific encryption matching behavior, or be triaged
3157            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3158                    | PackageManager.MATCH_ENCRYPTION_AWARE
3159                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3160                triaged = false;
3161            }
3162        }
3163        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3164                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3165            triaged = false;
3166        }
3167        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3168            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie,
3169                    new Throwable());
3170        }
3171        return updateFlagsForEncryption(flags, userId);
3172    }
3173
3174    /**
3175     * Update given flags when being used to request {@link ApplicationInfo}.
3176     */
3177    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3178        return updateFlagsForPackage(flags, userId, cookie);
3179    }
3180
3181    /**
3182     * Update given flags when being used to request {@link ComponentInfo}.
3183     */
3184    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3185        boolean triaged = true;
3186        // Caller is asking for component details, so they'd better be
3187        // asking for specific encryption matching behavior, or be triaged
3188        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3189                | PackageManager.MATCH_ENCRYPTION_AWARE
3190                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3191            triaged = false;
3192        }
3193        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3194            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie,
3195                    new Throwable());
3196        }
3197        return updateFlagsForEncryption(flags, userId);
3198    }
3199
3200    /**
3201     * Update given flags when being used to request {@link ResolveInfo}.
3202     */
3203    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3204        return updateFlagsForComponent(flags, userId, cookie);
3205    }
3206
3207    @Override
3208    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3209        if (!sUserManager.exists(userId)) return null;
3210        flags = updateFlagsForComponent(flags, userId, component);
3211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3212        synchronized (mPackages) {
3213            PackageParser.Activity a = mActivities.mActivities.get(component);
3214
3215            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3216            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3218                if (ps == null) return null;
3219                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3220                        userId);
3221            }
3222            if (mResolveComponentName.equals(component)) {
3223                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3224                        new PackageUserState(), userId);
3225            }
3226        }
3227        return null;
3228    }
3229
3230    @Override
3231    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3232            String resolvedType) {
3233        synchronized (mPackages) {
3234            if (component.equals(mResolveComponentName)) {
3235                // The resolver supports EVERYTHING!
3236                return true;
3237            }
3238            PackageParser.Activity a = mActivities.mActivities.get(component);
3239            if (a == null) {
3240                return false;
3241            }
3242            for (int i=0; i<a.intents.size(); i++) {
3243                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3244                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3245                    return true;
3246                }
3247            }
3248            return false;
3249        }
3250    }
3251
3252    @Override
3253    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3254        if (!sUserManager.exists(userId)) return null;
3255        flags = updateFlagsForComponent(flags, userId, component);
3256        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3257        synchronized (mPackages) {
3258            PackageParser.Activity a = mReceivers.mActivities.get(component);
3259            if (DEBUG_PACKAGE_INFO) Log.v(
3260                TAG, "getReceiverInfo " + component + ": " + a);
3261            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3262                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3263                if (ps == null) return null;
3264                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3265                        userId);
3266            }
3267        }
3268        return null;
3269    }
3270
3271    @Override
3272    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3273        if (!sUserManager.exists(userId)) return null;
3274        flags = updateFlagsForComponent(flags, userId, component);
3275        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3276        synchronized (mPackages) {
3277            PackageParser.Service s = mServices.mServices.get(component);
3278            if (DEBUG_PACKAGE_INFO) Log.v(
3279                TAG, "getServiceInfo " + component + ": " + s);
3280            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3281                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3282                if (ps == null) return null;
3283                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3284                        userId);
3285            }
3286        }
3287        return null;
3288    }
3289
3290    @Override
3291    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3292        if (!sUserManager.exists(userId)) return null;
3293        flags = updateFlagsForComponent(flags, userId, component);
3294        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3295        synchronized (mPackages) {
3296            PackageParser.Provider p = mProviders.mProviders.get(component);
3297            if (DEBUG_PACKAGE_INFO) Log.v(
3298                TAG, "getProviderInfo " + component + ": " + p);
3299            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3300                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3301                if (ps == null) return null;
3302                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3303                        userId);
3304            }
3305        }
3306        return null;
3307    }
3308
3309    @Override
3310    public String[] getSystemSharedLibraryNames() {
3311        Set<String> libSet;
3312        synchronized (mPackages) {
3313            libSet = mSharedLibraries.keySet();
3314            int size = libSet.size();
3315            if (size > 0) {
3316                String[] libs = new String[size];
3317                libSet.toArray(libs);
3318                return libs;
3319            }
3320        }
3321        return null;
3322    }
3323
3324    /**
3325     * @hide
3326     */
3327    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3328        synchronized (mPackages) {
3329            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3330            if (lib != null && lib.apk != null) {
3331                return mPackages.get(lib.apk);
3332            }
3333        }
3334        return null;
3335    }
3336
3337    @Override
3338    public FeatureInfo[] getSystemAvailableFeatures() {
3339        Collection<FeatureInfo> featSet;
3340        synchronized (mPackages) {
3341            featSet = mAvailableFeatures.values();
3342            int size = featSet.size();
3343            if (size > 0) {
3344                FeatureInfo[] features = new FeatureInfo[size+1];
3345                featSet.toArray(features);
3346                FeatureInfo fi = new FeatureInfo();
3347                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3348                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3349                features[size] = fi;
3350                return features;
3351            }
3352        }
3353        return null;
3354    }
3355
3356    @Override
3357    public boolean hasSystemFeature(String name) {
3358        synchronized (mPackages) {
3359            return mAvailableFeatures.containsKey(name);
3360        }
3361    }
3362
3363    @Override
3364    public int checkPermission(String permName, String pkgName, int userId) {
3365        if (!sUserManager.exists(userId)) {
3366            return PackageManager.PERMISSION_DENIED;
3367        }
3368
3369        synchronized (mPackages) {
3370            final PackageParser.Package p = mPackages.get(pkgName);
3371            if (p != null && p.mExtras != null) {
3372                final PackageSetting ps = (PackageSetting) p.mExtras;
3373                final PermissionsState permissionsState = ps.getPermissionsState();
3374                if (permissionsState.hasPermission(permName, userId)) {
3375                    return PackageManager.PERMISSION_GRANTED;
3376                }
3377                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3378                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3379                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3380                    return PackageManager.PERMISSION_GRANTED;
3381                }
3382            }
3383        }
3384
3385        return PackageManager.PERMISSION_DENIED;
3386    }
3387
3388    @Override
3389    public int checkUidPermission(String permName, int uid) {
3390        final int userId = UserHandle.getUserId(uid);
3391
3392        if (!sUserManager.exists(userId)) {
3393            return PackageManager.PERMISSION_DENIED;
3394        }
3395
3396        synchronized (mPackages) {
3397            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3398            if (obj != null) {
3399                final SettingBase ps = (SettingBase) obj;
3400                final PermissionsState permissionsState = ps.getPermissionsState();
3401                if (permissionsState.hasPermission(permName, userId)) {
3402                    return PackageManager.PERMISSION_GRANTED;
3403                }
3404                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3405                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3406                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3407                    return PackageManager.PERMISSION_GRANTED;
3408                }
3409            } else {
3410                ArraySet<String> perms = mSystemPermissions.get(uid);
3411                if (perms != null) {
3412                    if (perms.contains(permName)) {
3413                        return PackageManager.PERMISSION_GRANTED;
3414                    }
3415                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3416                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3417                        return PackageManager.PERMISSION_GRANTED;
3418                    }
3419                }
3420            }
3421        }
3422
3423        return PackageManager.PERMISSION_DENIED;
3424    }
3425
3426    @Override
3427    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3428        if (UserHandle.getCallingUserId() != userId) {
3429            mContext.enforceCallingPermission(
3430                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3431                    "isPermissionRevokedByPolicy for user " + userId);
3432        }
3433
3434        if (checkPermission(permission, packageName, userId)
3435                == PackageManager.PERMISSION_GRANTED) {
3436            return false;
3437        }
3438
3439        final long identity = Binder.clearCallingIdentity();
3440        try {
3441            final int flags = getPermissionFlags(permission, packageName, userId);
3442            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3443        } finally {
3444            Binder.restoreCallingIdentity(identity);
3445        }
3446    }
3447
3448    @Override
3449    public String getPermissionControllerPackageName() {
3450        synchronized (mPackages) {
3451            return mRequiredInstallerPackage;
3452        }
3453    }
3454
3455    /**
3456     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3457     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3458     * @param checkShell TODO(yamasani):
3459     * @param message the message to log on security exception
3460     */
3461    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3462            boolean checkShell, String message) {
3463        if (userId < 0) {
3464            throw new IllegalArgumentException("Invalid userId " + userId);
3465        }
3466        if (checkShell) {
3467            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3468        }
3469        if (userId == UserHandle.getUserId(callingUid)) return;
3470        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3471            if (requireFullPermission) {
3472                mContext.enforceCallingOrSelfPermission(
3473                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3474            } else {
3475                try {
3476                    mContext.enforceCallingOrSelfPermission(
3477                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3478                } catch (SecurityException se) {
3479                    mContext.enforceCallingOrSelfPermission(
3480                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3481                }
3482            }
3483        }
3484    }
3485
3486    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3487        if (callingUid == Process.SHELL_UID) {
3488            if (userHandle >= 0
3489                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3490                throw new SecurityException("Shell does not have permission to access user "
3491                        + userHandle);
3492            } else if (userHandle < 0) {
3493                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3494                        + Debug.getCallers(3));
3495            }
3496        }
3497    }
3498
3499    private BasePermission findPermissionTreeLP(String permName) {
3500        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3501            if (permName.startsWith(bp.name) &&
3502                    permName.length() > bp.name.length() &&
3503                    permName.charAt(bp.name.length()) == '.') {
3504                return bp;
3505            }
3506        }
3507        return null;
3508    }
3509
3510    private BasePermission checkPermissionTreeLP(String permName) {
3511        if (permName != null) {
3512            BasePermission bp = findPermissionTreeLP(permName);
3513            if (bp != null) {
3514                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3515                    return bp;
3516                }
3517                throw new SecurityException("Calling uid "
3518                        + Binder.getCallingUid()
3519                        + " is not allowed to add to permission tree "
3520                        + bp.name + " owned by uid " + bp.uid);
3521            }
3522        }
3523        throw new SecurityException("No permission tree found for " + permName);
3524    }
3525
3526    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3527        if (s1 == null) {
3528            return s2 == null;
3529        }
3530        if (s2 == null) {
3531            return false;
3532        }
3533        if (s1.getClass() != s2.getClass()) {
3534            return false;
3535        }
3536        return s1.equals(s2);
3537    }
3538
3539    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3540        if (pi1.icon != pi2.icon) return false;
3541        if (pi1.logo != pi2.logo) return false;
3542        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3543        if (!compareStrings(pi1.name, pi2.name)) return false;
3544        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3545        // We'll take care of setting this one.
3546        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3547        // These are not currently stored in settings.
3548        //if (!compareStrings(pi1.group, pi2.group)) return false;
3549        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3550        //if (pi1.labelRes != pi2.labelRes) return false;
3551        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3552        return true;
3553    }
3554
3555    int permissionInfoFootprint(PermissionInfo info) {
3556        int size = info.name.length();
3557        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3558        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3559        return size;
3560    }
3561
3562    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3563        int size = 0;
3564        for (BasePermission perm : mSettings.mPermissions.values()) {
3565            if (perm.uid == tree.uid) {
3566                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3567            }
3568        }
3569        return size;
3570    }
3571
3572    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3573        // We calculate the max size of permissions defined by this uid and throw
3574        // if that plus the size of 'info' would exceed our stated maximum.
3575        if (tree.uid != Process.SYSTEM_UID) {
3576            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3577            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3578                throw new SecurityException("Permission tree size cap exceeded");
3579            }
3580        }
3581    }
3582
3583    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3584        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3585            throw new SecurityException("Label must be specified in permission");
3586        }
3587        BasePermission tree = checkPermissionTreeLP(info.name);
3588        BasePermission bp = mSettings.mPermissions.get(info.name);
3589        boolean added = bp == null;
3590        boolean changed = true;
3591        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3592        if (added) {
3593            enforcePermissionCapLocked(info, tree);
3594            bp = new BasePermission(info.name, tree.sourcePackage,
3595                    BasePermission.TYPE_DYNAMIC);
3596        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3597            throw new SecurityException(
3598                    "Not allowed to modify non-dynamic permission "
3599                    + info.name);
3600        } else {
3601            if (bp.protectionLevel == fixedLevel
3602                    && bp.perm.owner.equals(tree.perm.owner)
3603                    && bp.uid == tree.uid
3604                    && comparePermissionInfos(bp.perm.info, info)) {
3605                changed = false;
3606            }
3607        }
3608        bp.protectionLevel = fixedLevel;
3609        info = new PermissionInfo(info);
3610        info.protectionLevel = fixedLevel;
3611        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3612        bp.perm.info.packageName = tree.perm.info.packageName;
3613        bp.uid = tree.uid;
3614        if (added) {
3615            mSettings.mPermissions.put(info.name, bp);
3616        }
3617        if (changed) {
3618            if (!async) {
3619                mSettings.writeLPr();
3620            } else {
3621                scheduleWriteSettingsLocked();
3622            }
3623        }
3624        return added;
3625    }
3626
3627    @Override
3628    public boolean addPermission(PermissionInfo info) {
3629        synchronized (mPackages) {
3630            return addPermissionLocked(info, false);
3631        }
3632    }
3633
3634    @Override
3635    public boolean addPermissionAsync(PermissionInfo info) {
3636        synchronized (mPackages) {
3637            return addPermissionLocked(info, true);
3638        }
3639    }
3640
3641    @Override
3642    public void removePermission(String name) {
3643        synchronized (mPackages) {
3644            checkPermissionTreeLP(name);
3645            BasePermission bp = mSettings.mPermissions.get(name);
3646            if (bp != null) {
3647                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3648                    throw new SecurityException(
3649                            "Not allowed to modify non-dynamic permission "
3650                            + name);
3651                }
3652                mSettings.mPermissions.remove(name);
3653                mSettings.writeLPr();
3654            }
3655        }
3656    }
3657
3658    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3659            BasePermission bp) {
3660        int index = pkg.requestedPermissions.indexOf(bp.name);
3661        if (index == -1) {
3662            throw new SecurityException("Package " + pkg.packageName
3663                    + " has not requested permission " + bp.name);
3664        }
3665        if (!bp.isRuntime() && !bp.isDevelopment()) {
3666            throw new SecurityException("Permission " + bp.name
3667                    + " is not a changeable permission type");
3668        }
3669    }
3670
3671    @Override
3672    public void grantRuntimePermission(String packageName, String name, final int userId) {
3673        if (!sUserManager.exists(userId)) {
3674            Log.e(TAG, "No such user:" + userId);
3675            return;
3676        }
3677
3678        mContext.enforceCallingOrSelfPermission(
3679                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3680                "grantRuntimePermission");
3681
3682        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3683                "grantRuntimePermission");
3684
3685        final int uid;
3686        final SettingBase sb;
3687
3688        synchronized (mPackages) {
3689            final PackageParser.Package pkg = mPackages.get(packageName);
3690            if (pkg == null) {
3691                throw new IllegalArgumentException("Unknown package: " + packageName);
3692            }
3693
3694            final BasePermission bp = mSettings.mPermissions.get(name);
3695            if (bp == null) {
3696                throw new IllegalArgumentException("Unknown permission: " + name);
3697            }
3698
3699            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3700
3701            // If a permission review is required for legacy apps we represent
3702            // their permissions as always granted runtime ones since we need
3703            // to keep the review required permission flag per user while an
3704            // install permission's state is shared across all users.
3705            if (Build.PERMISSIONS_REVIEW_REQUIRED
3706                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3707                    && bp.isRuntime()) {
3708                return;
3709            }
3710
3711            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3712            sb = (SettingBase) pkg.mExtras;
3713            if (sb == null) {
3714                throw new IllegalArgumentException("Unknown package: " + packageName);
3715            }
3716
3717            final PermissionsState permissionsState = sb.getPermissionsState();
3718
3719            final int flags = permissionsState.getPermissionFlags(name, userId);
3720            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3721                throw new SecurityException("Cannot grant system fixed permission "
3722                        + name + " for package " + packageName);
3723            }
3724
3725            if (bp.isDevelopment()) {
3726                // Development permissions must be handled specially, since they are not
3727                // normal runtime permissions.  For now they apply to all users.
3728                if (permissionsState.grantInstallPermission(bp) !=
3729                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3730                    scheduleWriteSettingsLocked();
3731                }
3732                return;
3733            }
3734
3735            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3736                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3737                return;
3738            }
3739
3740            final int result = permissionsState.grantRuntimePermission(bp, userId);
3741            switch (result) {
3742                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3743                    return;
3744                }
3745
3746                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3747                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3748                    mHandler.post(new Runnable() {
3749                        @Override
3750                        public void run() {
3751                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3752                        }
3753                    });
3754                }
3755                break;
3756            }
3757
3758            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3759
3760            // Not critical if that is lost - app has to request again.
3761            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3762        }
3763
3764        // Only need to do this if user is initialized. Otherwise it's a new user
3765        // and there are no processes running as the user yet and there's no need
3766        // to make an expensive call to remount processes for the changed permissions.
3767        if (READ_EXTERNAL_STORAGE.equals(name)
3768                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3769            final long token = Binder.clearCallingIdentity();
3770            try {
3771                if (sUserManager.isInitialized(userId)) {
3772                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3773                            MountServiceInternal.class);
3774                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3775                }
3776            } finally {
3777                Binder.restoreCallingIdentity(token);
3778            }
3779        }
3780    }
3781
3782    @Override
3783    public void revokeRuntimePermission(String packageName, String name, int userId) {
3784        if (!sUserManager.exists(userId)) {
3785            Log.e(TAG, "No such user:" + userId);
3786            return;
3787        }
3788
3789        mContext.enforceCallingOrSelfPermission(
3790                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3791                "revokeRuntimePermission");
3792
3793        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3794                "revokeRuntimePermission");
3795
3796        final int appId;
3797
3798        synchronized (mPackages) {
3799            final PackageParser.Package pkg = mPackages.get(packageName);
3800            if (pkg == null) {
3801                throw new IllegalArgumentException("Unknown package: " + packageName);
3802            }
3803
3804            final BasePermission bp = mSettings.mPermissions.get(name);
3805            if (bp == null) {
3806                throw new IllegalArgumentException("Unknown permission: " + name);
3807            }
3808
3809            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3810
3811            // If a permission review is required for legacy apps we represent
3812            // their permissions as always granted runtime ones since we need
3813            // to keep the review required permission flag per user while an
3814            // install permission's state is shared across all users.
3815            if (Build.PERMISSIONS_REVIEW_REQUIRED
3816                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3817                    && bp.isRuntime()) {
3818                return;
3819            }
3820
3821            SettingBase sb = (SettingBase) pkg.mExtras;
3822            if (sb == null) {
3823                throw new IllegalArgumentException("Unknown package: " + packageName);
3824            }
3825
3826            final PermissionsState permissionsState = sb.getPermissionsState();
3827
3828            final int flags = permissionsState.getPermissionFlags(name, userId);
3829            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3830                throw new SecurityException("Cannot revoke system fixed permission "
3831                        + name + " for package " + packageName);
3832            }
3833
3834            if (bp.isDevelopment()) {
3835                // Development permissions must be handled specially, since they are not
3836                // normal runtime permissions.  For now they apply to all users.
3837                if (permissionsState.revokeInstallPermission(bp) !=
3838                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3839                    scheduleWriteSettingsLocked();
3840                }
3841                return;
3842            }
3843
3844            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3845                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3846                return;
3847            }
3848
3849            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3850
3851            // Critical, after this call app should never have the permission.
3852            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3853
3854            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3855        }
3856
3857        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3858    }
3859
3860    @Override
3861    public void resetRuntimePermissions() {
3862        mContext.enforceCallingOrSelfPermission(
3863                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3864                "revokeRuntimePermission");
3865
3866        int callingUid = Binder.getCallingUid();
3867        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3868            mContext.enforceCallingOrSelfPermission(
3869                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3870                    "resetRuntimePermissions");
3871        }
3872
3873        synchronized (mPackages) {
3874            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3875            for (int userId : UserManagerService.getInstance().getUserIds()) {
3876                final int packageCount = mPackages.size();
3877                for (int i = 0; i < packageCount; i++) {
3878                    PackageParser.Package pkg = mPackages.valueAt(i);
3879                    if (!(pkg.mExtras instanceof PackageSetting)) {
3880                        continue;
3881                    }
3882                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3883                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3884                }
3885            }
3886        }
3887    }
3888
3889    @Override
3890    public int getPermissionFlags(String name, String packageName, int userId) {
3891        if (!sUserManager.exists(userId)) {
3892            return 0;
3893        }
3894
3895        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3896
3897        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3898                "getPermissionFlags");
3899
3900        synchronized (mPackages) {
3901            final PackageParser.Package pkg = mPackages.get(packageName);
3902            if (pkg == null) {
3903                throw new IllegalArgumentException("Unknown package: " + packageName);
3904            }
3905
3906            final BasePermission bp = mSettings.mPermissions.get(name);
3907            if (bp == null) {
3908                throw new IllegalArgumentException("Unknown permission: " + name);
3909            }
3910
3911            SettingBase sb = (SettingBase) pkg.mExtras;
3912            if (sb == null) {
3913                throw new IllegalArgumentException("Unknown package: " + packageName);
3914            }
3915
3916            PermissionsState permissionsState = sb.getPermissionsState();
3917            return permissionsState.getPermissionFlags(name, userId);
3918        }
3919    }
3920
3921    @Override
3922    public void updatePermissionFlags(String name, String packageName, int flagMask,
3923            int flagValues, int userId) {
3924        if (!sUserManager.exists(userId)) {
3925            return;
3926        }
3927
3928        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3929
3930        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3931                "updatePermissionFlags");
3932
3933        // Only the system can change these flags and nothing else.
3934        if (getCallingUid() != Process.SYSTEM_UID) {
3935            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3936            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3937            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3938            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3939            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3940        }
3941
3942        synchronized (mPackages) {
3943            final PackageParser.Package pkg = mPackages.get(packageName);
3944            if (pkg == null) {
3945                throw new IllegalArgumentException("Unknown package: " + packageName);
3946            }
3947
3948            final BasePermission bp = mSettings.mPermissions.get(name);
3949            if (bp == null) {
3950                throw new IllegalArgumentException("Unknown permission: " + name);
3951            }
3952
3953            SettingBase sb = (SettingBase) pkg.mExtras;
3954            if (sb == null) {
3955                throw new IllegalArgumentException("Unknown package: " + packageName);
3956            }
3957
3958            PermissionsState permissionsState = sb.getPermissionsState();
3959
3960            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3961
3962            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3963                // Install and runtime permissions are stored in different places,
3964                // so figure out what permission changed and persist the change.
3965                if (permissionsState.getInstallPermissionState(name) != null) {
3966                    scheduleWriteSettingsLocked();
3967                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3968                        || hadState) {
3969                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3970                }
3971            }
3972        }
3973    }
3974
3975    /**
3976     * Update the permission flags for all packages and runtime permissions of a user in order
3977     * to allow device or profile owner to remove POLICY_FIXED.
3978     */
3979    @Override
3980    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3981        if (!sUserManager.exists(userId)) {
3982            return;
3983        }
3984
3985        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3986
3987        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3988                "updatePermissionFlagsForAllApps");
3989
3990        // Only the system can change system fixed flags.
3991        if (getCallingUid() != Process.SYSTEM_UID) {
3992            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3993            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3994        }
3995
3996        synchronized (mPackages) {
3997            boolean changed = false;
3998            final int packageCount = mPackages.size();
3999            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4000                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4001                SettingBase sb = (SettingBase) pkg.mExtras;
4002                if (sb == null) {
4003                    continue;
4004                }
4005                PermissionsState permissionsState = sb.getPermissionsState();
4006                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4007                        userId, flagMask, flagValues);
4008            }
4009            if (changed) {
4010                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4011            }
4012        }
4013    }
4014
4015    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4016        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4017                != PackageManager.PERMISSION_GRANTED
4018            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4019                != PackageManager.PERMISSION_GRANTED) {
4020            throw new SecurityException(message + " requires "
4021                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4022                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4023        }
4024    }
4025
4026    @Override
4027    public boolean shouldShowRequestPermissionRationale(String permissionName,
4028            String packageName, int userId) {
4029        if (UserHandle.getCallingUserId() != userId) {
4030            mContext.enforceCallingPermission(
4031                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4032                    "canShowRequestPermissionRationale for user " + userId);
4033        }
4034
4035        final int uid = getPackageUid(packageName, userId);
4036        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4037            return false;
4038        }
4039
4040        if (checkPermission(permissionName, packageName, userId)
4041                == PackageManager.PERMISSION_GRANTED) {
4042            return false;
4043        }
4044
4045        final int flags;
4046
4047        final long identity = Binder.clearCallingIdentity();
4048        try {
4049            flags = getPermissionFlags(permissionName,
4050                    packageName, userId);
4051        } finally {
4052            Binder.restoreCallingIdentity(identity);
4053        }
4054
4055        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4056                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4057                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4058
4059        if ((flags & fixedFlags) != 0) {
4060            return false;
4061        }
4062
4063        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4064    }
4065
4066    @Override
4067    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4068        mContext.enforceCallingOrSelfPermission(
4069                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4070                "addOnPermissionsChangeListener");
4071
4072        synchronized (mPackages) {
4073            mOnPermissionChangeListeners.addListenerLocked(listener);
4074        }
4075    }
4076
4077    @Override
4078    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4079        synchronized (mPackages) {
4080            mOnPermissionChangeListeners.removeListenerLocked(listener);
4081        }
4082    }
4083
4084    @Override
4085    public boolean isProtectedBroadcast(String actionName) {
4086        synchronized (mPackages) {
4087            if (mProtectedBroadcasts.contains(actionName)) {
4088                return true;
4089            } else if (actionName != null) {
4090                // TODO: remove these terrible hacks
4091                if (actionName.startsWith("android.net.netmon.lingerExpired")
4092                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4093                    return true;
4094                }
4095            }
4096        }
4097        return false;
4098    }
4099
4100    @Override
4101    public int checkSignatures(String pkg1, String pkg2) {
4102        synchronized (mPackages) {
4103            final PackageParser.Package p1 = mPackages.get(pkg1);
4104            final PackageParser.Package p2 = mPackages.get(pkg2);
4105            if (p1 == null || p1.mExtras == null
4106                    || p2 == null || p2.mExtras == null) {
4107                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4108            }
4109            return compareSignatures(p1.mSignatures, p2.mSignatures);
4110        }
4111    }
4112
4113    @Override
4114    public int checkUidSignatures(int uid1, int uid2) {
4115        // Map to base uids.
4116        uid1 = UserHandle.getAppId(uid1);
4117        uid2 = UserHandle.getAppId(uid2);
4118        // reader
4119        synchronized (mPackages) {
4120            Signature[] s1;
4121            Signature[] s2;
4122            Object obj = mSettings.getUserIdLPr(uid1);
4123            if (obj != null) {
4124                if (obj instanceof SharedUserSetting) {
4125                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4126                } else if (obj instanceof PackageSetting) {
4127                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4128                } else {
4129                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4130                }
4131            } else {
4132                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4133            }
4134            obj = mSettings.getUserIdLPr(uid2);
4135            if (obj != null) {
4136                if (obj instanceof SharedUserSetting) {
4137                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4138                } else if (obj instanceof PackageSetting) {
4139                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4140                } else {
4141                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4142                }
4143            } else {
4144                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4145            }
4146            return compareSignatures(s1, s2);
4147        }
4148    }
4149
4150    private void killUid(int appId, int userId, String reason) {
4151        final long identity = Binder.clearCallingIdentity();
4152        try {
4153            IActivityManager am = ActivityManagerNative.getDefault();
4154            if (am != null) {
4155                try {
4156                    am.killUid(appId, userId, reason);
4157                } catch (RemoteException e) {
4158                    /* ignore - same process */
4159                }
4160            }
4161        } finally {
4162            Binder.restoreCallingIdentity(identity);
4163        }
4164    }
4165
4166    /**
4167     * Compares two sets of signatures. Returns:
4168     * <br />
4169     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4170     * <br />
4171     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4172     * <br />
4173     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4174     * <br />
4175     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4176     * <br />
4177     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4178     */
4179    static int compareSignatures(Signature[] s1, Signature[] s2) {
4180        if (s1 == null) {
4181            return s2 == null
4182                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4183                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4184        }
4185
4186        if (s2 == null) {
4187            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4188        }
4189
4190        if (s1.length != s2.length) {
4191            return PackageManager.SIGNATURE_NO_MATCH;
4192        }
4193
4194        // Since both signature sets are of size 1, we can compare without HashSets.
4195        if (s1.length == 1) {
4196            return s1[0].equals(s2[0]) ?
4197                    PackageManager.SIGNATURE_MATCH :
4198                    PackageManager.SIGNATURE_NO_MATCH;
4199        }
4200
4201        ArraySet<Signature> set1 = new ArraySet<Signature>();
4202        for (Signature sig : s1) {
4203            set1.add(sig);
4204        }
4205        ArraySet<Signature> set2 = new ArraySet<Signature>();
4206        for (Signature sig : s2) {
4207            set2.add(sig);
4208        }
4209        // Make sure s2 contains all signatures in s1.
4210        if (set1.equals(set2)) {
4211            return PackageManager.SIGNATURE_MATCH;
4212        }
4213        return PackageManager.SIGNATURE_NO_MATCH;
4214    }
4215
4216    /**
4217     * If the database version for this type of package (internal storage or
4218     * external storage) is less than the version where package signatures
4219     * were updated, return true.
4220     */
4221    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4222        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4223        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4224    }
4225
4226    /**
4227     * Used for backward compatibility to make sure any packages with
4228     * certificate chains get upgraded to the new style. {@code existingSigs}
4229     * will be in the old format (since they were stored on disk from before the
4230     * system upgrade) and {@code scannedSigs} will be in the newer format.
4231     */
4232    private int compareSignaturesCompat(PackageSignatures existingSigs,
4233            PackageParser.Package scannedPkg) {
4234        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4235            return PackageManager.SIGNATURE_NO_MATCH;
4236        }
4237
4238        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4239        for (Signature sig : existingSigs.mSignatures) {
4240            existingSet.add(sig);
4241        }
4242        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4243        for (Signature sig : scannedPkg.mSignatures) {
4244            try {
4245                Signature[] chainSignatures = sig.getChainSignatures();
4246                for (Signature chainSig : chainSignatures) {
4247                    scannedCompatSet.add(chainSig);
4248                }
4249            } catch (CertificateEncodingException e) {
4250                scannedCompatSet.add(sig);
4251            }
4252        }
4253        /*
4254         * Make sure the expanded scanned set contains all signatures in the
4255         * existing one.
4256         */
4257        if (scannedCompatSet.equals(existingSet)) {
4258            // Migrate the old signatures to the new scheme.
4259            existingSigs.assignSignatures(scannedPkg.mSignatures);
4260            // The new KeySets will be re-added later in the scanning process.
4261            synchronized (mPackages) {
4262                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4263            }
4264            return PackageManager.SIGNATURE_MATCH;
4265        }
4266        return PackageManager.SIGNATURE_NO_MATCH;
4267    }
4268
4269    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4270        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4271        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4272    }
4273
4274    private int compareSignaturesRecover(PackageSignatures existingSigs,
4275            PackageParser.Package scannedPkg) {
4276        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4277            return PackageManager.SIGNATURE_NO_MATCH;
4278        }
4279
4280        String msg = null;
4281        try {
4282            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4283                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4284                        + scannedPkg.packageName);
4285                return PackageManager.SIGNATURE_MATCH;
4286            }
4287        } catch (CertificateException e) {
4288            msg = e.getMessage();
4289        }
4290
4291        logCriticalInfo(Log.INFO,
4292                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4293        return PackageManager.SIGNATURE_NO_MATCH;
4294    }
4295
4296    @Override
4297    public String[] getPackagesForUid(int uid) {
4298        uid = UserHandle.getAppId(uid);
4299        // reader
4300        synchronized (mPackages) {
4301            Object obj = mSettings.getUserIdLPr(uid);
4302            if (obj instanceof SharedUserSetting) {
4303                final SharedUserSetting sus = (SharedUserSetting) obj;
4304                final int N = sus.packages.size();
4305                final String[] res = new String[N];
4306                final Iterator<PackageSetting> it = sus.packages.iterator();
4307                int i = 0;
4308                while (it.hasNext()) {
4309                    res[i++] = it.next().name;
4310                }
4311                return res;
4312            } else if (obj instanceof PackageSetting) {
4313                final PackageSetting ps = (PackageSetting) obj;
4314                return new String[] { ps.name };
4315            }
4316        }
4317        return null;
4318    }
4319
4320    @Override
4321    public String getNameForUid(int uid) {
4322        // reader
4323        synchronized (mPackages) {
4324            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4325            if (obj instanceof SharedUserSetting) {
4326                final SharedUserSetting sus = (SharedUserSetting) obj;
4327                return sus.name + ":" + sus.userId;
4328            } else if (obj instanceof PackageSetting) {
4329                final PackageSetting ps = (PackageSetting) obj;
4330                return ps.name;
4331            }
4332        }
4333        return null;
4334    }
4335
4336    @Override
4337    public int getUidForSharedUser(String sharedUserName) {
4338        if(sharedUserName == null) {
4339            return -1;
4340        }
4341        // reader
4342        synchronized (mPackages) {
4343            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4344            if (suid == null) {
4345                return -1;
4346            }
4347            return suid.userId;
4348        }
4349    }
4350
4351    @Override
4352    public int getFlagsForUid(int uid) {
4353        synchronized (mPackages) {
4354            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4355            if (obj instanceof SharedUserSetting) {
4356                final SharedUserSetting sus = (SharedUserSetting) obj;
4357                return sus.pkgFlags;
4358            } else if (obj instanceof PackageSetting) {
4359                final PackageSetting ps = (PackageSetting) obj;
4360                return ps.pkgFlags;
4361            }
4362        }
4363        return 0;
4364    }
4365
4366    @Override
4367    public int getPrivateFlagsForUid(int uid) {
4368        synchronized (mPackages) {
4369            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4370            if (obj instanceof SharedUserSetting) {
4371                final SharedUserSetting sus = (SharedUserSetting) obj;
4372                return sus.pkgPrivateFlags;
4373            } else if (obj instanceof PackageSetting) {
4374                final PackageSetting ps = (PackageSetting) obj;
4375                return ps.pkgPrivateFlags;
4376            }
4377        }
4378        return 0;
4379    }
4380
4381    @Override
4382    public boolean isUidPrivileged(int uid) {
4383        uid = UserHandle.getAppId(uid);
4384        // reader
4385        synchronized (mPackages) {
4386            Object obj = mSettings.getUserIdLPr(uid);
4387            if (obj instanceof SharedUserSetting) {
4388                final SharedUserSetting sus = (SharedUserSetting) obj;
4389                final Iterator<PackageSetting> it = sus.packages.iterator();
4390                while (it.hasNext()) {
4391                    if (it.next().isPrivileged()) {
4392                        return true;
4393                    }
4394                }
4395            } else if (obj instanceof PackageSetting) {
4396                final PackageSetting ps = (PackageSetting) obj;
4397                return ps.isPrivileged();
4398            }
4399        }
4400        return false;
4401    }
4402
4403    @Override
4404    public String[] getAppOpPermissionPackages(String permissionName) {
4405        synchronized (mPackages) {
4406            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4407            if (pkgs == null) {
4408                return null;
4409            }
4410            return pkgs.toArray(new String[pkgs.size()]);
4411        }
4412    }
4413
4414    @Override
4415    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4416            int flags, int userId) {
4417        if (!sUserManager.exists(userId)) return null;
4418        flags = updateFlagsForResolve(flags, userId, intent);
4419        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4420        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4421        final ResolveInfo bestChoice =
4422                chooseBestActivity(intent, resolvedType, flags, query, userId);
4423
4424        if (isEphemeralAllowed(intent, query, userId)) {
4425            final EphemeralResolveInfo ai =
4426                    getEphemeralResolveInfo(intent, resolvedType, userId);
4427            if (ai != null) {
4428                if (DEBUG_EPHEMERAL) {
4429                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4430                }
4431                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4432                bestChoice.ephemeralResolveInfo = ai;
4433            }
4434        }
4435        return bestChoice;
4436    }
4437
4438    @Override
4439    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4440            IntentFilter filter, int match, ComponentName activity) {
4441        final int userId = UserHandle.getCallingUserId();
4442        if (DEBUG_PREFERRED) {
4443            Log.v(TAG, "setLastChosenActivity intent=" + intent
4444                + " resolvedType=" + resolvedType
4445                + " flags=" + flags
4446                + " filter=" + filter
4447                + " match=" + match
4448                + " activity=" + activity);
4449            filter.dump(new PrintStreamPrinter(System.out), "    ");
4450        }
4451        intent.setComponent(null);
4452        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4453        // Find any earlier preferred or last chosen entries and nuke them
4454        findPreferredActivity(intent, resolvedType,
4455                flags, query, 0, false, true, false, userId);
4456        // Add the new activity as the last chosen for this filter
4457        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4458                "Setting last chosen");
4459    }
4460
4461    @Override
4462    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4463        final int userId = UserHandle.getCallingUserId();
4464        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4465        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4466        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4467                false, false, false, userId);
4468    }
4469
4470
4471    private boolean isEphemeralAllowed(
4472            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4473        // Short circuit and return early if possible.
4474        final int callingUser = UserHandle.getCallingUserId();
4475        if (callingUser != UserHandle.USER_SYSTEM) {
4476            return false;
4477        }
4478        if (mEphemeralResolverConnection == null) {
4479            return false;
4480        }
4481        if (intent.getComponent() != null) {
4482            return false;
4483        }
4484        if (intent.getPackage() != null) {
4485            return false;
4486        }
4487        final boolean isWebUri = hasWebURI(intent);
4488        if (!isWebUri) {
4489            return false;
4490        }
4491        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4492        synchronized (mPackages) {
4493            final int count = resolvedActivites.size();
4494            for (int n = 0; n < count; n++) {
4495                ResolveInfo info = resolvedActivites.get(n);
4496                String packageName = info.activityInfo.packageName;
4497                PackageSetting ps = mSettings.mPackages.get(packageName);
4498                if (ps != null) {
4499                    // Try to get the status from User settings first
4500                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4501                    int status = (int) (packedStatus >> 32);
4502                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4503                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4504                        if (DEBUG_EPHEMERAL) {
4505                            Slog.v(TAG, "DENY ephemeral apps;"
4506                                + " pkg: " + packageName + ", status: " + status);
4507                        }
4508                        return false;
4509                    }
4510                }
4511            }
4512        }
4513        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4514        return true;
4515    }
4516
4517    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4518            int userId) {
4519        MessageDigest digest = null;
4520        try {
4521            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4522        } catch (NoSuchAlgorithmException e) {
4523            // If we can't create a digest, ignore ephemeral apps.
4524            return null;
4525        }
4526
4527        final byte[] hostBytes = intent.getData().getHost().getBytes();
4528        final byte[] digestBytes = digest.digest(hostBytes);
4529        int shaPrefix =
4530                digestBytes[0] << 24
4531                | digestBytes[1] << 16
4532                | digestBytes[2] << 8
4533                | digestBytes[3] << 0;
4534        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4535                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4536        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4537            // No hash prefix match; there are no ephemeral apps for this domain.
4538            return null;
4539        }
4540        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4541            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4542            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4543                continue;
4544            }
4545            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4546            // No filters; this should never happen.
4547            if (filters.isEmpty()) {
4548                continue;
4549            }
4550            // We have a domain match; resolve the filters to see if anything matches.
4551            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4552            for (int j = filters.size() - 1; j >= 0; --j) {
4553                final EphemeralResolveIntentInfo intentInfo =
4554                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4555                ephemeralResolver.addFilter(intentInfo);
4556            }
4557            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4558                    intent, resolvedType, false /*defaultOnly*/, userId);
4559            if (!matchedResolveInfoList.isEmpty()) {
4560                return matchedResolveInfoList.get(0);
4561            }
4562        }
4563        // Hash or filter mis-match; no ephemeral apps for this domain.
4564        return null;
4565    }
4566
4567    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4568            int flags, List<ResolveInfo> query, int userId) {
4569        if (query != null) {
4570            final int N = query.size();
4571            if (N == 1) {
4572                return query.get(0);
4573            } else if (N > 1) {
4574                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4575                // If there is more than one activity with the same priority,
4576                // then let the user decide between them.
4577                ResolveInfo r0 = query.get(0);
4578                ResolveInfo r1 = query.get(1);
4579                if (DEBUG_INTENT_MATCHING || debug) {
4580                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4581                            + r1.activityInfo.name + "=" + r1.priority);
4582                }
4583                // If the first activity has a higher priority, or a different
4584                // default, then it is always desirable to pick it.
4585                if (r0.priority != r1.priority
4586                        || r0.preferredOrder != r1.preferredOrder
4587                        || r0.isDefault != r1.isDefault) {
4588                    return query.get(0);
4589                }
4590                // If we have saved a preference for a preferred activity for
4591                // this Intent, use that.
4592                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4593                        flags, query, r0.priority, true, false, debug, userId);
4594                if (ri != null) {
4595                    return ri;
4596                }
4597                ri = new ResolveInfo(mResolveInfo);
4598                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4599                ri.activityInfo.applicationInfo = new ApplicationInfo(
4600                        ri.activityInfo.applicationInfo);
4601                if (userId != 0) {
4602                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4603                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4604                }
4605                // Make sure that the resolver is displayable in car mode
4606                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4607                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4608                return ri;
4609            }
4610        }
4611        return null;
4612    }
4613
4614    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4615            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4616        final int N = query.size();
4617        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4618                .get(userId);
4619        // Get the list of persistent preferred activities that handle the intent
4620        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4621        List<PersistentPreferredActivity> pprefs = ppir != null
4622                ? ppir.queryIntent(intent, resolvedType,
4623                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4624                : null;
4625        if (pprefs != null && pprefs.size() > 0) {
4626            final int M = pprefs.size();
4627            for (int i=0; i<M; i++) {
4628                final PersistentPreferredActivity ppa = pprefs.get(i);
4629                if (DEBUG_PREFERRED || debug) {
4630                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4631                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4632                            + "\n  component=" + ppa.mComponent);
4633                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4634                }
4635                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4636                        flags | MATCH_DISABLED_COMPONENTS, userId);
4637                if (DEBUG_PREFERRED || debug) {
4638                    Slog.v(TAG, "Found persistent preferred activity:");
4639                    if (ai != null) {
4640                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4641                    } else {
4642                        Slog.v(TAG, "  null");
4643                    }
4644                }
4645                if (ai == null) {
4646                    // This previously registered persistent preferred activity
4647                    // component is no longer known. Ignore it and do NOT remove it.
4648                    continue;
4649                }
4650                for (int j=0; j<N; j++) {
4651                    final ResolveInfo ri = query.get(j);
4652                    if (!ri.activityInfo.applicationInfo.packageName
4653                            .equals(ai.applicationInfo.packageName)) {
4654                        continue;
4655                    }
4656                    if (!ri.activityInfo.name.equals(ai.name)) {
4657                        continue;
4658                    }
4659                    //  Found a persistent preference that can handle the intent.
4660                    if (DEBUG_PREFERRED || debug) {
4661                        Slog.v(TAG, "Returning persistent preferred activity: " +
4662                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4663                    }
4664                    return ri;
4665                }
4666            }
4667        }
4668        return null;
4669    }
4670
4671    // TODO: handle preferred activities missing while user has amnesia
4672    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4673            List<ResolveInfo> query, int priority, boolean always,
4674            boolean removeMatches, boolean debug, int userId) {
4675        if (!sUserManager.exists(userId)) return null;
4676        flags = updateFlagsForResolve(flags, userId, intent);
4677        // writer
4678        synchronized (mPackages) {
4679            if (intent.getSelector() != null) {
4680                intent = intent.getSelector();
4681            }
4682            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4683
4684            // Try to find a matching persistent preferred activity.
4685            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4686                    debug, userId);
4687
4688            // If a persistent preferred activity matched, use it.
4689            if (pri != null) {
4690                return pri;
4691            }
4692
4693            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4694            // Get the list of preferred activities that handle the intent
4695            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4696            List<PreferredActivity> prefs = pir != null
4697                    ? pir.queryIntent(intent, resolvedType,
4698                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4699                    : null;
4700            if (prefs != null && prefs.size() > 0) {
4701                boolean changed = false;
4702                try {
4703                    // First figure out how good the original match set is.
4704                    // We will only allow preferred activities that came
4705                    // from the same match quality.
4706                    int match = 0;
4707
4708                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4709
4710                    final int N = query.size();
4711                    for (int j=0; j<N; j++) {
4712                        final ResolveInfo ri = query.get(j);
4713                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4714                                + ": 0x" + Integer.toHexString(match));
4715                        if (ri.match > match) {
4716                            match = ri.match;
4717                        }
4718                    }
4719
4720                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4721                            + Integer.toHexString(match));
4722
4723                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4724                    final int M = prefs.size();
4725                    for (int i=0; i<M; i++) {
4726                        final PreferredActivity pa = prefs.get(i);
4727                        if (DEBUG_PREFERRED || debug) {
4728                            Slog.v(TAG, "Checking PreferredActivity ds="
4729                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4730                                    + "\n  component=" + pa.mPref.mComponent);
4731                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4732                        }
4733                        if (pa.mPref.mMatch != match) {
4734                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4735                                    + Integer.toHexString(pa.mPref.mMatch));
4736                            continue;
4737                        }
4738                        // If it's not an "always" type preferred activity and that's what we're
4739                        // looking for, skip it.
4740                        if (always && !pa.mPref.mAlways) {
4741                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4742                            continue;
4743                        }
4744                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4745                                flags | MATCH_DISABLED_COMPONENTS, userId);
4746                        if (DEBUG_PREFERRED || debug) {
4747                            Slog.v(TAG, "Found preferred activity:");
4748                            if (ai != null) {
4749                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4750                            } else {
4751                                Slog.v(TAG, "  null");
4752                            }
4753                        }
4754                        if (ai == null) {
4755                            // This previously registered preferred activity
4756                            // component is no longer known.  Most likely an update
4757                            // to the app was installed and in the new version this
4758                            // component no longer exists.  Clean it up by removing
4759                            // it from the preferred activities list, and skip it.
4760                            Slog.w(TAG, "Removing dangling preferred activity: "
4761                                    + pa.mPref.mComponent);
4762                            pir.removeFilter(pa);
4763                            changed = true;
4764                            continue;
4765                        }
4766                        for (int j=0; j<N; j++) {
4767                            final ResolveInfo ri = query.get(j);
4768                            if (!ri.activityInfo.applicationInfo.packageName
4769                                    .equals(ai.applicationInfo.packageName)) {
4770                                continue;
4771                            }
4772                            if (!ri.activityInfo.name.equals(ai.name)) {
4773                                continue;
4774                            }
4775
4776                            if (removeMatches) {
4777                                pir.removeFilter(pa);
4778                                changed = true;
4779                                if (DEBUG_PREFERRED) {
4780                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4781                                }
4782                                break;
4783                            }
4784
4785                            // Okay we found a previously set preferred or last chosen app.
4786                            // If the result set is different from when this
4787                            // was created, we need to clear it and re-ask the
4788                            // user their preference, if we're looking for an "always" type entry.
4789                            if (always && !pa.mPref.sameSet(query)) {
4790                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4791                                        + intent + " type " + resolvedType);
4792                                if (DEBUG_PREFERRED) {
4793                                    Slog.v(TAG, "Removing preferred activity since set changed "
4794                                            + pa.mPref.mComponent);
4795                                }
4796                                pir.removeFilter(pa);
4797                                // Re-add the filter as a "last chosen" entry (!always)
4798                                PreferredActivity lastChosen = new PreferredActivity(
4799                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4800                                pir.addFilter(lastChosen);
4801                                changed = true;
4802                                return null;
4803                            }
4804
4805                            // Yay! Either the set matched or we're looking for the last chosen
4806                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4807                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4808                            return ri;
4809                        }
4810                    }
4811                } finally {
4812                    if (changed) {
4813                        if (DEBUG_PREFERRED) {
4814                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4815                        }
4816                        scheduleWritePackageRestrictionsLocked(userId);
4817                    }
4818                }
4819            }
4820        }
4821        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4822        return null;
4823    }
4824
4825    /*
4826     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4827     */
4828    @Override
4829    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4830            int targetUserId) {
4831        mContext.enforceCallingOrSelfPermission(
4832                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4833        List<CrossProfileIntentFilter> matches =
4834                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4835        if (matches != null) {
4836            int size = matches.size();
4837            for (int i = 0; i < size; i++) {
4838                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4839            }
4840        }
4841        if (hasWebURI(intent)) {
4842            // cross-profile app linking works only towards the parent.
4843            final UserInfo parent = getProfileParent(sourceUserId);
4844            synchronized(mPackages) {
4845                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4846                        intent, resolvedType, 0, sourceUserId, parent.id);
4847                return xpDomainInfo != null;
4848            }
4849        }
4850        return false;
4851    }
4852
4853    private UserInfo getProfileParent(int userId) {
4854        final long identity = Binder.clearCallingIdentity();
4855        try {
4856            return sUserManager.getProfileParent(userId);
4857        } finally {
4858            Binder.restoreCallingIdentity(identity);
4859        }
4860    }
4861
4862    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4863            String resolvedType, int userId) {
4864        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4865        if (resolver != null) {
4866            return resolver.queryIntent(intent, resolvedType, false, userId);
4867        }
4868        return null;
4869    }
4870
4871    @Override
4872    public List<ResolveInfo> queryIntentActivities(Intent intent,
4873            String resolvedType, int flags, int userId) {
4874        if (!sUserManager.exists(userId)) return Collections.emptyList();
4875        flags = updateFlagsForResolve(flags, userId, intent);
4876        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4877        ComponentName comp = intent.getComponent();
4878        if (comp == null) {
4879            if (intent.getSelector() != null) {
4880                intent = intent.getSelector();
4881                comp = intent.getComponent();
4882            }
4883        }
4884
4885        if (comp != null) {
4886            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4887            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4888            if (ai != null) {
4889                final ResolveInfo ri = new ResolveInfo();
4890                ri.activityInfo = ai;
4891                list.add(ri);
4892            }
4893            return list;
4894        }
4895
4896        // reader
4897        synchronized (mPackages) {
4898            final String pkgName = intent.getPackage();
4899            if (pkgName == null) {
4900                List<CrossProfileIntentFilter> matchingFilters =
4901                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4902                // Check for results that need to skip the current profile.
4903                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4904                        resolvedType, flags, userId);
4905                if (xpResolveInfo != null) {
4906                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4907                    result.add(xpResolveInfo);
4908                    return filterIfNotSystemUser(result, userId);
4909                }
4910
4911                // Check for results in the current profile.
4912                List<ResolveInfo> result = mActivities.queryIntent(
4913                        intent, resolvedType, flags, userId);
4914                result = filterIfNotSystemUser(result, userId);
4915
4916                // Check for cross profile results.
4917                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4918                xpResolveInfo = queryCrossProfileIntents(
4919                        matchingFilters, intent, resolvedType, flags, userId,
4920                        hasNonNegativePriorityResult);
4921                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4922                    boolean isVisibleToUser = filterIfNotSystemUser(
4923                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4924                    if (isVisibleToUser) {
4925                        result.add(xpResolveInfo);
4926                        Collections.sort(result, mResolvePrioritySorter);
4927                    }
4928                }
4929                if (hasWebURI(intent)) {
4930                    CrossProfileDomainInfo xpDomainInfo = null;
4931                    final UserInfo parent = getProfileParent(userId);
4932                    if (parent != null) {
4933                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4934                                flags, userId, parent.id);
4935                    }
4936                    if (xpDomainInfo != null) {
4937                        if (xpResolveInfo != null) {
4938                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4939                            // in the result.
4940                            result.remove(xpResolveInfo);
4941                        }
4942                        if (result.size() == 0) {
4943                            result.add(xpDomainInfo.resolveInfo);
4944                            return result;
4945                        }
4946                    } else if (result.size() <= 1) {
4947                        return result;
4948                    }
4949                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4950                            xpDomainInfo, userId);
4951                    Collections.sort(result, mResolvePrioritySorter);
4952                }
4953                return result;
4954            }
4955            final PackageParser.Package pkg = mPackages.get(pkgName);
4956            if (pkg != null) {
4957                return filterIfNotSystemUser(
4958                        mActivities.queryIntentForPackage(
4959                                intent, resolvedType, flags, pkg.activities, userId),
4960                        userId);
4961            }
4962            return new ArrayList<ResolveInfo>();
4963        }
4964    }
4965
4966    private static class CrossProfileDomainInfo {
4967        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4968        ResolveInfo resolveInfo;
4969        /* Best domain verification status of the activities found in the other profile */
4970        int bestDomainVerificationStatus;
4971    }
4972
4973    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4974            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4975        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4976                sourceUserId)) {
4977            return null;
4978        }
4979        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4980                resolvedType, flags, parentUserId);
4981
4982        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4983            return null;
4984        }
4985        CrossProfileDomainInfo result = null;
4986        int size = resultTargetUser.size();
4987        for (int i = 0; i < size; i++) {
4988            ResolveInfo riTargetUser = resultTargetUser.get(i);
4989            // Intent filter verification is only for filters that specify a host. So don't return
4990            // those that handle all web uris.
4991            if (riTargetUser.handleAllWebDataURI) {
4992                continue;
4993            }
4994            String packageName = riTargetUser.activityInfo.packageName;
4995            PackageSetting ps = mSettings.mPackages.get(packageName);
4996            if (ps == null) {
4997                continue;
4998            }
4999            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5000            int status = (int)(verificationState >> 32);
5001            if (result == null) {
5002                result = new CrossProfileDomainInfo();
5003                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5004                        sourceUserId, parentUserId);
5005                result.bestDomainVerificationStatus = status;
5006            } else {
5007                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5008                        result.bestDomainVerificationStatus);
5009            }
5010        }
5011        // Don't consider matches with status NEVER across profiles.
5012        if (result != null && result.bestDomainVerificationStatus
5013                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5014            return null;
5015        }
5016        return result;
5017    }
5018
5019    /**
5020     * Verification statuses are ordered from the worse to the best, except for
5021     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5022     */
5023    private int bestDomainVerificationStatus(int status1, int status2) {
5024        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5025            return status2;
5026        }
5027        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5028            return status1;
5029        }
5030        return (int) MathUtils.max(status1, status2);
5031    }
5032
5033    private boolean isUserEnabled(int userId) {
5034        long callingId = Binder.clearCallingIdentity();
5035        try {
5036            UserInfo userInfo = sUserManager.getUserInfo(userId);
5037            return userInfo != null && userInfo.isEnabled();
5038        } finally {
5039            Binder.restoreCallingIdentity(callingId);
5040        }
5041    }
5042
5043    /**
5044     * Filter out activities with systemUserOnly flag set, when current user is not System.
5045     *
5046     * @return filtered list
5047     */
5048    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5049        if (userId == UserHandle.USER_SYSTEM) {
5050            return resolveInfos;
5051        }
5052        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5053            ResolveInfo info = resolveInfos.get(i);
5054            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5055                resolveInfos.remove(i);
5056            }
5057        }
5058        return resolveInfos;
5059    }
5060
5061    /**
5062     * @param resolveInfos list of resolve infos in descending priority order
5063     * @return if the list contains a resolve info with non-negative priority
5064     */
5065    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5066        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5067    }
5068
5069    private static boolean hasWebURI(Intent intent) {
5070        if (intent.getData() == null) {
5071            return false;
5072        }
5073        final String scheme = intent.getScheme();
5074        if (TextUtils.isEmpty(scheme)) {
5075            return false;
5076        }
5077        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5078    }
5079
5080    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5081            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5082            int userId) {
5083        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5084
5085        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5086            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5087                    candidates.size());
5088        }
5089
5090        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5091        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5092        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5093        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5094        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5095        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5096
5097        synchronized (mPackages) {
5098            final int count = candidates.size();
5099            // First, try to use linked apps. Partition the candidates into four lists:
5100            // one for the final results, one for the "do not use ever", one for "undefined status"
5101            // and finally one for "browser app type".
5102            for (int n=0; n<count; n++) {
5103                ResolveInfo info = candidates.get(n);
5104                String packageName = info.activityInfo.packageName;
5105                PackageSetting ps = mSettings.mPackages.get(packageName);
5106                if (ps != null) {
5107                    // Add to the special match all list (Browser use case)
5108                    if (info.handleAllWebDataURI) {
5109                        matchAllList.add(info);
5110                        continue;
5111                    }
5112                    // Try to get the status from User settings first
5113                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5114                    int status = (int)(packedStatus >> 32);
5115                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5116                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5117                        if (DEBUG_DOMAIN_VERIFICATION) {
5118                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5119                                    + " : linkgen=" + linkGeneration);
5120                        }
5121                        // Use link-enabled generation as preferredOrder, i.e.
5122                        // prefer newly-enabled over earlier-enabled.
5123                        info.preferredOrder = linkGeneration;
5124                        alwaysList.add(info);
5125                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5126                        if (DEBUG_DOMAIN_VERIFICATION) {
5127                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5128                        }
5129                        neverList.add(info);
5130                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5131                        if (DEBUG_DOMAIN_VERIFICATION) {
5132                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5133                        }
5134                        alwaysAskList.add(info);
5135                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5136                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5137                        if (DEBUG_DOMAIN_VERIFICATION) {
5138                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5139                        }
5140                        undefinedList.add(info);
5141                    }
5142                }
5143            }
5144
5145            // We'll want to include browser possibilities in a few cases
5146            boolean includeBrowser = false;
5147
5148            // First try to add the "always" resolution(s) for the current user, if any
5149            if (alwaysList.size() > 0) {
5150                result.addAll(alwaysList);
5151            } else {
5152                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5153                result.addAll(undefinedList);
5154                // Maybe add one for the other profile.
5155                if (xpDomainInfo != null && (
5156                        xpDomainInfo.bestDomainVerificationStatus
5157                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5158                    result.add(xpDomainInfo.resolveInfo);
5159                }
5160                includeBrowser = true;
5161            }
5162
5163            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5164            // If there were 'always' entries their preferred order has been set, so we also
5165            // back that off to make the alternatives equivalent
5166            if (alwaysAskList.size() > 0) {
5167                for (ResolveInfo i : result) {
5168                    i.preferredOrder = 0;
5169                }
5170                result.addAll(alwaysAskList);
5171                includeBrowser = true;
5172            }
5173
5174            if (includeBrowser) {
5175                // Also add browsers (all of them or only the default one)
5176                if (DEBUG_DOMAIN_VERIFICATION) {
5177                    Slog.v(TAG, "   ...including browsers in candidate set");
5178                }
5179                if ((matchFlags & MATCH_ALL) != 0) {
5180                    result.addAll(matchAllList);
5181                } else {
5182                    // Browser/generic handling case.  If there's a default browser, go straight
5183                    // to that (but only if there is no other higher-priority match).
5184                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5185                    int maxMatchPrio = 0;
5186                    ResolveInfo defaultBrowserMatch = null;
5187                    final int numCandidates = matchAllList.size();
5188                    for (int n = 0; n < numCandidates; n++) {
5189                        ResolveInfo info = matchAllList.get(n);
5190                        // track the highest overall match priority...
5191                        if (info.priority > maxMatchPrio) {
5192                            maxMatchPrio = info.priority;
5193                        }
5194                        // ...and the highest-priority default browser match
5195                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5196                            if (defaultBrowserMatch == null
5197                                    || (defaultBrowserMatch.priority < info.priority)) {
5198                                if (debug) {
5199                                    Slog.v(TAG, "Considering default browser match " + info);
5200                                }
5201                                defaultBrowserMatch = info;
5202                            }
5203                        }
5204                    }
5205                    if (defaultBrowserMatch != null
5206                            && defaultBrowserMatch.priority >= maxMatchPrio
5207                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5208                    {
5209                        if (debug) {
5210                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5211                        }
5212                        result.add(defaultBrowserMatch);
5213                    } else {
5214                        result.addAll(matchAllList);
5215                    }
5216                }
5217
5218                // If there is nothing selected, add all candidates and remove the ones that the user
5219                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5220                if (result.size() == 0) {
5221                    result.addAll(candidates);
5222                    result.removeAll(neverList);
5223                }
5224            }
5225        }
5226        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5227            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5228                    result.size());
5229            for (ResolveInfo info : result) {
5230                Slog.v(TAG, "  + " + info.activityInfo);
5231            }
5232        }
5233        return result;
5234    }
5235
5236    // Returns a packed value as a long:
5237    //
5238    // high 'int'-sized word: link status: undefined/ask/never/always.
5239    // low 'int'-sized word: relative priority among 'always' results.
5240    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5241        long result = ps.getDomainVerificationStatusForUser(userId);
5242        // if none available, get the master status
5243        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5244            if (ps.getIntentFilterVerificationInfo() != null) {
5245                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5246            }
5247        }
5248        return result;
5249    }
5250
5251    private ResolveInfo querySkipCurrentProfileIntents(
5252            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5253            int flags, int sourceUserId) {
5254        if (matchingFilters != null) {
5255            int size = matchingFilters.size();
5256            for (int i = 0; i < size; i ++) {
5257                CrossProfileIntentFilter filter = matchingFilters.get(i);
5258                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5259                    // Checking if there are activities in the target user that can handle the
5260                    // intent.
5261                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5262                            resolvedType, flags, sourceUserId);
5263                    if (resolveInfo != null) {
5264                        return resolveInfo;
5265                    }
5266                }
5267            }
5268        }
5269        return null;
5270    }
5271
5272    // Return matching ResolveInfo in target user if any.
5273    private ResolveInfo queryCrossProfileIntents(
5274            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5275            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5276        if (matchingFilters != null) {
5277            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5278            // match the same intent. For performance reasons, it is better not to
5279            // run queryIntent twice for the same userId
5280            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5281            int size = matchingFilters.size();
5282            for (int i = 0; i < size; i++) {
5283                CrossProfileIntentFilter filter = matchingFilters.get(i);
5284                int targetUserId = filter.getTargetUserId();
5285                boolean skipCurrentProfile =
5286                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5287                boolean skipCurrentProfileIfNoMatchFound =
5288                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5289                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5290                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5291                    // Checking if there are activities in the target user that can handle the
5292                    // intent.
5293                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5294                            resolvedType, flags, sourceUserId);
5295                    if (resolveInfo != null) return resolveInfo;
5296                    alreadyTriedUserIds.put(targetUserId, true);
5297                }
5298            }
5299        }
5300        return null;
5301    }
5302
5303    /**
5304     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5305     * will forward the intent to the filter's target user.
5306     * Otherwise, returns null.
5307     */
5308    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5309            String resolvedType, int flags, int sourceUserId) {
5310        int targetUserId = filter.getTargetUserId();
5311        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5312                resolvedType, flags, targetUserId);
5313        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5314                && isUserEnabled(targetUserId)) {
5315            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5316        }
5317        return null;
5318    }
5319
5320    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5321            int sourceUserId, int targetUserId) {
5322        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5323        long ident = Binder.clearCallingIdentity();
5324        boolean targetIsProfile;
5325        try {
5326            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5327        } finally {
5328            Binder.restoreCallingIdentity(ident);
5329        }
5330        String className;
5331        if (targetIsProfile) {
5332            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5333        } else {
5334            className = FORWARD_INTENT_TO_PARENT;
5335        }
5336        ComponentName forwardingActivityComponentName = new ComponentName(
5337                mAndroidApplication.packageName, className);
5338        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5339                sourceUserId);
5340        if (!targetIsProfile) {
5341            forwardingActivityInfo.showUserIcon = targetUserId;
5342            forwardingResolveInfo.noResourceId = true;
5343        }
5344        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5345        forwardingResolveInfo.priority = 0;
5346        forwardingResolveInfo.preferredOrder = 0;
5347        forwardingResolveInfo.match = 0;
5348        forwardingResolveInfo.isDefault = true;
5349        forwardingResolveInfo.filter = filter;
5350        forwardingResolveInfo.targetUserId = targetUserId;
5351        return forwardingResolveInfo;
5352    }
5353
5354    @Override
5355    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5356            Intent[] specifics, String[] specificTypes, Intent intent,
5357            String resolvedType, int flags, int userId) {
5358        if (!sUserManager.exists(userId)) return Collections.emptyList();
5359        flags = updateFlagsForResolve(flags, userId, intent);
5360        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5361                false, "query intent activity options");
5362        final String resultsAction = intent.getAction();
5363
5364        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5365                | PackageManager.GET_RESOLVED_FILTER, userId);
5366
5367        if (DEBUG_INTENT_MATCHING) {
5368            Log.v(TAG, "Query " + intent + ": " + results);
5369        }
5370
5371        int specificsPos = 0;
5372        int N;
5373
5374        // todo: note that the algorithm used here is O(N^2).  This
5375        // isn't a problem in our current environment, but if we start running
5376        // into situations where we have more than 5 or 10 matches then this
5377        // should probably be changed to something smarter...
5378
5379        // First we go through and resolve each of the specific items
5380        // that were supplied, taking care of removing any corresponding
5381        // duplicate items in the generic resolve list.
5382        if (specifics != null) {
5383            for (int i=0; i<specifics.length; i++) {
5384                final Intent sintent = specifics[i];
5385                if (sintent == null) {
5386                    continue;
5387                }
5388
5389                if (DEBUG_INTENT_MATCHING) {
5390                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5391                }
5392
5393                String action = sintent.getAction();
5394                if (resultsAction != null && resultsAction.equals(action)) {
5395                    // If this action was explicitly requested, then don't
5396                    // remove things that have it.
5397                    action = null;
5398                }
5399
5400                ResolveInfo ri = null;
5401                ActivityInfo ai = null;
5402
5403                ComponentName comp = sintent.getComponent();
5404                if (comp == null) {
5405                    ri = resolveIntent(
5406                        sintent,
5407                        specificTypes != null ? specificTypes[i] : null,
5408                            flags, userId);
5409                    if (ri == null) {
5410                        continue;
5411                    }
5412                    if (ri == mResolveInfo) {
5413                        // ACK!  Must do something better with this.
5414                    }
5415                    ai = ri.activityInfo;
5416                    comp = new ComponentName(ai.applicationInfo.packageName,
5417                            ai.name);
5418                } else {
5419                    ai = getActivityInfo(comp, flags, userId);
5420                    if (ai == null) {
5421                        continue;
5422                    }
5423                }
5424
5425                // Look for any generic query activities that are duplicates
5426                // of this specific one, and remove them from the results.
5427                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5428                N = results.size();
5429                int j;
5430                for (j=specificsPos; j<N; j++) {
5431                    ResolveInfo sri = results.get(j);
5432                    if ((sri.activityInfo.name.equals(comp.getClassName())
5433                            && sri.activityInfo.applicationInfo.packageName.equals(
5434                                    comp.getPackageName()))
5435                        || (action != null && sri.filter.matchAction(action))) {
5436                        results.remove(j);
5437                        if (DEBUG_INTENT_MATCHING) Log.v(
5438                            TAG, "Removing duplicate item from " + j
5439                            + " due to specific " + specificsPos);
5440                        if (ri == null) {
5441                            ri = sri;
5442                        }
5443                        j--;
5444                        N--;
5445                    }
5446                }
5447
5448                // Add this specific item to its proper place.
5449                if (ri == null) {
5450                    ri = new ResolveInfo();
5451                    ri.activityInfo = ai;
5452                }
5453                results.add(specificsPos, ri);
5454                ri.specificIndex = i;
5455                specificsPos++;
5456            }
5457        }
5458
5459        // Now we go through the remaining generic results and remove any
5460        // duplicate actions that are found here.
5461        N = results.size();
5462        for (int i=specificsPos; i<N-1; i++) {
5463            final ResolveInfo rii = results.get(i);
5464            if (rii.filter == null) {
5465                continue;
5466            }
5467
5468            // Iterate over all of the actions of this result's intent
5469            // filter...  typically this should be just one.
5470            final Iterator<String> it = rii.filter.actionsIterator();
5471            if (it == null) {
5472                continue;
5473            }
5474            while (it.hasNext()) {
5475                final String action = it.next();
5476                if (resultsAction != null && resultsAction.equals(action)) {
5477                    // If this action was explicitly requested, then don't
5478                    // remove things that have it.
5479                    continue;
5480                }
5481                for (int j=i+1; j<N; j++) {
5482                    final ResolveInfo rij = results.get(j);
5483                    if (rij.filter != null && rij.filter.hasAction(action)) {
5484                        results.remove(j);
5485                        if (DEBUG_INTENT_MATCHING) Log.v(
5486                            TAG, "Removing duplicate item from " + j
5487                            + " due to action " + action + " at " + i);
5488                        j--;
5489                        N--;
5490                    }
5491                }
5492            }
5493
5494            // If the caller didn't request filter information, drop it now
5495            // so we don't have to marshall/unmarshall it.
5496            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5497                rii.filter = null;
5498            }
5499        }
5500
5501        // Filter out the caller activity if so requested.
5502        if (caller != null) {
5503            N = results.size();
5504            for (int i=0; i<N; i++) {
5505                ActivityInfo ainfo = results.get(i).activityInfo;
5506                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5507                        && caller.getClassName().equals(ainfo.name)) {
5508                    results.remove(i);
5509                    break;
5510                }
5511            }
5512        }
5513
5514        // If the caller didn't request filter information,
5515        // drop them now so we don't have to
5516        // marshall/unmarshall it.
5517        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5518            N = results.size();
5519            for (int i=0; i<N; i++) {
5520                results.get(i).filter = null;
5521            }
5522        }
5523
5524        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5525        return results;
5526    }
5527
5528    @Override
5529    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5530            int userId) {
5531        if (!sUserManager.exists(userId)) return Collections.emptyList();
5532        flags = updateFlagsForResolve(flags, userId, intent);
5533        ComponentName comp = intent.getComponent();
5534        if (comp == null) {
5535            if (intent.getSelector() != null) {
5536                intent = intent.getSelector();
5537                comp = intent.getComponent();
5538            }
5539        }
5540        if (comp != null) {
5541            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5542            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5543            if (ai != null) {
5544                ResolveInfo ri = new ResolveInfo();
5545                ri.activityInfo = ai;
5546                list.add(ri);
5547            }
5548            return list;
5549        }
5550
5551        // reader
5552        synchronized (mPackages) {
5553            String pkgName = intent.getPackage();
5554            if (pkgName == null) {
5555                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5556            }
5557            final PackageParser.Package pkg = mPackages.get(pkgName);
5558            if (pkg != null) {
5559                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5560                        userId);
5561            }
5562            return null;
5563        }
5564    }
5565
5566    @Override
5567    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5568        if (!sUserManager.exists(userId)) return null;
5569        flags = updateFlagsForResolve(flags, userId, intent);
5570        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5571        if (query != null) {
5572            if (query.size() >= 1) {
5573                // If there is more than one service with the same priority,
5574                // just arbitrarily pick the first one.
5575                return query.get(0);
5576            }
5577        }
5578        return null;
5579    }
5580
5581    @Override
5582    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5583            int userId) {
5584        if (!sUserManager.exists(userId)) return Collections.emptyList();
5585        flags = updateFlagsForResolve(flags, userId, intent);
5586        ComponentName comp = intent.getComponent();
5587        if (comp == null) {
5588            if (intent.getSelector() != null) {
5589                intent = intent.getSelector();
5590                comp = intent.getComponent();
5591            }
5592        }
5593        if (comp != null) {
5594            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5595            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5596            if (si != null) {
5597                final ResolveInfo ri = new ResolveInfo();
5598                ri.serviceInfo = si;
5599                list.add(ri);
5600            }
5601            return list;
5602        }
5603
5604        // reader
5605        synchronized (mPackages) {
5606            String pkgName = intent.getPackage();
5607            if (pkgName == null) {
5608                return mServices.queryIntent(intent, resolvedType, flags, userId);
5609            }
5610            final PackageParser.Package pkg = mPackages.get(pkgName);
5611            if (pkg != null) {
5612                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5613                        userId);
5614            }
5615            return null;
5616        }
5617    }
5618
5619    @Override
5620    public List<ResolveInfo> queryIntentContentProviders(
5621            Intent intent, String resolvedType, int flags, int userId) {
5622        if (!sUserManager.exists(userId)) return Collections.emptyList();
5623        flags = updateFlagsForResolve(flags, userId, intent);
5624        ComponentName comp = intent.getComponent();
5625        if (comp == null) {
5626            if (intent.getSelector() != null) {
5627                intent = intent.getSelector();
5628                comp = intent.getComponent();
5629            }
5630        }
5631        if (comp != null) {
5632            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5633            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5634            if (pi != null) {
5635                final ResolveInfo ri = new ResolveInfo();
5636                ri.providerInfo = pi;
5637                list.add(ri);
5638            }
5639            return list;
5640        }
5641
5642        // reader
5643        synchronized (mPackages) {
5644            String pkgName = intent.getPackage();
5645            if (pkgName == null) {
5646                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5647            }
5648            final PackageParser.Package pkg = mPackages.get(pkgName);
5649            if (pkg != null) {
5650                return mProviders.queryIntentForPackage(
5651                        intent, resolvedType, flags, pkg.providers, userId);
5652            }
5653            return null;
5654        }
5655    }
5656
5657    @Override
5658    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5659        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5660        flags = updateFlagsForPackage(flags, userId, null);
5661        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5662        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5663
5664        // writer
5665        synchronized (mPackages) {
5666            ArrayList<PackageInfo> list;
5667            if (listUninstalled) {
5668                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5669                for (PackageSetting ps : mSettings.mPackages.values()) {
5670                    PackageInfo pi;
5671                    if (ps.pkg != null) {
5672                        pi = generatePackageInfo(ps.pkg, flags, userId);
5673                    } else {
5674                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5675                    }
5676                    if (pi != null) {
5677                        list.add(pi);
5678                    }
5679                }
5680            } else {
5681                list = new ArrayList<PackageInfo>(mPackages.size());
5682                for (PackageParser.Package p : mPackages.values()) {
5683                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5684                    if (pi != null) {
5685                        list.add(pi);
5686                    }
5687                }
5688            }
5689
5690            return new ParceledListSlice<PackageInfo>(list);
5691        }
5692    }
5693
5694    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5695            String[] permissions, boolean[] tmp, int flags, int userId) {
5696        int numMatch = 0;
5697        final PermissionsState permissionsState = ps.getPermissionsState();
5698        for (int i=0; i<permissions.length; i++) {
5699            final String permission = permissions[i];
5700            if (permissionsState.hasPermission(permission, userId)) {
5701                tmp[i] = true;
5702                numMatch++;
5703            } else {
5704                tmp[i] = false;
5705            }
5706        }
5707        if (numMatch == 0) {
5708            return;
5709        }
5710        PackageInfo pi;
5711        if (ps.pkg != null) {
5712            pi = generatePackageInfo(ps.pkg, flags, userId);
5713        } else {
5714            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5715        }
5716        // The above might return null in cases of uninstalled apps or install-state
5717        // skew across users/profiles.
5718        if (pi != null) {
5719            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5720                if (numMatch == permissions.length) {
5721                    pi.requestedPermissions = permissions;
5722                } else {
5723                    pi.requestedPermissions = new String[numMatch];
5724                    numMatch = 0;
5725                    for (int i=0; i<permissions.length; i++) {
5726                        if (tmp[i]) {
5727                            pi.requestedPermissions[numMatch] = permissions[i];
5728                            numMatch++;
5729                        }
5730                    }
5731                }
5732            }
5733            list.add(pi);
5734        }
5735    }
5736
5737    @Override
5738    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5739            String[] permissions, int flags, int userId) {
5740        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5741        flags = updateFlagsForPackage(flags, userId, permissions);
5742        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5743
5744        // writer
5745        synchronized (mPackages) {
5746            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5747            boolean[] tmpBools = new boolean[permissions.length];
5748            if (listUninstalled) {
5749                for (PackageSetting ps : mSettings.mPackages.values()) {
5750                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5751                }
5752            } else {
5753                for (PackageParser.Package pkg : mPackages.values()) {
5754                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5755                    if (ps != null) {
5756                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5757                                userId);
5758                    }
5759                }
5760            }
5761
5762            return new ParceledListSlice<PackageInfo>(list);
5763        }
5764    }
5765
5766    @Override
5767    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5768        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5769        flags = updateFlagsForApplication(flags, userId, null);
5770        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5771
5772        // writer
5773        synchronized (mPackages) {
5774            ArrayList<ApplicationInfo> list;
5775            if (listUninstalled) {
5776                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5777                for (PackageSetting ps : mSettings.mPackages.values()) {
5778                    ApplicationInfo ai;
5779                    if (ps.pkg != null) {
5780                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5781                                ps.readUserState(userId), userId);
5782                    } else {
5783                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5784                    }
5785                    if (ai != null) {
5786                        list.add(ai);
5787                    }
5788                }
5789            } else {
5790                list = new ArrayList<ApplicationInfo>(mPackages.size());
5791                for (PackageParser.Package p : mPackages.values()) {
5792                    if (p.mExtras != null) {
5793                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5794                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5795                        if (ai != null) {
5796                            list.add(ai);
5797                        }
5798                    }
5799                }
5800            }
5801
5802            return new ParceledListSlice<ApplicationInfo>(list);
5803        }
5804    }
5805
5806    @Override
5807    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5808        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5809                "getEphemeralApplications");
5810        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5811                "getEphemeralApplications");
5812        synchronized (mPackages) {
5813            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5814                    .getEphemeralApplicationsLPw(userId);
5815            if (ephemeralApps != null) {
5816                return new ParceledListSlice<>(ephemeralApps);
5817            }
5818        }
5819        return null;
5820    }
5821
5822    @Override
5823    public boolean isEphemeralApplication(String packageName, int userId) {
5824        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5825                "isEphemeral");
5826        if (!isCallerSameApp(packageName)) {
5827            return false;
5828        }
5829        synchronized (mPackages) {
5830            PackageParser.Package pkg = mPackages.get(packageName);
5831            if (pkg != null) {
5832                return pkg.applicationInfo.isEphemeralApp();
5833            }
5834        }
5835        return false;
5836    }
5837
5838    @Override
5839    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5840        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5841                "getCookie");
5842        if (!isCallerSameApp(packageName)) {
5843            return null;
5844        }
5845        synchronized (mPackages) {
5846            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5847                    packageName, userId);
5848        }
5849    }
5850
5851    @Override
5852    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5853        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5854                "setCookie");
5855        if (!isCallerSameApp(packageName)) {
5856            return false;
5857        }
5858        synchronized (mPackages) {
5859            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5860                    packageName, cookie, userId);
5861        }
5862    }
5863
5864    @Override
5865    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5866        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5867                "getEphemeralApplicationIcon");
5868        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5869                "getEphemeralApplicationIcon");
5870        synchronized (mPackages) {
5871            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5872                    packageName, userId);
5873        }
5874    }
5875
5876    private boolean isCallerSameApp(String packageName) {
5877        PackageParser.Package pkg = mPackages.get(packageName);
5878        return pkg != null
5879                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5880    }
5881
5882    public List<ApplicationInfo> getPersistentApplications(int flags) {
5883        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5884
5885        // reader
5886        synchronized (mPackages) {
5887            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5888            final int userId = UserHandle.getCallingUserId();
5889            while (i.hasNext()) {
5890                final PackageParser.Package p = i.next();
5891                if (p.applicationInfo != null
5892                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5893                        && (!mSafeMode || isSystemApp(p))) {
5894                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5895                    if (ps != null) {
5896                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5897                                ps.readUserState(userId), userId);
5898                        if (ai != null) {
5899                            finalList.add(ai);
5900                        }
5901                    }
5902                }
5903            }
5904        }
5905
5906        return finalList;
5907    }
5908
5909    @Override
5910    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5911        if (!sUserManager.exists(userId)) return null;
5912        flags = updateFlagsForComponent(flags, userId, name);
5913        // reader
5914        synchronized (mPackages) {
5915            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5916            PackageSetting ps = provider != null
5917                    ? mSettings.mPackages.get(provider.owner.packageName)
5918                    : null;
5919            return ps != null
5920                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5921                    && (!mSafeMode || (provider.info.applicationInfo.flags
5922                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5923                    ? PackageParser.generateProviderInfo(provider, flags,
5924                            ps.readUserState(userId), userId)
5925                    : null;
5926        }
5927    }
5928
5929    /**
5930     * @deprecated
5931     */
5932    @Deprecated
5933    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5934        // reader
5935        synchronized (mPackages) {
5936            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5937                    .entrySet().iterator();
5938            final int userId = UserHandle.getCallingUserId();
5939            while (i.hasNext()) {
5940                Map.Entry<String, PackageParser.Provider> entry = i.next();
5941                PackageParser.Provider p = entry.getValue();
5942                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5943
5944                if (ps != null && p.syncable
5945                        && (!mSafeMode || (p.info.applicationInfo.flags
5946                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5947                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5948                            ps.readUserState(userId), userId);
5949                    if (info != null) {
5950                        outNames.add(entry.getKey());
5951                        outInfo.add(info);
5952                    }
5953                }
5954            }
5955        }
5956    }
5957
5958    @Override
5959    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5960            int uid, int flags) {
5961        final int userId = processName != null ? UserHandle.getUserId(uid)
5962                : UserHandle.getCallingUserId();
5963        if (!sUserManager.exists(userId)) return null;
5964        flags = updateFlagsForComponent(flags, userId, processName);
5965
5966        ArrayList<ProviderInfo> finalList = null;
5967        // reader
5968        synchronized (mPackages) {
5969            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5970            while (i.hasNext()) {
5971                final PackageParser.Provider p = i.next();
5972                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5973                if (ps != null && p.info.authority != null
5974                        && (processName == null
5975                                || (p.info.processName.equals(processName)
5976                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5977                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)
5978                        && (!mSafeMode
5979                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5980                    if (finalList == null) {
5981                        finalList = new ArrayList<ProviderInfo>(3);
5982                    }
5983                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5984                            ps.readUserState(userId), userId);
5985                    if (info != null) {
5986                        finalList.add(info);
5987                    }
5988                }
5989            }
5990        }
5991
5992        if (finalList != null) {
5993            Collections.sort(finalList, mProviderInitOrderSorter);
5994            return new ParceledListSlice<ProviderInfo>(finalList);
5995        }
5996
5997        return null;
5998    }
5999
6000    @Override
6001    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6002        // reader
6003        synchronized (mPackages) {
6004            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6005            return PackageParser.generateInstrumentationInfo(i, flags);
6006        }
6007    }
6008
6009    @Override
6010    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6011            int flags) {
6012        ArrayList<InstrumentationInfo> finalList =
6013            new ArrayList<InstrumentationInfo>();
6014
6015        // reader
6016        synchronized (mPackages) {
6017            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6018            while (i.hasNext()) {
6019                final PackageParser.Instrumentation p = i.next();
6020                if (targetPackage == null
6021                        || targetPackage.equals(p.info.targetPackage)) {
6022                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6023                            flags);
6024                    if (ii != null) {
6025                        finalList.add(ii);
6026                    }
6027                }
6028            }
6029        }
6030
6031        return finalList;
6032    }
6033
6034    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6035        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6036        if (overlays == null) {
6037            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6038            return;
6039        }
6040        for (PackageParser.Package opkg : overlays.values()) {
6041            // Not much to do if idmap fails: we already logged the error
6042            // and we certainly don't want to abort installation of pkg simply
6043            // because an overlay didn't fit properly. For these reasons,
6044            // ignore the return value of createIdmapForPackagePairLI.
6045            createIdmapForPackagePairLI(pkg, opkg);
6046        }
6047    }
6048
6049    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6050            PackageParser.Package opkg) {
6051        if (!opkg.mTrustedOverlay) {
6052            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6053                    opkg.baseCodePath + ": overlay not trusted");
6054            return false;
6055        }
6056        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6057        if (overlaySet == null) {
6058            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6059                    opkg.baseCodePath + " but target package has no known overlays");
6060            return false;
6061        }
6062        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6063        // TODO: generate idmap for split APKs
6064        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6065            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6066                    + opkg.baseCodePath);
6067            return false;
6068        }
6069        PackageParser.Package[] overlayArray =
6070            overlaySet.values().toArray(new PackageParser.Package[0]);
6071        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6072            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6073                return p1.mOverlayPriority - p2.mOverlayPriority;
6074            }
6075        };
6076        Arrays.sort(overlayArray, cmp);
6077
6078        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6079        int i = 0;
6080        for (PackageParser.Package p : overlayArray) {
6081            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6082        }
6083        return true;
6084    }
6085
6086    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6087        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6088        try {
6089            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6090        } finally {
6091            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6092        }
6093    }
6094
6095    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6096        final File[] files = dir.listFiles();
6097        if (ArrayUtils.isEmpty(files)) {
6098            Log.d(TAG, "No files in app dir " + dir);
6099            return;
6100        }
6101
6102        if (DEBUG_PACKAGE_SCANNING) {
6103            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6104                    + " flags=0x" + Integer.toHexString(parseFlags));
6105        }
6106
6107        for (File file : files) {
6108            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6109                    && !PackageInstallerService.isStageName(file.getName());
6110            if (!isPackage) {
6111                // Ignore entries which are not packages
6112                continue;
6113            }
6114            try {
6115                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6116                        scanFlags, currentTime, null);
6117            } catch (PackageManagerException e) {
6118                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6119
6120                // Delete invalid userdata apps
6121                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6122                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6123                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6124                    if (file.isDirectory()) {
6125                        mInstaller.rmPackageDir(file.getAbsolutePath());
6126                    } else {
6127                        file.delete();
6128                    }
6129                }
6130            }
6131        }
6132    }
6133
6134    private static File getSettingsProblemFile() {
6135        File dataDir = Environment.getDataDirectory();
6136        File systemDir = new File(dataDir, "system");
6137        File fname = new File(systemDir, "uiderrors.txt");
6138        return fname;
6139    }
6140
6141    static void reportSettingsProblem(int priority, String msg) {
6142        logCriticalInfo(priority, msg);
6143    }
6144
6145    static void logCriticalInfo(int priority, String msg) {
6146        Slog.println(priority, TAG, msg);
6147        EventLogTags.writePmCriticalInfo(msg);
6148        try {
6149            File fname = getSettingsProblemFile();
6150            FileOutputStream out = new FileOutputStream(fname, true);
6151            PrintWriter pw = new FastPrintWriter(out);
6152            SimpleDateFormat formatter = new SimpleDateFormat();
6153            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6154            pw.println(dateString + ": " + msg);
6155            pw.close();
6156            FileUtils.setPermissions(
6157                    fname.toString(),
6158                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6159                    -1, -1);
6160        } catch (java.io.IOException e) {
6161        }
6162    }
6163
6164    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6165            PackageParser.Package pkg, File srcFile, int parseFlags)
6166            throws PackageManagerException {
6167        if (ps != null
6168                && ps.codePath.equals(srcFile)
6169                && ps.timeStamp == srcFile.lastModified()
6170                && !isCompatSignatureUpdateNeeded(pkg)
6171                && !isRecoverSignatureUpdateNeeded(pkg)) {
6172            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6173            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6174            ArraySet<PublicKey> signingKs;
6175            synchronized (mPackages) {
6176                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6177            }
6178            if (ps.signatures.mSignatures != null
6179                    && ps.signatures.mSignatures.length != 0
6180                    && signingKs != null) {
6181                // Optimization: reuse the existing cached certificates
6182                // if the package appears to be unchanged.
6183                pkg.mSignatures = ps.signatures.mSignatures;
6184                pkg.mSigningKeys = signingKs;
6185                return;
6186            }
6187
6188            Slog.w(TAG, "PackageSetting for " + ps.name
6189                    + " is missing signatures.  Collecting certs again to recover them.");
6190        } else {
6191            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6192        }
6193
6194        try {
6195            pp.collectCertificates(pkg, parseFlags);
6196        } catch (PackageParserException e) {
6197            throw PackageManagerException.from(e);
6198        }
6199    }
6200
6201    /**
6202     *  Traces a package scan.
6203     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6204     */
6205    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6206            long currentTime, UserHandle user) throws PackageManagerException {
6207        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6208        try {
6209            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6210        } finally {
6211            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6212        }
6213    }
6214
6215    /**
6216     *  Scans a package and returns the newly parsed package.
6217     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6218     */
6219    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6220            long currentTime, UserHandle user) throws PackageManagerException {
6221        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6222        parseFlags |= mDefParseFlags;
6223        PackageParser pp = new PackageParser();
6224        pp.setSeparateProcesses(mSeparateProcesses);
6225        pp.setOnlyCoreApps(mOnlyCore);
6226        pp.setDisplayMetrics(mMetrics);
6227
6228        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6229            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6230        }
6231
6232        final PackageParser.Package pkg;
6233        try {
6234            pkg = pp.parsePackage(scanFile, parseFlags);
6235        } catch (PackageParserException e) {
6236            throw PackageManagerException.from(e);
6237        }
6238
6239        PackageSetting ps = null;
6240        PackageSetting updatedPkg;
6241        // reader
6242        synchronized (mPackages) {
6243            // Look to see if we already know about this package.
6244            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6245            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6246                // This package has been renamed to its original name.  Let's
6247                // use that.
6248                ps = mSettings.peekPackageLPr(oldName);
6249            }
6250            // If there was no original package, see one for the real package name.
6251            if (ps == null) {
6252                ps = mSettings.peekPackageLPr(pkg.packageName);
6253            }
6254            // Check to see if this package could be hiding/updating a system
6255            // package.  Must look for it either under the original or real
6256            // package name depending on our state.
6257            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6258            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6259        }
6260        boolean updatedPkgBetter = false;
6261        // First check if this is a system package that may involve an update
6262        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6263            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6264            // it needs to drop FLAG_PRIVILEGED.
6265            if (locationIsPrivileged(scanFile)) {
6266                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6267            } else {
6268                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6269            }
6270
6271            if (ps != null && !ps.codePath.equals(scanFile)) {
6272                // The path has changed from what was last scanned...  check the
6273                // version of the new path against what we have stored to determine
6274                // what to do.
6275                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6276                if (pkg.mVersionCode <= ps.versionCode) {
6277                    // The system package has been updated and the code path does not match
6278                    // Ignore entry. Skip it.
6279                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6280                            + " ignored: updated version " + ps.versionCode
6281                            + " better than this " + pkg.mVersionCode);
6282                    if (!updatedPkg.codePath.equals(scanFile)) {
6283                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6284                                + ps.name + " changing from " + updatedPkg.codePathString
6285                                + " to " + scanFile);
6286                        updatedPkg.codePath = scanFile;
6287                        updatedPkg.codePathString = scanFile.toString();
6288                        updatedPkg.resourcePath = scanFile;
6289                        updatedPkg.resourcePathString = scanFile.toString();
6290                    }
6291                    updatedPkg.pkg = pkg;
6292                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6293                            "Package " + ps.name + " at " + scanFile
6294                                    + " ignored: updated version " + ps.versionCode
6295                                    + " better than this " + pkg.mVersionCode);
6296                } else {
6297                    // The current app on the system partition is better than
6298                    // what we have updated to on the data partition; switch
6299                    // back to the system partition version.
6300                    // At this point, its safely assumed that package installation for
6301                    // apps in system partition will go through. If not there won't be a working
6302                    // version of the app
6303                    // writer
6304                    synchronized (mPackages) {
6305                        // Just remove the loaded entries from package lists.
6306                        mPackages.remove(ps.name);
6307                    }
6308
6309                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6310                            + " reverting from " + ps.codePathString
6311                            + ": new version " + pkg.mVersionCode
6312                            + " better than installed " + ps.versionCode);
6313
6314                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6315                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6316                    synchronized (mInstallLock) {
6317                        args.cleanUpResourcesLI();
6318                    }
6319                    synchronized (mPackages) {
6320                        mSettings.enableSystemPackageLPw(ps.name);
6321                    }
6322                    updatedPkgBetter = true;
6323                }
6324            }
6325        }
6326
6327        if (updatedPkg != null) {
6328            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6329            // initially
6330            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6331
6332            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6333            // flag set initially
6334            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6335                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6336            }
6337        }
6338
6339        // Verify certificates against what was last scanned
6340        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6341
6342        /*
6343         * A new system app appeared, but we already had a non-system one of the
6344         * same name installed earlier.
6345         */
6346        boolean shouldHideSystemApp = false;
6347        if (updatedPkg == null && ps != null
6348                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6349            /*
6350             * Check to make sure the signatures match first. If they don't,
6351             * wipe the installed application and its data.
6352             */
6353            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6354                    != PackageManager.SIGNATURE_MATCH) {
6355                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6356                        + " signatures don't match existing userdata copy; removing");
6357                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6358                ps = null;
6359            } else {
6360                /*
6361                 * If the newly-added system app is an older version than the
6362                 * already installed version, hide it. It will be scanned later
6363                 * and re-added like an update.
6364                 */
6365                if (pkg.mVersionCode <= ps.versionCode) {
6366                    shouldHideSystemApp = true;
6367                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6368                            + " but new version " + pkg.mVersionCode + " better than installed "
6369                            + ps.versionCode + "; hiding system");
6370                } else {
6371                    /*
6372                     * The newly found system app is a newer version that the
6373                     * one previously installed. Simply remove the
6374                     * already-installed application and replace it with our own
6375                     * while keeping the application data.
6376                     */
6377                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6378                            + " reverting from " + ps.codePathString + ": new version "
6379                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6380                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6381                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6382                    synchronized (mInstallLock) {
6383                        args.cleanUpResourcesLI();
6384                    }
6385                }
6386            }
6387        }
6388
6389        // The apk is forward locked (not public) if its code and resources
6390        // are kept in different files. (except for app in either system or
6391        // vendor path).
6392        // TODO grab this value from PackageSettings
6393        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6394            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6395                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6396            }
6397        }
6398
6399        // TODO: extend to support forward-locked splits
6400        String resourcePath = null;
6401        String baseResourcePath = null;
6402        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6403            if (ps != null && ps.resourcePathString != null) {
6404                resourcePath = ps.resourcePathString;
6405                baseResourcePath = ps.resourcePathString;
6406            } else {
6407                // Should not happen at all. Just log an error.
6408                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6409            }
6410        } else {
6411            resourcePath = pkg.codePath;
6412            baseResourcePath = pkg.baseCodePath;
6413        }
6414
6415        // Set application objects path explicitly.
6416        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6417        pkg.applicationInfo.setCodePath(pkg.codePath);
6418        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6419        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6420        pkg.applicationInfo.setResourcePath(resourcePath);
6421        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6422        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6423
6424        // Note that we invoke the following method only if we are about to unpack an application
6425        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6426                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6427
6428        /*
6429         * If the system app should be overridden by a previously installed
6430         * data, hide the system app now and let the /data/app scan pick it up
6431         * again.
6432         */
6433        if (shouldHideSystemApp) {
6434            synchronized (mPackages) {
6435                mSettings.disableSystemPackageLPw(pkg.packageName);
6436            }
6437        }
6438
6439        return scannedPkg;
6440    }
6441
6442    private static String fixProcessName(String defProcessName,
6443            String processName, int uid) {
6444        if (processName == null) {
6445            return defProcessName;
6446        }
6447        return processName;
6448    }
6449
6450    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6451            throws PackageManagerException {
6452        if (pkgSetting.signatures.mSignatures != null) {
6453            // Already existing package. Make sure signatures match
6454            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6455                    == PackageManager.SIGNATURE_MATCH;
6456            if (!match) {
6457                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6458                        == PackageManager.SIGNATURE_MATCH;
6459            }
6460            if (!match) {
6461                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6462                        == PackageManager.SIGNATURE_MATCH;
6463            }
6464            if (!match) {
6465                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6466                        + pkg.packageName + " signatures do not match the "
6467                        + "previously installed version; ignoring!");
6468            }
6469        }
6470
6471        // Check for shared user signatures
6472        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6473            // Already existing package. Make sure signatures match
6474            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6475                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6476            if (!match) {
6477                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6478                        == PackageManager.SIGNATURE_MATCH;
6479            }
6480            if (!match) {
6481                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6482                        == PackageManager.SIGNATURE_MATCH;
6483            }
6484            if (!match) {
6485                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6486                        "Package " + pkg.packageName
6487                        + " has no signatures that match those in shared user "
6488                        + pkgSetting.sharedUser.name + "; ignoring!");
6489            }
6490        }
6491    }
6492
6493    /**
6494     * Enforces that only the system UID or root's UID can call a method exposed
6495     * via Binder.
6496     *
6497     * @param message used as message if SecurityException is thrown
6498     * @throws SecurityException if the caller is not system or root
6499     */
6500    private static final void enforceSystemOrRoot(String message) {
6501        final int uid = Binder.getCallingUid();
6502        if (uid != Process.SYSTEM_UID && uid != 0) {
6503            throw new SecurityException(message);
6504        }
6505    }
6506
6507    @Override
6508    public void performFstrimIfNeeded() {
6509        enforceSystemOrRoot("Only the system can request fstrim");
6510
6511        // Before everything else, see whether we need to fstrim.
6512        try {
6513            IMountService ms = PackageHelper.getMountService();
6514            if (ms != null) {
6515                final boolean isUpgrade = isUpgrade();
6516                boolean doTrim = isUpgrade;
6517                if (doTrim) {
6518                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6519                } else {
6520                    final long interval = android.provider.Settings.Global.getLong(
6521                            mContext.getContentResolver(),
6522                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6523                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6524                    if (interval > 0) {
6525                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6526                        if (timeSinceLast > interval) {
6527                            doTrim = true;
6528                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6529                                    + "; running immediately");
6530                        }
6531                    }
6532                }
6533                if (doTrim) {
6534                    if (!isFirstBoot()) {
6535                        try {
6536                            ActivityManagerNative.getDefault().showBootMessage(
6537                                    mContext.getResources().getString(
6538                                            R.string.android_upgrading_fstrim), true);
6539                        } catch (RemoteException e) {
6540                        }
6541                    }
6542                    ms.runMaintenance();
6543                }
6544            } else {
6545                Slog.e(TAG, "Mount service unavailable!");
6546            }
6547        } catch (RemoteException e) {
6548            // Can't happen; MountService is local
6549        }
6550    }
6551
6552    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6553        List<ResolveInfo> ris = null;
6554        try {
6555            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6556                    intent, null, 0, userId);
6557        } catch (RemoteException e) {
6558        }
6559        ArraySet<String> pkgNames = new ArraySet<String>();
6560        if (ris != null) {
6561            for (ResolveInfo ri : ris) {
6562                pkgNames.add(ri.activityInfo.packageName);
6563            }
6564        }
6565        return pkgNames;
6566    }
6567
6568    @Override
6569    public void notifyPackageUse(String packageName) {
6570        synchronized (mPackages) {
6571            PackageParser.Package p = mPackages.get(packageName);
6572            if (p == null) {
6573                return;
6574            }
6575            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6576        }
6577    }
6578
6579    @Override
6580    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6581        return performDexOptTraced(packageName, instructionSet);
6582    }
6583
6584    public boolean performDexOpt(String packageName, String instructionSet) {
6585        return performDexOptTraced(packageName, instructionSet);
6586    }
6587
6588    private boolean performDexOptTraced(String packageName, String instructionSet) {
6589        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6590        try {
6591            return performDexOptInternal(packageName, instructionSet);
6592        } finally {
6593            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6594        }
6595    }
6596
6597    private boolean performDexOptInternal(String packageName, String instructionSet) {
6598        PackageParser.Package p;
6599        final String targetInstructionSet;
6600        synchronized (mPackages) {
6601            p = mPackages.get(packageName);
6602            if (p == null) {
6603                return false;
6604            }
6605            mPackageUsage.write(false);
6606
6607            targetInstructionSet = instructionSet != null ? instructionSet :
6608                    getPrimaryInstructionSet(p.applicationInfo);
6609            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6610                return false;
6611            }
6612        }
6613        long callingId = Binder.clearCallingIdentity();
6614        try {
6615            synchronized (mInstallLock) {
6616                final String[] instructionSets = new String[] { targetInstructionSet };
6617                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6618                        true /* inclDependencies */);
6619                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6620            }
6621        } finally {
6622            Binder.restoreCallingIdentity(callingId);
6623        }
6624    }
6625
6626    public ArraySet<String> getPackagesThatNeedDexOpt() {
6627        ArraySet<String> pkgs = null;
6628        synchronized (mPackages) {
6629            for (PackageParser.Package p : mPackages.values()) {
6630                if (DEBUG_DEXOPT) {
6631                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6632                }
6633                if (!p.mDexOptPerformed.isEmpty()) {
6634                    continue;
6635                }
6636                if (pkgs == null) {
6637                    pkgs = new ArraySet<String>();
6638                }
6639                pkgs.add(p.packageName);
6640            }
6641        }
6642        return pkgs;
6643    }
6644
6645    public void shutdown() {
6646        mPackageUsage.write(true);
6647    }
6648
6649    @Override
6650    public void forceDexOpt(String packageName) {
6651        enforceSystemOrRoot("forceDexOpt");
6652
6653        PackageParser.Package pkg;
6654        synchronized (mPackages) {
6655            pkg = mPackages.get(packageName);
6656            if (pkg == null) {
6657                throw new IllegalArgumentException("Unknown package: " + packageName);
6658            }
6659        }
6660
6661        synchronized (mInstallLock) {
6662            final String[] instructionSets = new String[] {
6663                    getPrimaryInstructionSet(pkg.applicationInfo) };
6664
6665            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6666
6667            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6668                    true /* inclDependencies */);
6669
6670            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6671            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6672                throw new IllegalStateException("Failed to dexopt: " + res);
6673            }
6674        }
6675    }
6676
6677    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6678        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6679            Slog.w(TAG, "Unable to update from " + oldPkg.name
6680                    + " to " + newPkg.packageName
6681                    + ": old package not in system partition");
6682            return false;
6683        } else if (mPackages.get(oldPkg.name) != null) {
6684            Slog.w(TAG, "Unable to update from " + oldPkg.name
6685                    + " to " + newPkg.packageName
6686                    + ": old package still exists");
6687            return false;
6688        }
6689        return true;
6690    }
6691
6692    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6693            throws PackageManagerException {
6694        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6695        if (res != 0) {
6696            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6697                    "Failed to install " + packageName + ": " + res);
6698        }
6699
6700        final int[] users = sUserManager.getUserIds();
6701        for (int user : users) {
6702            if (user != 0) {
6703                res = mInstaller.createUserData(volumeUuid, packageName,
6704                        UserHandle.getUid(user, uid), user, seinfo);
6705                if (res != 0) {
6706                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6707                            "Failed to createUserData " + packageName + ": " + res);
6708                }
6709            }
6710        }
6711    }
6712
6713    private int removeDataDirsLI(String volumeUuid, String packageName) {
6714        int[] users = sUserManager.getUserIds();
6715        int res = 0;
6716        for (int user : users) {
6717            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6718            if (resInner < 0) {
6719                res = resInner;
6720            }
6721        }
6722
6723        return res;
6724    }
6725
6726    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6727        int[] users = sUserManager.getUserIds();
6728        int res = 0;
6729        for (int user : users) {
6730            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6731            if (resInner < 0) {
6732                res = resInner;
6733            }
6734        }
6735        return res;
6736    }
6737
6738    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6739            PackageParser.Package changingLib) {
6740        if (file.path != null) {
6741            usesLibraryFiles.add(file.path);
6742            return;
6743        }
6744        PackageParser.Package p = mPackages.get(file.apk);
6745        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6746            // If we are doing this while in the middle of updating a library apk,
6747            // then we need to make sure to use that new apk for determining the
6748            // dependencies here.  (We haven't yet finished committing the new apk
6749            // to the package manager state.)
6750            if (p == null || p.packageName.equals(changingLib.packageName)) {
6751                p = changingLib;
6752            }
6753        }
6754        if (p != null) {
6755            usesLibraryFiles.addAll(p.getAllCodePaths());
6756        }
6757    }
6758
6759    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6760            PackageParser.Package changingLib) throws PackageManagerException {
6761        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6762            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6763            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6764            for (int i=0; i<N; i++) {
6765                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6766                if (file == null) {
6767                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6768                            "Package " + pkg.packageName + " requires unavailable shared library "
6769                            + pkg.usesLibraries.get(i) + "; failing!");
6770                }
6771                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6772            }
6773            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6774            for (int i=0; i<N; i++) {
6775                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6776                if (file == null) {
6777                    Slog.w(TAG, "Package " + pkg.packageName
6778                            + " desires unavailable shared library "
6779                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6780                } else {
6781                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6782                }
6783            }
6784            N = usesLibraryFiles.size();
6785            if (N > 0) {
6786                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6787            } else {
6788                pkg.usesLibraryFiles = null;
6789            }
6790        }
6791    }
6792
6793    private static boolean hasString(List<String> list, List<String> which) {
6794        if (list == null) {
6795            return false;
6796        }
6797        for (int i=list.size()-1; i>=0; i--) {
6798            for (int j=which.size()-1; j>=0; j--) {
6799                if (which.get(j).equals(list.get(i))) {
6800                    return true;
6801                }
6802            }
6803        }
6804        return false;
6805    }
6806
6807    private void updateAllSharedLibrariesLPw() {
6808        for (PackageParser.Package pkg : mPackages.values()) {
6809            try {
6810                updateSharedLibrariesLPw(pkg, null);
6811            } catch (PackageManagerException e) {
6812                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6813            }
6814        }
6815    }
6816
6817    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6818            PackageParser.Package changingPkg) {
6819        ArrayList<PackageParser.Package> res = null;
6820        for (PackageParser.Package pkg : mPackages.values()) {
6821            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6822                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6823                if (res == null) {
6824                    res = new ArrayList<PackageParser.Package>();
6825                }
6826                res.add(pkg);
6827                try {
6828                    updateSharedLibrariesLPw(pkg, changingPkg);
6829                } catch (PackageManagerException e) {
6830                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6831                }
6832            }
6833        }
6834        return res;
6835    }
6836
6837    /**
6838     * Derive the value of the {@code cpuAbiOverride} based on the provided
6839     * value and an optional stored value from the package settings.
6840     */
6841    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6842        String cpuAbiOverride = null;
6843
6844        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6845            cpuAbiOverride = null;
6846        } else if (abiOverride != null) {
6847            cpuAbiOverride = abiOverride;
6848        } else if (settings != null) {
6849            cpuAbiOverride = settings.cpuAbiOverrideString;
6850        }
6851
6852        return cpuAbiOverride;
6853    }
6854
6855    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6856            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6857        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6858        try {
6859            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6860        } finally {
6861            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6862        }
6863    }
6864
6865    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6866            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6867        boolean success = false;
6868        try {
6869            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6870                    currentTime, user);
6871            success = true;
6872            return res;
6873        } finally {
6874            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6875                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6876            }
6877        }
6878    }
6879
6880    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6881            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6882        final File scanFile = new File(pkg.codePath);
6883        if (pkg.applicationInfo.getCodePath() == null ||
6884                pkg.applicationInfo.getResourcePath() == null) {
6885            // Bail out. The resource and code paths haven't been set.
6886            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6887                    "Code and resource paths haven't been set correctly");
6888        }
6889
6890        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6891            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6892        } else {
6893            // Only allow system apps to be flagged as core apps.
6894            pkg.coreApp = false;
6895        }
6896
6897        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6898            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6899        }
6900
6901        if (mCustomResolverComponentName != null &&
6902                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6903            setUpCustomResolverActivity(pkg);
6904        }
6905
6906        if (pkg.packageName.equals("android")) {
6907            synchronized (mPackages) {
6908                if (mAndroidApplication != null) {
6909                    Slog.w(TAG, "*************************************************");
6910                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6911                    Slog.w(TAG, " file=" + scanFile);
6912                    Slog.w(TAG, "*************************************************");
6913                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6914                            "Core android package being redefined.  Skipping.");
6915                }
6916
6917                // Set up information for our fall-back user intent resolution activity.
6918                mPlatformPackage = pkg;
6919                pkg.mVersionCode = mSdkVersion;
6920                mAndroidApplication = pkg.applicationInfo;
6921
6922                if (!mResolverReplaced) {
6923                    mResolveActivity.applicationInfo = mAndroidApplication;
6924                    mResolveActivity.name = ResolverActivity.class.getName();
6925                    mResolveActivity.packageName = mAndroidApplication.packageName;
6926                    mResolveActivity.processName = "system:ui";
6927                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6928                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6929                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6930                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6931                    mResolveActivity.exported = true;
6932                    mResolveActivity.enabled = true;
6933                    mResolveInfo.activityInfo = mResolveActivity;
6934                    mResolveInfo.priority = 0;
6935                    mResolveInfo.preferredOrder = 0;
6936                    mResolveInfo.match = 0;
6937                    mResolveComponentName = new ComponentName(
6938                            mAndroidApplication.packageName, mResolveActivity.name);
6939                }
6940            }
6941        }
6942
6943        if (DEBUG_PACKAGE_SCANNING) {
6944            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6945                Log.d(TAG, "Scanning package " + pkg.packageName);
6946        }
6947
6948        if (mPackages.containsKey(pkg.packageName)
6949                || mSharedLibraries.containsKey(pkg.packageName)) {
6950            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6951                    "Application package " + pkg.packageName
6952                    + " already installed.  Skipping duplicate.");
6953        }
6954
6955        // If we're only installing presumed-existing packages, require that the
6956        // scanned APK is both already known and at the path previously established
6957        // for it.  Previously unknown packages we pick up normally, but if we have an
6958        // a priori expectation about this package's install presence, enforce it.
6959        // With a singular exception for new system packages. When an OTA contains
6960        // a new system package, we allow the codepath to change from a system location
6961        // to the user-installed location. If we don't allow this change, any newer,
6962        // user-installed version of the application will be ignored.
6963        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6964            if (mExpectingBetter.containsKey(pkg.packageName)) {
6965                logCriticalInfo(Log.WARN,
6966                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6967            } else {
6968                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6969                if (known != null) {
6970                    if (DEBUG_PACKAGE_SCANNING) {
6971                        Log.d(TAG, "Examining " + pkg.codePath
6972                                + " and requiring known paths " + known.codePathString
6973                                + " & " + known.resourcePathString);
6974                    }
6975                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6976                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6977                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6978                                "Application package " + pkg.packageName
6979                                + " found at " + pkg.applicationInfo.getCodePath()
6980                                + " but expected at " + known.codePathString + "; ignoring.");
6981                    }
6982                }
6983            }
6984        }
6985
6986        // Initialize package source and resource directories
6987        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6988        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6989
6990        SharedUserSetting suid = null;
6991        PackageSetting pkgSetting = null;
6992
6993        if (!isSystemApp(pkg)) {
6994            // Only system apps can use these features.
6995            pkg.mOriginalPackages = null;
6996            pkg.mRealPackage = null;
6997            pkg.mAdoptPermissions = null;
6998        }
6999
7000        // writer
7001        synchronized (mPackages) {
7002            if (pkg.mSharedUserId != null) {
7003                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7004                if (suid == null) {
7005                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7006                            "Creating application package " + pkg.packageName
7007                            + " for shared user failed");
7008                }
7009                if (DEBUG_PACKAGE_SCANNING) {
7010                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7011                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7012                                + "): packages=" + suid.packages);
7013                }
7014            }
7015
7016            // Check if we are renaming from an original package name.
7017            PackageSetting origPackage = null;
7018            String realName = null;
7019            if (pkg.mOriginalPackages != null) {
7020                // This package may need to be renamed to a previously
7021                // installed name.  Let's check on that...
7022                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7023                if (pkg.mOriginalPackages.contains(renamed)) {
7024                    // This package had originally been installed as the
7025                    // original name, and we have already taken care of
7026                    // transitioning to the new one.  Just update the new
7027                    // one to continue using the old name.
7028                    realName = pkg.mRealPackage;
7029                    if (!pkg.packageName.equals(renamed)) {
7030                        // Callers into this function may have already taken
7031                        // care of renaming the package; only do it here if
7032                        // it is not already done.
7033                        pkg.setPackageName(renamed);
7034                    }
7035
7036                } else {
7037                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7038                        if ((origPackage = mSettings.peekPackageLPr(
7039                                pkg.mOriginalPackages.get(i))) != null) {
7040                            // We do have the package already installed under its
7041                            // original name...  should we use it?
7042                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7043                                // New package is not compatible with original.
7044                                origPackage = null;
7045                                continue;
7046                            } else if (origPackage.sharedUser != null) {
7047                                // Make sure uid is compatible between packages.
7048                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7049                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7050                                            + " to " + pkg.packageName + ": old uid "
7051                                            + origPackage.sharedUser.name
7052                                            + " differs from " + pkg.mSharedUserId);
7053                                    origPackage = null;
7054                                    continue;
7055                                }
7056                            } else {
7057                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7058                                        + pkg.packageName + " to old name " + origPackage.name);
7059                            }
7060                            break;
7061                        }
7062                    }
7063                }
7064            }
7065
7066            if (mTransferedPackages.contains(pkg.packageName)) {
7067                Slog.w(TAG, "Package " + pkg.packageName
7068                        + " was transferred to another, but its .apk remains");
7069            }
7070
7071            // Just create the setting, don't add it yet. For already existing packages
7072            // the PkgSetting exists already and doesn't have to be created.
7073            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7074                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7075                    pkg.applicationInfo.primaryCpuAbi,
7076                    pkg.applicationInfo.secondaryCpuAbi,
7077                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7078                    user, false);
7079            if (pkgSetting == null) {
7080                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7081                        "Creating application package " + pkg.packageName + " failed");
7082            }
7083
7084            if (pkgSetting.origPackage != null) {
7085                // If we are first transitioning from an original package,
7086                // fix up the new package's name now.  We need to do this after
7087                // looking up the package under its new name, so getPackageLP
7088                // can take care of fiddling things correctly.
7089                pkg.setPackageName(origPackage.name);
7090
7091                // File a report about this.
7092                String msg = "New package " + pkgSetting.realName
7093                        + " renamed to replace old package " + pkgSetting.name;
7094                reportSettingsProblem(Log.WARN, msg);
7095
7096                // Make a note of it.
7097                mTransferedPackages.add(origPackage.name);
7098
7099                // No longer need to retain this.
7100                pkgSetting.origPackage = null;
7101            }
7102
7103            if (realName != null) {
7104                // Make a note of it.
7105                mTransferedPackages.add(pkg.packageName);
7106            }
7107
7108            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7109                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7110            }
7111
7112            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7113                // Check all shared libraries and map to their actual file path.
7114                // We only do this here for apps not on a system dir, because those
7115                // are the only ones that can fail an install due to this.  We
7116                // will take care of the system apps by updating all of their
7117                // library paths after the scan is done.
7118                updateSharedLibrariesLPw(pkg, null);
7119            }
7120
7121            if (mFoundPolicyFile) {
7122                SELinuxMMAC.assignSeinfoValue(pkg);
7123            }
7124
7125            pkg.applicationInfo.uid = pkgSetting.appId;
7126            pkg.mExtras = pkgSetting;
7127            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7128                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7129                    // We just determined the app is signed correctly, so bring
7130                    // over the latest parsed certs.
7131                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7132                } else {
7133                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7134                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7135                                "Package " + pkg.packageName + " upgrade keys do not match the "
7136                                + "previously installed version");
7137                    } else {
7138                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7139                        String msg = "System package " + pkg.packageName
7140                            + " signature changed; retaining data.";
7141                        reportSettingsProblem(Log.WARN, msg);
7142                    }
7143                }
7144            } else {
7145                try {
7146                    verifySignaturesLP(pkgSetting, pkg);
7147                    // We just determined the app is signed correctly, so bring
7148                    // over the latest parsed certs.
7149                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7150                } catch (PackageManagerException e) {
7151                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7152                        throw e;
7153                    }
7154                    // The signature has changed, but this package is in the system
7155                    // image...  let's recover!
7156                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7157                    // However...  if this package is part of a shared user, but it
7158                    // doesn't match the signature of the shared user, let's fail.
7159                    // What this means is that you can't change the signatures
7160                    // associated with an overall shared user, which doesn't seem all
7161                    // that unreasonable.
7162                    if (pkgSetting.sharedUser != null) {
7163                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7164                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7165                            throw new PackageManagerException(
7166                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7167                                            "Signature mismatch for shared user: "
7168                                            + pkgSetting.sharedUser);
7169                        }
7170                    }
7171                    // File a report about this.
7172                    String msg = "System package " + pkg.packageName
7173                        + " signature changed; retaining data.";
7174                    reportSettingsProblem(Log.WARN, msg);
7175                }
7176            }
7177            // Verify that this new package doesn't have any content providers
7178            // that conflict with existing packages.  Only do this if the
7179            // package isn't already installed, since we don't want to break
7180            // things that are installed.
7181            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7182                final int N = pkg.providers.size();
7183                int i;
7184                for (i=0; i<N; i++) {
7185                    PackageParser.Provider p = pkg.providers.get(i);
7186                    if (p.info.authority != null) {
7187                        String names[] = p.info.authority.split(";");
7188                        for (int j = 0; j < names.length; j++) {
7189                            if (mProvidersByAuthority.containsKey(names[j])) {
7190                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7191                                final String otherPackageName =
7192                                        ((other != null && other.getComponentName() != null) ?
7193                                                other.getComponentName().getPackageName() : "?");
7194                                throw new PackageManagerException(
7195                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7196                                                "Can't install because provider name " + names[j]
7197                                                + " (in package " + pkg.applicationInfo.packageName
7198                                                + ") is already used by " + otherPackageName);
7199                            }
7200                        }
7201                    }
7202                }
7203            }
7204
7205            if (pkg.mAdoptPermissions != null) {
7206                // This package wants to adopt ownership of permissions from
7207                // another package.
7208                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7209                    final String origName = pkg.mAdoptPermissions.get(i);
7210                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7211                    if (orig != null) {
7212                        if (verifyPackageUpdateLPr(orig, pkg)) {
7213                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7214                                    + pkg.packageName);
7215                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7216                        }
7217                    }
7218                }
7219            }
7220        }
7221
7222        final String pkgName = pkg.packageName;
7223
7224        final long scanFileTime = scanFile.lastModified();
7225        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7226        pkg.applicationInfo.processName = fixProcessName(
7227                pkg.applicationInfo.packageName,
7228                pkg.applicationInfo.processName,
7229                pkg.applicationInfo.uid);
7230
7231        if (pkg != mPlatformPackage) {
7232            // This is a normal package, need to make its data directory.
7233            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7234                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7235
7236            boolean uidError = false;
7237            if (dataPath.exists()) {
7238                int currentUid = 0;
7239                try {
7240                    StructStat stat = Os.stat(dataPath.getPath());
7241                    currentUid = stat.st_uid;
7242                } catch (ErrnoException e) {
7243                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7244                }
7245
7246                // If we have mismatched owners for the data path, we have a problem.
7247                if (currentUid != pkg.applicationInfo.uid) {
7248                    boolean recovered = false;
7249                    if (currentUid == 0) {
7250                        // The directory somehow became owned by root.  Wow.
7251                        // This is probably because the system was stopped while
7252                        // installd was in the middle of messing with its libs
7253                        // directory.  Ask installd to fix that.
7254                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7255                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7256                        if (ret >= 0) {
7257                            recovered = true;
7258                            String msg = "Package " + pkg.packageName
7259                                    + " unexpectedly changed to uid 0; recovered to " +
7260                                    + pkg.applicationInfo.uid;
7261                            reportSettingsProblem(Log.WARN, msg);
7262                        }
7263                    }
7264                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7265                            || (scanFlags&SCAN_BOOTING) != 0)) {
7266                        // If this is a system app, we can at least delete its
7267                        // current data so the application will still work.
7268                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7269                        if (ret >= 0) {
7270                            // TODO: Kill the processes first
7271                            // Old data gone!
7272                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7273                                    ? "System package " : "Third party package ";
7274                            String msg = prefix + pkg.packageName
7275                                    + " has changed from uid: "
7276                                    + currentUid + " to "
7277                                    + pkg.applicationInfo.uid + "; old data erased";
7278                            reportSettingsProblem(Log.WARN, msg);
7279                            recovered = true;
7280                        }
7281                        if (!recovered) {
7282                            mHasSystemUidErrors = true;
7283                        }
7284                    } else if (!recovered) {
7285                        // If we allow this install to proceed, we will be broken.
7286                        // Abort, abort!
7287                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7288                                "scanPackageLI");
7289                    }
7290                    if (!recovered) {
7291                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7292                            + pkg.applicationInfo.uid + "/fs_"
7293                            + currentUid;
7294                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7295                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7296                        String msg = "Package " + pkg.packageName
7297                                + " has mismatched uid: "
7298                                + currentUid + " on disk, "
7299                                + pkg.applicationInfo.uid + " in settings";
7300                        // writer
7301                        synchronized (mPackages) {
7302                            mSettings.mReadMessages.append(msg);
7303                            mSettings.mReadMessages.append('\n');
7304                            uidError = true;
7305                            if (!pkgSetting.uidError) {
7306                                reportSettingsProblem(Log.ERROR, msg);
7307                            }
7308                        }
7309                    }
7310                }
7311
7312                // Ensure that directories are prepared
7313                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7314                        pkg.applicationInfo.seinfo);
7315
7316                if (mShouldRestoreconData) {
7317                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7318                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7319                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7320                }
7321            } else {
7322                if (DEBUG_PACKAGE_SCANNING) {
7323                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7324                        Log.v(TAG, "Want this data dir: " + dataPath);
7325                }
7326                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7327                        pkg.applicationInfo.seinfo);
7328            }
7329
7330            // Get all of our default paths setup
7331            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7332
7333            pkgSetting.uidError = uidError;
7334        }
7335
7336        final String path = scanFile.getPath();
7337        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7338
7339        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7340            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7341
7342            // Some system apps still use directory structure for native libraries
7343            // in which case we might end up not detecting abi solely based on apk
7344            // structure. Try to detect abi based on directory structure.
7345            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7346                    pkg.applicationInfo.primaryCpuAbi == null) {
7347                setBundledAppAbisAndRoots(pkg, pkgSetting);
7348                setNativeLibraryPaths(pkg);
7349            }
7350
7351        } else {
7352            if ((scanFlags & SCAN_MOVE) != 0) {
7353                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7354                // but we already have this packages package info in the PackageSetting. We just
7355                // use that and derive the native library path based on the new codepath.
7356                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7357                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7358            }
7359
7360            // Set native library paths again. For moves, the path will be updated based on the
7361            // ABIs we've determined above. For non-moves, the path will be updated based on the
7362            // ABIs we determined during compilation, but the path will depend on the final
7363            // package path (after the rename away from the stage path).
7364            setNativeLibraryPaths(pkg);
7365        }
7366
7367        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7368        final int[] userIds = sUserManager.getUserIds();
7369        synchronized (mInstallLock) {
7370            // Make sure all user data directories are ready to roll; we're okay
7371            // if they already exist
7372            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7373                for (int userId : userIds) {
7374                    if (userId != UserHandle.USER_SYSTEM) {
7375                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7376                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7377                                pkg.applicationInfo.seinfo);
7378                    }
7379                }
7380            }
7381
7382            // Create a native library symlink only if we have native libraries
7383            // and if the native libraries are 32 bit libraries. We do not provide
7384            // this symlink for 64 bit libraries.
7385            if (pkg.applicationInfo.primaryCpuAbi != null &&
7386                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7387                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7388                try {
7389                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7390                    for (int userId : userIds) {
7391                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7392                                nativeLibPath, userId) < 0) {
7393                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7394                                    "Failed linking native library dir (user=" + userId + ")");
7395                        }
7396                    }
7397                } finally {
7398                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7399                }
7400            }
7401        }
7402
7403        // This is a special case for the "system" package, where the ABI is
7404        // dictated by the zygote configuration (and init.rc). We should keep track
7405        // of this ABI so that we can deal with "normal" applications that run under
7406        // the same UID correctly.
7407        if (mPlatformPackage == pkg) {
7408            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7409                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7410        }
7411
7412        // If there's a mismatch between the abi-override in the package setting
7413        // and the abiOverride specified for the install. Warn about this because we
7414        // would've already compiled the app without taking the package setting into
7415        // account.
7416        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7417            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7418                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7419                        " for package " + pkg.packageName);
7420            }
7421        }
7422
7423        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7424        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7425        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7426
7427        // Copy the derived override back to the parsed package, so that we can
7428        // update the package settings accordingly.
7429        pkg.cpuAbiOverride = cpuAbiOverride;
7430
7431        if (DEBUG_ABI_SELECTION) {
7432            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7433                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7434                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7435        }
7436
7437        // Push the derived path down into PackageSettings so we know what to
7438        // clean up at uninstall time.
7439        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7440
7441        if (DEBUG_ABI_SELECTION) {
7442            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7443                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7444                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7445        }
7446
7447        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7448            // We don't do this here during boot because we can do it all
7449            // at once after scanning all existing packages.
7450            //
7451            // We also do this *before* we perform dexopt on this package, so that
7452            // we can avoid redundant dexopts, and also to make sure we've got the
7453            // code and package path correct.
7454            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7455                    pkg, true /* boot complete */);
7456        }
7457
7458        if (mFactoryTest && pkg.requestedPermissions.contains(
7459                android.Manifest.permission.FACTORY_TEST)) {
7460            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7461        }
7462
7463        ArrayList<PackageParser.Package> clientLibPkgs = null;
7464
7465        // writer
7466        synchronized (mPackages) {
7467            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7468                // Only system apps can add new shared libraries.
7469                if (pkg.libraryNames != null) {
7470                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7471                        String name = pkg.libraryNames.get(i);
7472                        boolean allowed = false;
7473                        if (pkg.isUpdatedSystemApp()) {
7474                            // New library entries can only be added through the
7475                            // system image.  This is important to get rid of a lot
7476                            // of nasty edge cases: for example if we allowed a non-
7477                            // system update of the app to add a library, then uninstalling
7478                            // the update would make the library go away, and assumptions
7479                            // we made such as through app install filtering would now
7480                            // have allowed apps on the device which aren't compatible
7481                            // with it.  Better to just have the restriction here, be
7482                            // conservative, and create many fewer cases that can negatively
7483                            // impact the user experience.
7484                            final PackageSetting sysPs = mSettings
7485                                    .getDisabledSystemPkgLPr(pkg.packageName);
7486                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7487                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7488                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7489                                        allowed = true;
7490                                        break;
7491                                    }
7492                                }
7493                            }
7494                        } else {
7495                            allowed = true;
7496                        }
7497                        if (allowed) {
7498                            if (!mSharedLibraries.containsKey(name)) {
7499                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7500                            } else if (!name.equals(pkg.packageName)) {
7501                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7502                                        + name + " already exists; skipping");
7503                            }
7504                        } else {
7505                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7506                                    + name + " that is not declared on system image; skipping");
7507                        }
7508                    }
7509                    if ((scanFlags & SCAN_BOOTING) == 0) {
7510                        // If we are not booting, we need to update any applications
7511                        // that are clients of our shared library.  If we are booting,
7512                        // this will all be done once the scan is complete.
7513                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7514                    }
7515                }
7516            }
7517        }
7518
7519        // Request the ActivityManager to kill the process(only for existing packages)
7520        // so that we do not end up in a confused state while the user is still using the older
7521        // version of the application while the new one gets installed.
7522        if ((scanFlags & SCAN_REPLACING) != 0) {
7523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7524
7525            killApplication(pkg.applicationInfo.packageName,
7526                        pkg.applicationInfo.uid, "replace pkg");
7527
7528            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7529        }
7530
7531        // Also need to kill any apps that are dependent on the library.
7532        if (clientLibPkgs != null) {
7533            for (int i=0; i<clientLibPkgs.size(); i++) {
7534                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7535                killApplication(clientPkg.applicationInfo.packageName,
7536                        clientPkg.applicationInfo.uid, "update lib");
7537            }
7538        }
7539
7540        // Make sure we're not adding any bogus keyset info
7541        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7542        ksms.assertScannedPackageValid(pkg);
7543
7544        // writer
7545        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7546
7547        boolean createIdmapFailed = false;
7548        synchronized (mPackages) {
7549            // We don't expect installation to fail beyond this point
7550
7551            // Add the new setting to mSettings
7552            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7553            // Add the new setting to mPackages
7554            mPackages.put(pkg.applicationInfo.packageName, pkg);
7555            // Make sure we don't accidentally delete its data.
7556            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7557            while (iter.hasNext()) {
7558                PackageCleanItem item = iter.next();
7559                if (pkgName.equals(item.packageName)) {
7560                    iter.remove();
7561                }
7562            }
7563
7564            // Take care of first install / last update times.
7565            if (currentTime != 0) {
7566                if (pkgSetting.firstInstallTime == 0) {
7567                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7568                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7569                    pkgSetting.lastUpdateTime = currentTime;
7570                }
7571            } else if (pkgSetting.firstInstallTime == 0) {
7572                // We need *something*.  Take time time stamp of the file.
7573                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7574            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7575                if (scanFileTime != pkgSetting.timeStamp) {
7576                    // A package on the system image has changed; consider this
7577                    // to be an update.
7578                    pkgSetting.lastUpdateTime = scanFileTime;
7579                }
7580            }
7581
7582            // Add the package's KeySets to the global KeySetManagerService
7583            ksms.addScannedPackageLPw(pkg);
7584
7585            int N = pkg.providers.size();
7586            StringBuilder r = null;
7587            int i;
7588            for (i=0; i<N; i++) {
7589                PackageParser.Provider p = pkg.providers.get(i);
7590                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7591                        p.info.processName, pkg.applicationInfo.uid);
7592                mProviders.addProvider(p);
7593                p.syncable = p.info.isSyncable;
7594                if (p.info.authority != null) {
7595                    String names[] = p.info.authority.split(";");
7596                    p.info.authority = null;
7597                    for (int j = 0; j < names.length; j++) {
7598                        if (j == 1 && p.syncable) {
7599                            // We only want the first authority for a provider to possibly be
7600                            // syncable, so if we already added this provider using a different
7601                            // authority clear the syncable flag. We copy the provider before
7602                            // changing it because the mProviders object contains a reference
7603                            // to a provider that we don't want to change.
7604                            // Only do this for the second authority since the resulting provider
7605                            // object can be the same for all future authorities for this provider.
7606                            p = new PackageParser.Provider(p);
7607                            p.syncable = false;
7608                        }
7609                        if (!mProvidersByAuthority.containsKey(names[j])) {
7610                            mProvidersByAuthority.put(names[j], p);
7611                            if (p.info.authority == null) {
7612                                p.info.authority = names[j];
7613                            } else {
7614                                p.info.authority = p.info.authority + ";" + names[j];
7615                            }
7616                            if (DEBUG_PACKAGE_SCANNING) {
7617                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7618                                    Log.d(TAG, "Registered content provider: " + names[j]
7619                                            + ", className = " + p.info.name + ", isSyncable = "
7620                                            + p.info.isSyncable);
7621                            }
7622                        } else {
7623                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7624                            Slog.w(TAG, "Skipping provider name " + names[j] +
7625                                    " (in package " + pkg.applicationInfo.packageName +
7626                                    "): name already used by "
7627                                    + ((other != null && other.getComponentName() != null)
7628                                            ? other.getComponentName().getPackageName() : "?"));
7629                        }
7630                    }
7631                }
7632                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7633                    if (r == null) {
7634                        r = new StringBuilder(256);
7635                    } else {
7636                        r.append(' ');
7637                    }
7638                    r.append(p.info.name);
7639                }
7640            }
7641            if (r != null) {
7642                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7643            }
7644
7645            N = pkg.services.size();
7646            r = null;
7647            for (i=0; i<N; i++) {
7648                PackageParser.Service s = pkg.services.get(i);
7649                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7650                        s.info.processName, pkg.applicationInfo.uid);
7651                mServices.addService(s);
7652                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7653                    if (r == null) {
7654                        r = new StringBuilder(256);
7655                    } else {
7656                        r.append(' ');
7657                    }
7658                    r.append(s.info.name);
7659                }
7660            }
7661            if (r != null) {
7662                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7663            }
7664
7665            N = pkg.receivers.size();
7666            r = null;
7667            for (i=0; i<N; i++) {
7668                PackageParser.Activity a = pkg.receivers.get(i);
7669                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7670                        a.info.processName, pkg.applicationInfo.uid);
7671                mReceivers.addActivity(a, "receiver");
7672                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7673                    if (r == null) {
7674                        r = new StringBuilder(256);
7675                    } else {
7676                        r.append(' ');
7677                    }
7678                    r.append(a.info.name);
7679                }
7680            }
7681            if (r != null) {
7682                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7683            }
7684
7685            N = pkg.activities.size();
7686            r = null;
7687            for (i=0; i<N; i++) {
7688                PackageParser.Activity a = pkg.activities.get(i);
7689                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7690                        a.info.processName, pkg.applicationInfo.uid);
7691                mActivities.addActivity(a, "activity");
7692                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7693                    if (r == null) {
7694                        r = new StringBuilder(256);
7695                    } else {
7696                        r.append(' ');
7697                    }
7698                    r.append(a.info.name);
7699                }
7700            }
7701            if (r != null) {
7702                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7703            }
7704
7705            N = pkg.permissionGroups.size();
7706            r = null;
7707            for (i=0; i<N; i++) {
7708                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7709                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7710                if (cur == null) {
7711                    mPermissionGroups.put(pg.info.name, pg);
7712                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7713                        if (r == null) {
7714                            r = new StringBuilder(256);
7715                        } else {
7716                            r.append(' ');
7717                        }
7718                        r.append(pg.info.name);
7719                    }
7720                } else {
7721                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7722                            + pg.info.packageName + " ignored: original from "
7723                            + cur.info.packageName);
7724                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7725                        if (r == null) {
7726                            r = new StringBuilder(256);
7727                        } else {
7728                            r.append(' ');
7729                        }
7730                        r.append("DUP:");
7731                        r.append(pg.info.name);
7732                    }
7733                }
7734            }
7735            if (r != null) {
7736                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7737            }
7738
7739            N = pkg.permissions.size();
7740            r = null;
7741            for (i=0; i<N; i++) {
7742                PackageParser.Permission p = pkg.permissions.get(i);
7743
7744                // Assume by default that we did not install this permission into the system.
7745                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7746
7747                // Now that permission groups have a special meaning, we ignore permission
7748                // groups for legacy apps to prevent unexpected behavior. In particular,
7749                // permissions for one app being granted to someone just becuase they happen
7750                // to be in a group defined by another app (before this had no implications).
7751                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7752                    p.group = mPermissionGroups.get(p.info.group);
7753                    // Warn for a permission in an unknown group.
7754                    if (p.info.group != null && p.group == null) {
7755                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7756                                + p.info.packageName + " in an unknown group " + p.info.group);
7757                    }
7758                }
7759
7760                ArrayMap<String, BasePermission> permissionMap =
7761                        p.tree ? mSettings.mPermissionTrees
7762                                : mSettings.mPermissions;
7763                BasePermission bp = permissionMap.get(p.info.name);
7764
7765                // Allow system apps to redefine non-system permissions
7766                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7767                    final boolean currentOwnerIsSystem = (bp.perm != null
7768                            && isSystemApp(bp.perm.owner));
7769                    if (isSystemApp(p.owner)) {
7770                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7771                            // It's a built-in permission and no owner, take ownership now
7772                            bp.packageSetting = pkgSetting;
7773                            bp.perm = p;
7774                            bp.uid = pkg.applicationInfo.uid;
7775                            bp.sourcePackage = p.info.packageName;
7776                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7777                        } else if (!currentOwnerIsSystem) {
7778                            String msg = "New decl " + p.owner + " of permission  "
7779                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7780                            reportSettingsProblem(Log.WARN, msg);
7781                            bp = null;
7782                        }
7783                    }
7784                }
7785
7786                if (bp == null) {
7787                    bp = new BasePermission(p.info.name, p.info.packageName,
7788                            BasePermission.TYPE_NORMAL);
7789                    permissionMap.put(p.info.name, bp);
7790                }
7791
7792                if (bp.perm == null) {
7793                    if (bp.sourcePackage == null
7794                            || bp.sourcePackage.equals(p.info.packageName)) {
7795                        BasePermission tree = findPermissionTreeLP(p.info.name);
7796                        if (tree == null
7797                                || tree.sourcePackage.equals(p.info.packageName)) {
7798                            bp.packageSetting = pkgSetting;
7799                            bp.perm = p;
7800                            bp.uid = pkg.applicationInfo.uid;
7801                            bp.sourcePackage = p.info.packageName;
7802                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7803                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7804                                if (r == null) {
7805                                    r = new StringBuilder(256);
7806                                } else {
7807                                    r.append(' ');
7808                                }
7809                                r.append(p.info.name);
7810                            }
7811                        } else {
7812                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7813                                    + p.info.packageName + " ignored: base tree "
7814                                    + tree.name + " is from package "
7815                                    + tree.sourcePackage);
7816                        }
7817                    } else {
7818                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7819                                + p.info.packageName + " ignored: original from "
7820                                + bp.sourcePackage);
7821                    }
7822                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7823                    if (r == null) {
7824                        r = new StringBuilder(256);
7825                    } else {
7826                        r.append(' ');
7827                    }
7828                    r.append("DUP:");
7829                    r.append(p.info.name);
7830                }
7831                if (bp.perm == p) {
7832                    bp.protectionLevel = p.info.protectionLevel;
7833                }
7834            }
7835
7836            if (r != null) {
7837                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7838            }
7839
7840            N = pkg.instrumentation.size();
7841            r = null;
7842            for (i=0; i<N; i++) {
7843                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7844                a.info.packageName = pkg.applicationInfo.packageName;
7845                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7846                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7847                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7848                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7849                a.info.dataDir = pkg.applicationInfo.dataDir;
7850                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7851                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7852
7853                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7854                // need other information about the application, like the ABI and what not ?
7855                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7856                mInstrumentation.put(a.getComponentName(), a);
7857                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7858                    if (r == null) {
7859                        r = new StringBuilder(256);
7860                    } else {
7861                        r.append(' ');
7862                    }
7863                    r.append(a.info.name);
7864                }
7865            }
7866            if (r != null) {
7867                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7868            }
7869
7870            if (pkg.protectedBroadcasts != null) {
7871                N = pkg.protectedBroadcasts.size();
7872                for (i=0; i<N; i++) {
7873                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7874                }
7875            }
7876
7877            pkgSetting.setTimeStamp(scanFileTime);
7878
7879            // Create idmap files for pairs of (packages, overlay packages).
7880            // Note: "android", ie framework-res.apk, is handled by native layers.
7881            if (pkg.mOverlayTarget != null) {
7882                // This is an overlay package.
7883                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7884                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7885                        mOverlays.put(pkg.mOverlayTarget,
7886                                new ArrayMap<String, PackageParser.Package>());
7887                    }
7888                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7889                    map.put(pkg.packageName, pkg);
7890                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7891                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7892                        createIdmapFailed = true;
7893                    }
7894                }
7895            } else if (mOverlays.containsKey(pkg.packageName) &&
7896                    !pkg.packageName.equals("android")) {
7897                // This is a regular package, with one or more known overlay packages.
7898                createIdmapsForPackageLI(pkg);
7899            }
7900        }
7901
7902        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7903
7904        if (createIdmapFailed) {
7905            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7906                    "scanPackageLI failed to createIdmap");
7907        }
7908        return pkg;
7909    }
7910
7911    /**
7912     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7913     * is derived purely on the basis of the contents of {@code scanFile} and
7914     * {@code cpuAbiOverride}.
7915     *
7916     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7917     */
7918    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7919                                 String cpuAbiOverride, boolean extractLibs)
7920            throws PackageManagerException {
7921        // TODO: We can probably be smarter about this stuff. For installed apps,
7922        // we can calculate this information at install time once and for all. For
7923        // system apps, we can probably assume that this information doesn't change
7924        // after the first boot scan. As things stand, we do lots of unnecessary work.
7925
7926        // Give ourselves some initial paths; we'll come back for another
7927        // pass once we've determined ABI below.
7928        setNativeLibraryPaths(pkg);
7929
7930        // We would never need to extract libs for forward-locked and external packages,
7931        // since the container service will do it for us. We shouldn't attempt to
7932        // extract libs from system app when it was not updated.
7933        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7934                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7935            extractLibs = false;
7936        }
7937
7938        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7939        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7940
7941        NativeLibraryHelper.Handle handle = null;
7942        try {
7943            handle = NativeLibraryHelper.Handle.create(pkg);
7944            // TODO(multiArch): This can be null for apps that didn't go through the
7945            // usual installation process. We can calculate it again, like we
7946            // do during install time.
7947            //
7948            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7949            // unnecessary.
7950            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7951
7952            // Null out the abis so that they can be recalculated.
7953            pkg.applicationInfo.primaryCpuAbi = null;
7954            pkg.applicationInfo.secondaryCpuAbi = null;
7955            if (isMultiArch(pkg.applicationInfo)) {
7956                // Warn if we've set an abiOverride for multi-lib packages..
7957                // By definition, we need to copy both 32 and 64 bit libraries for
7958                // such packages.
7959                if (pkg.cpuAbiOverride != null
7960                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7961                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7962                }
7963
7964                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7965                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7966                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7967                    if (extractLibs) {
7968                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7969                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7970                                useIsaSpecificSubdirs);
7971                    } else {
7972                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7973                    }
7974                }
7975
7976                maybeThrowExceptionForMultiArchCopy(
7977                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7978
7979                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7980                    if (extractLibs) {
7981                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7982                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7983                                useIsaSpecificSubdirs);
7984                    } else {
7985                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7986                    }
7987                }
7988
7989                maybeThrowExceptionForMultiArchCopy(
7990                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7991
7992                if (abi64 >= 0) {
7993                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7994                }
7995
7996                if (abi32 >= 0) {
7997                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7998                    if (abi64 >= 0) {
7999                        pkg.applicationInfo.secondaryCpuAbi = abi;
8000                    } else {
8001                        pkg.applicationInfo.primaryCpuAbi = abi;
8002                    }
8003                }
8004            } else {
8005                String[] abiList = (cpuAbiOverride != null) ?
8006                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8007
8008                // Enable gross and lame hacks for apps that are built with old
8009                // SDK tools. We must scan their APKs for renderscript bitcode and
8010                // not launch them if it's present. Don't bother checking on devices
8011                // that don't have 64 bit support.
8012                boolean needsRenderScriptOverride = false;
8013                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8014                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8015                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8016                    needsRenderScriptOverride = true;
8017                }
8018
8019                final int copyRet;
8020                if (extractLibs) {
8021                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8022                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8023                } else {
8024                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8025                }
8026
8027                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8028                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8029                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8030                }
8031
8032                if (copyRet >= 0) {
8033                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8034                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8035                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8036                } else if (needsRenderScriptOverride) {
8037                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8038                }
8039            }
8040        } catch (IOException ioe) {
8041            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8042        } finally {
8043            IoUtils.closeQuietly(handle);
8044        }
8045
8046        // Now that we've calculated the ABIs and determined if it's an internal app,
8047        // we will go ahead and populate the nativeLibraryPath.
8048        setNativeLibraryPaths(pkg);
8049    }
8050
8051    /**
8052     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8053     * i.e, so that all packages can be run inside a single process if required.
8054     *
8055     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8056     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8057     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8058     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8059     * updating a package that belongs to a shared user.
8060     *
8061     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8062     * adds unnecessary complexity.
8063     */
8064    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8065            PackageParser.Package scannedPackage, boolean bootComplete) {
8066        String requiredInstructionSet = null;
8067        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8068            requiredInstructionSet = VMRuntime.getInstructionSet(
8069                     scannedPackage.applicationInfo.primaryCpuAbi);
8070        }
8071
8072        PackageSetting requirer = null;
8073        for (PackageSetting ps : packagesForUser) {
8074            // If packagesForUser contains scannedPackage, we skip it. This will happen
8075            // when scannedPackage is an update of an existing package. Without this check,
8076            // we will never be able to change the ABI of any package belonging to a shared
8077            // user, even if it's compatible with other packages.
8078            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8079                if (ps.primaryCpuAbiString == null) {
8080                    continue;
8081                }
8082
8083                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8084                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8085                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8086                    // this but there's not much we can do.
8087                    String errorMessage = "Instruction set mismatch, "
8088                            + ((requirer == null) ? "[caller]" : requirer)
8089                            + " requires " + requiredInstructionSet + " whereas " + ps
8090                            + " requires " + instructionSet;
8091                    Slog.w(TAG, errorMessage);
8092                }
8093
8094                if (requiredInstructionSet == null) {
8095                    requiredInstructionSet = instructionSet;
8096                    requirer = ps;
8097                }
8098            }
8099        }
8100
8101        if (requiredInstructionSet != null) {
8102            String adjustedAbi;
8103            if (requirer != null) {
8104                // requirer != null implies that either scannedPackage was null or that scannedPackage
8105                // did not require an ABI, in which case we have to adjust scannedPackage to match
8106                // the ABI of the set (which is the same as requirer's ABI)
8107                adjustedAbi = requirer.primaryCpuAbiString;
8108                if (scannedPackage != null) {
8109                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8110                }
8111            } else {
8112                // requirer == null implies that we're updating all ABIs in the set to
8113                // match scannedPackage.
8114                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8115            }
8116
8117            for (PackageSetting ps : packagesForUser) {
8118                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8119                    if (ps.primaryCpuAbiString != null) {
8120                        continue;
8121                    }
8122
8123                    ps.primaryCpuAbiString = adjustedAbi;
8124                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8125                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8126                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8127                        mInstaller.rmdex(ps.codePathString,
8128                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8129                    }
8130                }
8131            }
8132        }
8133    }
8134
8135    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8136        synchronized (mPackages) {
8137            mResolverReplaced = true;
8138            // Set up information for custom user intent resolution activity.
8139            mResolveActivity.applicationInfo = pkg.applicationInfo;
8140            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8141            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8142            mResolveActivity.processName = pkg.applicationInfo.packageName;
8143            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8144            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8145                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8146            mResolveActivity.theme = 0;
8147            mResolveActivity.exported = true;
8148            mResolveActivity.enabled = true;
8149            mResolveInfo.activityInfo = mResolveActivity;
8150            mResolveInfo.priority = 0;
8151            mResolveInfo.preferredOrder = 0;
8152            mResolveInfo.match = 0;
8153            mResolveComponentName = mCustomResolverComponentName;
8154            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8155                    mResolveComponentName);
8156        }
8157    }
8158
8159    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8160        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8161
8162        // Set up information for ephemeral installer activity
8163        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8164        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8165        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8166        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8167        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8168        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8169                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8170        mEphemeralInstallerActivity.theme = 0;
8171        mEphemeralInstallerActivity.exported = true;
8172        mEphemeralInstallerActivity.enabled = true;
8173        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8174        mEphemeralInstallerInfo.priority = 0;
8175        mEphemeralInstallerInfo.preferredOrder = 0;
8176        mEphemeralInstallerInfo.match = 0;
8177
8178        if (DEBUG_EPHEMERAL) {
8179            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8180        }
8181    }
8182
8183    private static String calculateBundledApkRoot(final String codePathString) {
8184        final File codePath = new File(codePathString);
8185        final File codeRoot;
8186        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8187            codeRoot = Environment.getRootDirectory();
8188        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8189            codeRoot = Environment.getOemDirectory();
8190        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8191            codeRoot = Environment.getVendorDirectory();
8192        } else {
8193            // Unrecognized code path; take its top real segment as the apk root:
8194            // e.g. /something/app/blah.apk => /something
8195            try {
8196                File f = codePath.getCanonicalFile();
8197                File parent = f.getParentFile();    // non-null because codePath is a file
8198                File tmp;
8199                while ((tmp = parent.getParentFile()) != null) {
8200                    f = parent;
8201                    parent = tmp;
8202                }
8203                codeRoot = f;
8204                Slog.w(TAG, "Unrecognized code path "
8205                        + codePath + " - using " + codeRoot);
8206            } catch (IOException e) {
8207                // Can't canonicalize the code path -- shenanigans?
8208                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8209                return Environment.getRootDirectory().getPath();
8210            }
8211        }
8212        return codeRoot.getPath();
8213    }
8214
8215    /**
8216     * Derive and set the location of native libraries for the given package,
8217     * which varies depending on where and how the package was installed.
8218     */
8219    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8220        final ApplicationInfo info = pkg.applicationInfo;
8221        final String codePath = pkg.codePath;
8222        final File codeFile = new File(codePath);
8223        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8224        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8225
8226        info.nativeLibraryRootDir = null;
8227        info.nativeLibraryRootRequiresIsa = false;
8228        info.nativeLibraryDir = null;
8229        info.secondaryNativeLibraryDir = null;
8230
8231        if (isApkFile(codeFile)) {
8232            // Monolithic install
8233            if (bundledApp) {
8234                // If "/system/lib64/apkname" exists, assume that is the per-package
8235                // native library directory to use; otherwise use "/system/lib/apkname".
8236                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8237                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8238                        getPrimaryInstructionSet(info));
8239
8240                // This is a bundled system app so choose the path based on the ABI.
8241                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8242                // is just the default path.
8243                final String apkName = deriveCodePathName(codePath);
8244                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8245                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8246                        apkName).getAbsolutePath();
8247
8248                if (info.secondaryCpuAbi != null) {
8249                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8250                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8251                            secondaryLibDir, apkName).getAbsolutePath();
8252                }
8253            } else if (asecApp) {
8254                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8255                        .getAbsolutePath();
8256            } else {
8257                final String apkName = deriveCodePathName(codePath);
8258                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8259                        .getAbsolutePath();
8260            }
8261
8262            info.nativeLibraryRootRequiresIsa = false;
8263            info.nativeLibraryDir = info.nativeLibraryRootDir;
8264        } else {
8265            // Cluster install
8266            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8267            info.nativeLibraryRootRequiresIsa = true;
8268
8269            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8270                    getPrimaryInstructionSet(info)).getAbsolutePath();
8271
8272            if (info.secondaryCpuAbi != null) {
8273                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8274                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8275            }
8276        }
8277    }
8278
8279    /**
8280     * Calculate the abis and roots for a bundled app. These can uniquely
8281     * be determined from the contents of the system partition, i.e whether
8282     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8283     * of this information, and instead assume that the system was built
8284     * sensibly.
8285     */
8286    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8287                                           PackageSetting pkgSetting) {
8288        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8289
8290        // If "/system/lib64/apkname" exists, assume that is the per-package
8291        // native library directory to use; otherwise use "/system/lib/apkname".
8292        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8293        setBundledAppAbi(pkg, apkRoot, apkName);
8294        // pkgSetting might be null during rescan following uninstall of updates
8295        // to a bundled app, so accommodate that possibility.  The settings in
8296        // that case will be established later from the parsed package.
8297        //
8298        // If the settings aren't null, sync them up with what we've just derived.
8299        // note that apkRoot isn't stored in the package settings.
8300        if (pkgSetting != null) {
8301            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8302            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8303        }
8304    }
8305
8306    /**
8307     * Deduces the ABI of a bundled app and sets the relevant fields on the
8308     * parsed pkg object.
8309     *
8310     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8311     *        under which system libraries are installed.
8312     * @param apkName the name of the installed package.
8313     */
8314    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8315        final File codeFile = new File(pkg.codePath);
8316
8317        final boolean has64BitLibs;
8318        final boolean has32BitLibs;
8319        if (isApkFile(codeFile)) {
8320            // Monolithic install
8321            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8322            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8323        } else {
8324            // Cluster install
8325            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8326            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8327                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8328                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8329                has64BitLibs = (new File(rootDir, isa)).exists();
8330            } else {
8331                has64BitLibs = false;
8332            }
8333            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8334                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8335                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8336                has32BitLibs = (new File(rootDir, isa)).exists();
8337            } else {
8338                has32BitLibs = false;
8339            }
8340        }
8341
8342        if (has64BitLibs && !has32BitLibs) {
8343            // The package has 64 bit libs, but not 32 bit libs. Its primary
8344            // ABI should be 64 bit. We can safely assume here that the bundled
8345            // native libraries correspond to the most preferred ABI in the list.
8346
8347            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8348            pkg.applicationInfo.secondaryCpuAbi = null;
8349        } else if (has32BitLibs && !has64BitLibs) {
8350            // The package has 32 bit libs but not 64 bit libs. Its primary
8351            // ABI should be 32 bit.
8352
8353            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8354            pkg.applicationInfo.secondaryCpuAbi = null;
8355        } else if (has32BitLibs && has64BitLibs) {
8356            // The application has both 64 and 32 bit bundled libraries. We check
8357            // here that the app declares multiArch support, and warn if it doesn't.
8358            //
8359            // We will be lenient here and record both ABIs. The primary will be the
8360            // ABI that's higher on the list, i.e, a device that's configured to prefer
8361            // 64 bit apps will see a 64 bit primary ABI,
8362
8363            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8364                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8365            }
8366
8367            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8368                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8369                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8370            } else {
8371                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8372                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8373            }
8374        } else {
8375            pkg.applicationInfo.primaryCpuAbi = null;
8376            pkg.applicationInfo.secondaryCpuAbi = null;
8377        }
8378    }
8379
8380    private void killApplication(String pkgName, int appId, String reason) {
8381        // Request the ActivityManager to kill the process(only for existing packages)
8382        // so that we do not end up in a confused state while the user is still using the older
8383        // version of the application while the new one gets installed.
8384        IActivityManager am = ActivityManagerNative.getDefault();
8385        if (am != null) {
8386            try {
8387                am.killApplicationWithAppId(pkgName, appId, reason);
8388            } catch (RemoteException e) {
8389            }
8390        }
8391    }
8392
8393    void removePackageLI(PackageSetting ps, boolean chatty) {
8394        if (DEBUG_INSTALL) {
8395            if (chatty)
8396                Log.d(TAG, "Removing package " + ps.name);
8397        }
8398
8399        // writer
8400        synchronized (mPackages) {
8401            mPackages.remove(ps.name);
8402            final PackageParser.Package pkg = ps.pkg;
8403            if (pkg != null) {
8404                cleanPackageDataStructuresLILPw(pkg, chatty);
8405            }
8406        }
8407    }
8408
8409    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8410        if (DEBUG_INSTALL) {
8411            if (chatty)
8412                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8413        }
8414
8415        // writer
8416        synchronized (mPackages) {
8417            mPackages.remove(pkg.applicationInfo.packageName);
8418            cleanPackageDataStructuresLILPw(pkg, chatty);
8419        }
8420    }
8421
8422    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8423        int N = pkg.providers.size();
8424        StringBuilder r = null;
8425        int i;
8426        for (i=0; i<N; i++) {
8427            PackageParser.Provider p = pkg.providers.get(i);
8428            mProviders.removeProvider(p);
8429            if (p.info.authority == null) {
8430
8431                /* There was another ContentProvider with this authority when
8432                 * this app was installed so this authority is null,
8433                 * Ignore it as we don't have to unregister the provider.
8434                 */
8435                continue;
8436            }
8437            String names[] = p.info.authority.split(";");
8438            for (int j = 0; j < names.length; j++) {
8439                if (mProvidersByAuthority.get(names[j]) == p) {
8440                    mProvidersByAuthority.remove(names[j]);
8441                    if (DEBUG_REMOVE) {
8442                        if (chatty)
8443                            Log.d(TAG, "Unregistered content provider: " + names[j]
8444                                    + ", className = " + p.info.name + ", isSyncable = "
8445                                    + p.info.isSyncable);
8446                    }
8447                }
8448            }
8449            if (DEBUG_REMOVE && chatty) {
8450                if (r == null) {
8451                    r = new StringBuilder(256);
8452                } else {
8453                    r.append(' ');
8454                }
8455                r.append(p.info.name);
8456            }
8457        }
8458        if (r != null) {
8459            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8460        }
8461
8462        N = pkg.services.size();
8463        r = null;
8464        for (i=0; i<N; i++) {
8465            PackageParser.Service s = pkg.services.get(i);
8466            mServices.removeService(s);
8467            if (chatty) {
8468                if (r == null) {
8469                    r = new StringBuilder(256);
8470                } else {
8471                    r.append(' ');
8472                }
8473                r.append(s.info.name);
8474            }
8475        }
8476        if (r != null) {
8477            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8478        }
8479
8480        N = pkg.receivers.size();
8481        r = null;
8482        for (i=0; i<N; i++) {
8483            PackageParser.Activity a = pkg.receivers.get(i);
8484            mReceivers.removeActivity(a, "receiver");
8485            if (DEBUG_REMOVE && chatty) {
8486                if (r == null) {
8487                    r = new StringBuilder(256);
8488                } else {
8489                    r.append(' ');
8490                }
8491                r.append(a.info.name);
8492            }
8493        }
8494        if (r != null) {
8495            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8496        }
8497
8498        N = pkg.activities.size();
8499        r = null;
8500        for (i=0; i<N; i++) {
8501            PackageParser.Activity a = pkg.activities.get(i);
8502            mActivities.removeActivity(a, "activity");
8503            if (DEBUG_REMOVE && chatty) {
8504                if (r == null) {
8505                    r = new StringBuilder(256);
8506                } else {
8507                    r.append(' ');
8508                }
8509                r.append(a.info.name);
8510            }
8511        }
8512        if (r != null) {
8513            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8514        }
8515
8516        N = pkg.permissions.size();
8517        r = null;
8518        for (i=0; i<N; i++) {
8519            PackageParser.Permission p = pkg.permissions.get(i);
8520            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8521            if (bp == null) {
8522                bp = mSettings.mPermissionTrees.get(p.info.name);
8523            }
8524            if (bp != null && bp.perm == p) {
8525                bp.perm = null;
8526                if (DEBUG_REMOVE && chatty) {
8527                    if (r == null) {
8528                        r = new StringBuilder(256);
8529                    } else {
8530                        r.append(' ');
8531                    }
8532                    r.append(p.info.name);
8533                }
8534            }
8535            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8536                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8537                if (appOpPkgs != null) {
8538                    appOpPkgs.remove(pkg.packageName);
8539                }
8540            }
8541        }
8542        if (r != null) {
8543            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8544        }
8545
8546        N = pkg.requestedPermissions.size();
8547        r = null;
8548        for (i=0; i<N; i++) {
8549            String perm = pkg.requestedPermissions.get(i);
8550            BasePermission bp = mSettings.mPermissions.get(perm);
8551            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8552                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8553                if (appOpPkgs != null) {
8554                    appOpPkgs.remove(pkg.packageName);
8555                    if (appOpPkgs.isEmpty()) {
8556                        mAppOpPermissionPackages.remove(perm);
8557                    }
8558                }
8559            }
8560        }
8561        if (r != null) {
8562            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8563        }
8564
8565        N = pkg.instrumentation.size();
8566        r = null;
8567        for (i=0; i<N; i++) {
8568            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8569            mInstrumentation.remove(a.getComponentName());
8570            if (DEBUG_REMOVE && chatty) {
8571                if (r == null) {
8572                    r = new StringBuilder(256);
8573                } else {
8574                    r.append(' ');
8575                }
8576                r.append(a.info.name);
8577            }
8578        }
8579        if (r != null) {
8580            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8581        }
8582
8583        r = null;
8584        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8585            // Only system apps can hold shared libraries.
8586            if (pkg.libraryNames != null) {
8587                for (i=0; i<pkg.libraryNames.size(); i++) {
8588                    String name = pkg.libraryNames.get(i);
8589                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8590                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8591                        mSharedLibraries.remove(name);
8592                        if (DEBUG_REMOVE && chatty) {
8593                            if (r == null) {
8594                                r = new StringBuilder(256);
8595                            } else {
8596                                r.append(' ');
8597                            }
8598                            r.append(name);
8599                        }
8600                    }
8601                }
8602            }
8603        }
8604        if (r != null) {
8605            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8606        }
8607    }
8608
8609    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8610        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8611            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8612                return true;
8613            }
8614        }
8615        return false;
8616    }
8617
8618    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8619    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8620    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8621
8622    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8623            int flags) {
8624        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8625        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8626    }
8627
8628    private void updatePermissionsLPw(String changingPkg,
8629            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8630        // Make sure there are no dangling permission trees.
8631        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8632        while (it.hasNext()) {
8633            final BasePermission bp = it.next();
8634            if (bp.packageSetting == null) {
8635                // We may not yet have parsed the package, so just see if
8636                // we still know about its settings.
8637                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8638            }
8639            if (bp.packageSetting == null) {
8640                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8641                        + " from package " + bp.sourcePackage);
8642                it.remove();
8643            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8644                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8645                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8646                            + " from package " + bp.sourcePackage);
8647                    flags |= UPDATE_PERMISSIONS_ALL;
8648                    it.remove();
8649                }
8650            }
8651        }
8652
8653        // Make sure all dynamic permissions have been assigned to a package,
8654        // and make sure there are no dangling permissions.
8655        it = mSettings.mPermissions.values().iterator();
8656        while (it.hasNext()) {
8657            final BasePermission bp = it.next();
8658            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8659                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8660                        + bp.name + " pkg=" + bp.sourcePackage
8661                        + " info=" + bp.pendingInfo);
8662                if (bp.packageSetting == null && bp.pendingInfo != null) {
8663                    final BasePermission tree = findPermissionTreeLP(bp.name);
8664                    if (tree != null && tree.perm != null) {
8665                        bp.packageSetting = tree.packageSetting;
8666                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8667                                new PermissionInfo(bp.pendingInfo));
8668                        bp.perm.info.packageName = tree.perm.info.packageName;
8669                        bp.perm.info.name = bp.name;
8670                        bp.uid = tree.uid;
8671                    }
8672                }
8673            }
8674            if (bp.packageSetting == null) {
8675                // We may not yet have parsed the package, so just see if
8676                // we still know about its settings.
8677                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8678            }
8679            if (bp.packageSetting == null) {
8680                Slog.w(TAG, "Removing dangling permission: " + bp.name
8681                        + " from package " + bp.sourcePackage);
8682                it.remove();
8683            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8684                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8685                    Slog.i(TAG, "Removing old permission: " + bp.name
8686                            + " from package " + bp.sourcePackage);
8687                    flags |= UPDATE_PERMISSIONS_ALL;
8688                    it.remove();
8689                }
8690            }
8691        }
8692
8693        // Now update the permissions for all packages, in particular
8694        // replace the granted permissions of the system packages.
8695        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8696            for (PackageParser.Package pkg : mPackages.values()) {
8697                if (pkg != pkgInfo) {
8698                    // Only replace for packages on requested volume
8699                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8700                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8701                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8702                    grantPermissionsLPw(pkg, replace, changingPkg);
8703                }
8704            }
8705        }
8706
8707        if (pkgInfo != null) {
8708            // Only replace for packages on requested volume
8709            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8710            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8711                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8712            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8713        }
8714    }
8715
8716    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8717            String packageOfInterest) {
8718        // IMPORTANT: There are two types of permissions: install and runtime.
8719        // Install time permissions are granted when the app is installed to
8720        // all device users and users added in the future. Runtime permissions
8721        // are granted at runtime explicitly to specific users. Normal and signature
8722        // protected permissions are install time permissions. Dangerous permissions
8723        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8724        // otherwise they are runtime permissions. This function does not manage
8725        // runtime permissions except for the case an app targeting Lollipop MR1
8726        // being upgraded to target a newer SDK, in which case dangerous permissions
8727        // are transformed from install time to runtime ones.
8728
8729        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8730        if (ps == null) {
8731            return;
8732        }
8733
8734        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8735
8736        PermissionsState permissionsState = ps.getPermissionsState();
8737        PermissionsState origPermissions = permissionsState;
8738
8739        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8740
8741        boolean runtimePermissionsRevoked = false;
8742        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8743
8744        boolean changedInstallPermission = false;
8745
8746        if (replace) {
8747            ps.installPermissionsFixed = false;
8748            if (!ps.isSharedUser()) {
8749                origPermissions = new PermissionsState(permissionsState);
8750                permissionsState.reset();
8751            } else {
8752                // We need to know only about runtime permission changes since the
8753                // calling code always writes the install permissions state but
8754                // the runtime ones are written only if changed. The only cases of
8755                // changed runtime permissions here are promotion of an install to
8756                // runtime and revocation of a runtime from a shared user.
8757                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8758                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8759                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8760                    runtimePermissionsRevoked = true;
8761                }
8762            }
8763        }
8764
8765        permissionsState.setGlobalGids(mGlobalGids);
8766
8767        final int N = pkg.requestedPermissions.size();
8768        for (int i=0; i<N; i++) {
8769            final String name = pkg.requestedPermissions.get(i);
8770            final BasePermission bp = mSettings.mPermissions.get(name);
8771
8772            if (DEBUG_INSTALL) {
8773                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8774            }
8775
8776            if (bp == null || bp.packageSetting == null) {
8777                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8778                    Slog.w(TAG, "Unknown permission " + name
8779                            + " in package " + pkg.packageName);
8780                }
8781                continue;
8782            }
8783
8784            final String perm = bp.name;
8785            boolean allowedSig = false;
8786            int grant = GRANT_DENIED;
8787
8788            // Keep track of app op permissions.
8789            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8790                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8791                if (pkgs == null) {
8792                    pkgs = new ArraySet<>();
8793                    mAppOpPermissionPackages.put(bp.name, pkgs);
8794                }
8795                pkgs.add(pkg.packageName);
8796            }
8797
8798            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8799            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8800                    >= Build.VERSION_CODES.M;
8801            switch (level) {
8802                case PermissionInfo.PROTECTION_NORMAL: {
8803                    // For all apps normal permissions are install time ones.
8804                    grant = GRANT_INSTALL;
8805                } break;
8806
8807                case PermissionInfo.PROTECTION_DANGEROUS: {
8808                    // If a permission review is required for legacy apps we represent
8809                    // their permissions as always granted runtime ones since we need
8810                    // to keep the review required permission flag per user while an
8811                    // install permission's state is shared across all users.
8812                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8813                        // For legacy apps dangerous permissions are install time ones.
8814                        grant = GRANT_INSTALL;
8815                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8816                        // For legacy apps that became modern, install becomes runtime.
8817                        grant = GRANT_UPGRADE;
8818                    } else if (mPromoteSystemApps
8819                            && isSystemApp(ps)
8820                            && mExistingSystemPackages.contains(ps.name)) {
8821                        // For legacy system apps, install becomes runtime.
8822                        // We cannot check hasInstallPermission() for system apps since those
8823                        // permissions were granted implicitly and not persisted pre-M.
8824                        grant = GRANT_UPGRADE;
8825                    } else {
8826                        // For modern apps keep runtime permissions unchanged.
8827                        grant = GRANT_RUNTIME;
8828                    }
8829                } break;
8830
8831                case PermissionInfo.PROTECTION_SIGNATURE: {
8832                    // For all apps signature permissions are install time ones.
8833                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8834                    if (allowedSig) {
8835                        grant = GRANT_INSTALL;
8836                    }
8837                } break;
8838            }
8839
8840            if (DEBUG_INSTALL) {
8841                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8842            }
8843
8844            if (grant != GRANT_DENIED) {
8845                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8846                    // If this is an existing, non-system package, then
8847                    // we can't add any new permissions to it.
8848                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8849                        // Except...  if this is a permission that was added
8850                        // to the platform (note: need to only do this when
8851                        // updating the platform).
8852                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8853                            grant = GRANT_DENIED;
8854                        }
8855                    }
8856                }
8857
8858                switch (grant) {
8859                    case GRANT_INSTALL: {
8860                        // Revoke this as runtime permission to handle the case of
8861                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8862                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8863                            if (origPermissions.getRuntimePermissionState(
8864                                    bp.name, userId) != null) {
8865                                // Revoke the runtime permission and clear the flags.
8866                                origPermissions.revokeRuntimePermission(bp, userId);
8867                                origPermissions.updatePermissionFlags(bp, userId,
8868                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8869                                // If we revoked a permission permission, we have to write.
8870                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8871                                        changedRuntimePermissionUserIds, userId);
8872                            }
8873                        }
8874                        // Grant an install permission.
8875                        if (permissionsState.grantInstallPermission(bp) !=
8876                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8877                            changedInstallPermission = true;
8878                        }
8879                    } break;
8880
8881                    case GRANT_RUNTIME: {
8882                        // Grant previously granted runtime permissions.
8883                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8884                            PermissionState permissionState = origPermissions
8885                                    .getRuntimePermissionState(bp.name, userId);
8886                            int flags = permissionState != null
8887                                    ? permissionState.getFlags() : 0;
8888                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8889                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8890                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8891                                    // If we cannot put the permission as it was, we have to write.
8892                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8893                                            changedRuntimePermissionUserIds, userId);
8894                                }
8895                                // If the app supports runtime permissions no need for a review.
8896                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8897                                        && appSupportsRuntimePermissions
8898                                        && (flags & PackageManager
8899                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8900                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8901                                    // Since we changed the flags, we have to write.
8902                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8903                                            changedRuntimePermissionUserIds, userId);
8904                                }
8905                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8906                                    && !appSupportsRuntimePermissions) {
8907                                // For legacy apps that need a permission review, every new
8908                                // runtime permission is granted but it is pending a review.
8909                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8910                                    permissionsState.grantRuntimePermission(bp, userId);
8911                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8912                                    // We changed the permission and flags, hence have to write.
8913                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8914                                            changedRuntimePermissionUserIds, userId);
8915                                }
8916                            }
8917                            // Propagate the permission flags.
8918                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8919                        }
8920                    } break;
8921
8922                    case GRANT_UPGRADE: {
8923                        // Grant runtime permissions for a previously held install permission.
8924                        PermissionState permissionState = origPermissions
8925                                .getInstallPermissionState(bp.name);
8926                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8927
8928                        if (origPermissions.revokeInstallPermission(bp)
8929                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8930                            // We will be transferring the permission flags, so clear them.
8931                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8932                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8933                            changedInstallPermission = true;
8934                        }
8935
8936                        // If the permission is not to be promoted to runtime we ignore it and
8937                        // also its other flags as they are not applicable to install permissions.
8938                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8939                            for (int userId : currentUserIds) {
8940                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8941                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8942                                    // Transfer the permission flags.
8943                                    permissionsState.updatePermissionFlags(bp, userId,
8944                                            flags, flags);
8945                                    // If we granted the permission, we have to write.
8946                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8947                                            changedRuntimePermissionUserIds, userId);
8948                                }
8949                            }
8950                        }
8951                    } break;
8952
8953                    default: {
8954                        if (packageOfInterest == null
8955                                || packageOfInterest.equals(pkg.packageName)) {
8956                            Slog.w(TAG, "Not granting permission " + perm
8957                                    + " to package " + pkg.packageName
8958                                    + " because it was previously installed without");
8959                        }
8960                    } break;
8961                }
8962            } else {
8963                if (permissionsState.revokeInstallPermission(bp) !=
8964                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8965                    // Also drop the permission flags.
8966                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8967                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8968                    changedInstallPermission = true;
8969                    Slog.i(TAG, "Un-granting permission " + perm
8970                            + " from package " + pkg.packageName
8971                            + " (protectionLevel=" + bp.protectionLevel
8972                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8973                            + ")");
8974                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8975                    // Don't print warning for app op permissions, since it is fine for them
8976                    // not to be granted, there is a UI for the user to decide.
8977                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8978                        Slog.w(TAG, "Not granting permission " + perm
8979                                + " to package " + pkg.packageName
8980                                + " (protectionLevel=" + bp.protectionLevel
8981                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8982                                + ")");
8983                    }
8984                }
8985            }
8986        }
8987
8988        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8989                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8990            // This is the first that we have heard about this package, so the
8991            // permissions we have now selected are fixed until explicitly
8992            // changed.
8993            ps.installPermissionsFixed = true;
8994        }
8995
8996        // Persist the runtime permissions state for users with changes. If permissions
8997        // were revoked because no app in the shared user declares them we have to
8998        // write synchronously to avoid losing runtime permissions state.
8999        for (int userId : changedRuntimePermissionUserIds) {
9000            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9001        }
9002
9003        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9004    }
9005
9006    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9007        boolean allowed = false;
9008        final int NP = PackageParser.NEW_PERMISSIONS.length;
9009        for (int ip=0; ip<NP; ip++) {
9010            final PackageParser.NewPermissionInfo npi
9011                    = PackageParser.NEW_PERMISSIONS[ip];
9012            if (npi.name.equals(perm)
9013                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9014                allowed = true;
9015                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9016                        + pkg.packageName);
9017                break;
9018            }
9019        }
9020        return allowed;
9021    }
9022
9023    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9024            BasePermission bp, PermissionsState origPermissions) {
9025        boolean allowed;
9026        allowed = (compareSignatures(
9027                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9028                        == PackageManager.SIGNATURE_MATCH)
9029                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9030                        == PackageManager.SIGNATURE_MATCH);
9031        if (!allowed && (bp.protectionLevel
9032                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9033            if (isSystemApp(pkg)) {
9034                // For updated system applications, a system permission
9035                // is granted only if it had been defined by the original application.
9036                if (pkg.isUpdatedSystemApp()) {
9037                    final PackageSetting sysPs = mSettings
9038                            .getDisabledSystemPkgLPr(pkg.packageName);
9039                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9040                        // If the original was granted this permission, we take
9041                        // that grant decision as read and propagate it to the
9042                        // update.
9043                        if (sysPs.isPrivileged()) {
9044                            allowed = true;
9045                        }
9046                    } else {
9047                        // The system apk may have been updated with an older
9048                        // version of the one on the data partition, but which
9049                        // granted a new system permission that it didn't have
9050                        // before.  In this case we do want to allow the app to
9051                        // now get the new permission if the ancestral apk is
9052                        // privileged to get it.
9053                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9054                            for (int j=0;
9055                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9056                                if (perm.equals(
9057                                        sysPs.pkg.requestedPermissions.get(j))) {
9058                                    allowed = true;
9059                                    break;
9060                                }
9061                            }
9062                        }
9063                    }
9064                } else {
9065                    allowed = isPrivilegedApp(pkg);
9066                }
9067            }
9068        }
9069        if (!allowed) {
9070            if (!allowed && (bp.protectionLevel
9071                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9072                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9073                // If this was a previously normal/dangerous permission that got moved
9074                // to a system permission as part of the runtime permission redesign, then
9075                // we still want to blindly grant it to old apps.
9076                allowed = true;
9077            }
9078            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9079                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9080                // If this permission is to be granted to the system installer and
9081                // this app is an installer, then it gets the permission.
9082                allowed = true;
9083            }
9084            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9085                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9086                // If this permission is to be granted to the system verifier and
9087                // this app is a verifier, then it gets the permission.
9088                allowed = true;
9089            }
9090            if (!allowed && (bp.protectionLevel
9091                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9092                    && isSystemApp(pkg)) {
9093                // Any pre-installed system app is allowed to get this permission.
9094                allowed = true;
9095            }
9096            if (!allowed && (bp.protectionLevel
9097                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9098                // For development permissions, a development permission
9099                // is granted only if it was already granted.
9100                allowed = origPermissions.hasInstallPermission(perm);
9101            }
9102        }
9103        return allowed;
9104    }
9105
9106    final class ActivityIntentResolver
9107            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9108        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9109                boolean defaultOnly, int userId) {
9110            if (!sUserManager.exists(userId)) return null;
9111            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9112            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9113        }
9114
9115        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9116                int userId) {
9117            if (!sUserManager.exists(userId)) return null;
9118            mFlags = flags;
9119            return super.queryIntent(intent, resolvedType,
9120                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9121        }
9122
9123        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9124                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9125            if (!sUserManager.exists(userId)) return null;
9126            if (packageActivities == null) {
9127                return null;
9128            }
9129            mFlags = flags;
9130            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9131            final int N = packageActivities.size();
9132            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9133                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9134
9135            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9136            for (int i = 0; i < N; ++i) {
9137                intentFilters = packageActivities.get(i).intents;
9138                if (intentFilters != null && intentFilters.size() > 0) {
9139                    PackageParser.ActivityIntentInfo[] array =
9140                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9141                    intentFilters.toArray(array);
9142                    listCut.add(array);
9143                }
9144            }
9145            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9146        }
9147
9148        public final void addActivity(PackageParser.Activity a, String type) {
9149            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9150            mActivities.put(a.getComponentName(), a);
9151            if (DEBUG_SHOW_INFO)
9152                Log.v(
9153                TAG, "  " + type + " " +
9154                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9155            if (DEBUG_SHOW_INFO)
9156                Log.v(TAG, "    Class=" + a.info.name);
9157            final int NI = a.intents.size();
9158            for (int j=0; j<NI; j++) {
9159                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9160                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9161                    intent.setPriority(0);
9162                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9163                            + a.className + " with priority > 0, forcing to 0");
9164                }
9165                if (DEBUG_SHOW_INFO) {
9166                    Log.v(TAG, "    IntentFilter:");
9167                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9168                }
9169                if (!intent.debugCheck()) {
9170                    Log.w(TAG, "==> For Activity " + a.info.name);
9171                }
9172                addFilter(intent);
9173            }
9174        }
9175
9176        public final void removeActivity(PackageParser.Activity a, String type) {
9177            mActivities.remove(a.getComponentName());
9178            if (DEBUG_SHOW_INFO) {
9179                Log.v(TAG, "  " + type + " "
9180                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9181                                : a.info.name) + ":");
9182                Log.v(TAG, "    Class=" + a.info.name);
9183            }
9184            final int NI = a.intents.size();
9185            for (int j=0; j<NI; j++) {
9186                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9187                if (DEBUG_SHOW_INFO) {
9188                    Log.v(TAG, "    IntentFilter:");
9189                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9190                }
9191                removeFilter(intent);
9192            }
9193        }
9194
9195        @Override
9196        protected boolean allowFilterResult(
9197                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9198            ActivityInfo filterAi = filter.activity.info;
9199            for (int i=dest.size()-1; i>=0; i--) {
9200                ActivityInfo destAi = dest.get(i).activityInfo;
9201                if (destAi.name == filterAi.name
9202                        && destAi.packageName == filterAi.packageName) {
9203                    return false;
9204                }
9205            }
9206            return true;
9207        }
9208
9209        @Override
9210        protected ActivityIntentInfo[] newArray(int size) {
9211            return new ActivityIntentInfo[size];
9212        }
9213
9214        @Override
9215        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9216            if (!sUserManager.exists(userId)) return true;
9217            PackageParser.Package p = filter.activity.owner;
9218            if (p != null) {
9219                PackageSetting ps = (PackageSetting)p.mExtras;
9220                if (ps != null) {
9221                    // System apps are never considered stopped for purposes of
9222                    // filtering, because there may be no way for the user to
9223                    // actually re-launch them.
9224                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9225                            && ps.getStopped(userId);
9226                }
9227            }
9228            return false;
9229        }
9230
9231        @Override
9232        protected boolean isPackageForFilter(String packageName,
9233                PackageParser.ActivityIntentInfo info) {
9234            return packageName.equals(info.activity.owner.packageName);
9235        }
9236
9237        @Override
9238        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9239                int match, int userId) {
9240            if (!sUserManager.exists(userId)) return null;
9241            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9242                return null;
9243            }
9244            final PackageParser.Activity activity = info.activity;
9245            if (mSafeMode && (activity.info.applicationInfo.flags
9246                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9247                return null;
9248            }
9249            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9250            if (ps == null) {
9251                return null;
9252            }
9253            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9254                    ps.readUserState(userId), userId);
9255            if (ai == null) {
9256                return null;
9257            }
9258            final ResolveInfo res = new ResolveInfo();
9259            res.activityInfo = ai;
9260            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9261                res.filter = info;
9262            }
9263            if (info != null) {
9264                res.handleAllWebDataURI = info.handleAllWebDataURI();
9265            }
9266            res.priority = info.getPriority();
9267            res.preferredOrder = activity.owner.mPreferredOrder;
9268            //System.out.println("Result: " + res.activityInfo.className +
9269            //                   " = " + res.priority);
9270            res.match = match;
9271            res.isDefault = info.hasDefault;
9272            res.labelRes = info.labelRes;
9273            res.nonLocalizedLabel = info.nonLocalizedLabel;
9274            if (userNeedsBadging(userId)) {
9275                res.noResourceId = true;
9276            } else {
9277                res.icon = info.icon;
9278            }
9279            res.iconResourceId = info.icon;
9280            res.system = res.activityInfo.applicationInfo.isSystemApp();
9281            return res;
9282        }
9283
9284        @Override
9285        protected void sortResults(List<ResolveInfo> results) {
9286            Collections.sort(results, mResolvePrioritySorter);
9287        }
9288
9289        @Override
9290        protected void dumpFilter(PrintWriter out, String prefix,
9291                PackageParser.ActivityIntentInfo filter) {
9292            out.print(prefix); out.print(
9293                    Integer.toHexString(System.identityHashCode(filter.activity)));
9294                    out.print(' ');
9295                    filter.activity.printComponentShortName(out);
9296                    out.print(" filter ");
9297                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9298        }
9299
9300        @Override
9301        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9302            return filter.activity;
9303        }
9304
9305        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9306            PackageParser.Activity activity = (PackageParser.Activity)label;
9307            out.print(prefix); out.print(
9308                    Integer.toHexString(System.identityHashCode(activity)));
9309                    out.print(' ');
9310                    activity.printComponentShortName(out);
9311            if (count > 1) {
9312                out.print(" ("); out.print(count); out.print(" filters)");
9313            }
9314            out.println();
9315        }
9316
9317//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9318//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9319//            final List<ResolveInfo> retList = Lists.newArrayList();
9320//            while (i.hasNext()) {
9321//                final ResolveInfo resolveInfo = i.next();
9322//                if (isEnabledLP(resolveInfo.activityInfo)) {
9323//                    retList.add(resolveInfo);
9324//                }
9325//            }
9326//            return retList;
9327//        }
9328
9329        // Keys are String (activity class name), values are Activity.
9330        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9331                = new ArrayMap<ComponentName, PackageParser.Activity>();
9332        private int mFlags;
9333    }
9334
9335    private final class ServiceIntentResolver
9336            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9337        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9338                boolean defaultOnly, int userId) {
9339            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9340            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9341        }
9342
9343        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9344                int userId) {
9345            if (!sUserManager.exists(userId)) return null;
9346            mFlags = flags;
9347            return super.queryIntent(intent, resolvedType,
9348                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9349        }
9350
9351        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9352                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9353            if (!sUserManager.exists(userId)) return null;
9354            if (packageServices == null) {
9355                return null;
9356            }
9357            mFlags = flags;
9358            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9359            final int N = packageServices.size();
9360            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9361                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9362
9363            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9364            for (int i = 0; i < N; ++i) {
9365                intentFilters = packageServices.get(i).intents;
9366                if (intentFilters != null && intentFilters.size() > 0) {
9367                    PackageParser.ServiceIntentInfo[] array =
9368                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9369                    intentFilters.toArray(array);
9370                    listCut.add(array);
9371                }
9372            }
9373            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9374        }
9375
9376        public final void addService(PackageParser.Service s) {
9377            mServices.put(s.getComponentName(), s);
9378            if (DEBUG_SHOW_INFO) {
9379                Log.v(TAG, "  "
9380                        + (s.info.nonLocalizedLabel != null
9381                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9382                Log.v(TAG, "    Class=" + s.info.name);
9383            }
9384            final int NI = s.intents.size();
9385            int j;
9386            for (j=0; j<NI; j++) {
9387                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9388                if (DEBUG_SHOW_INFO) {
9389                    Log.v(TAG, "    IntentFilter:");
9390                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9391                }
9392                if (!intent.debugCheck()) {
9393                    Log.w(TAG, "==> For Service " + s.info.name);
9394                }
9395                addFilter(intent);
9396            }
9397        }
9398
9399        public final void removeService(PackageParser.Service s) {
9400            mServices.remove(s.getComponentName());
9401            if (DEBUG_SHOW_INFO) {
9402                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9403                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9404                Log.v(TAG, "    Class=" + s.info.name);
9405            }
9406            final int NI = s.intents.size();
9407            int j;
9408            for (j=0; j<NI; j++) {
9409                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9410                if (DEBUG_SHOW_INFO) {
9411                    Log.v(TAG, "    IntentFilter:");
9412                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9413                }
9414                removeFilter(intent);
9415            }
9416        }
9417
9418        @Override
9419        protected boolean allowFilterResult(
9420                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9421            ServiceInfo filterSi = filter.service.info;
9422            for (int i=dest.size()-1; i>=0; i--) {
9423                ServiceInfo destAi = dest.get(i).serviceInfo;
9424                if (destAi.name == filterSi.name
9425                        && destAi.packageName == filterSi.packageName) {
9426                    return false;
9427                }
9428            }
9429            return true;
9430        }
9431
9432        @Override
9433        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9434            return new PackageParser.ServiceIntentInfo[size];
9435        }
9436
9437        @Override
9438        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9439            if (!sUserManager.exists(userId)) return true;
9440            PackageParser.Package p = filter.service.owner;
9441            if (p != null) {
9442                PackageSetting ps = (PackageSetting)p.mExtras;
9443                if (ps != null) {
9444                    // System apps are never considered stopped for purposes of
9445                    // filtering, because there may be no way for the user to
9446                    // actually re-launch them.
9447                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9448                            && ps.getStopped(userId);
9449                }
9450            }
9451            return false;
9452        }
9453
9454        @Override
9455        protected boolean isPackageForFilter(String packageName,
9456                PackageParser.ServiceIntentInfo info) {
9457            return packageName.equals(info.service.owner.packageName);
9458        }
9459
9460        @Override
9461        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9462                int match, int userId) {
9463            if (!sUserManager.exists(userId)) return null;
9464            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9465            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9466                return null;
9467            }
9468            final PackageParser.Service service = info.service;
9469            if (mSafeMode && (service.info.applicationInfo.flags
9470                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9471                return null;
9472            }
9473            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9474            if (ps == null) {
9475                return null;
9476            }
9477            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9478                    ps.readUserState(userId), userId);
9479            if (si == null) {
9480                return null;
9481            }
9482            final ResolveInfo res = new ResolveInfo();
9483            res.serviceInfo = si;
9484            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9485                res.filter = filter;
9486            }
9487            res.priority = info.getPriority();
9488            res.preferredOrder = service.owner.mPreferredOrder;
9489            res.match = match;
9490            res.isDefault = info.hasDefault;
9491            res.labelRes = info.labelRes;
9492            res.nonLocalizedLabel = info.nonLocalizedLabel;
9493            res.icon = info.icon;
9494            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9495            return res;
9496        }
9497
9498        @Override
9499        protected void sortResults(List<ResolveInfo> results) {
9500            Collections.sort(results, mResolvePrioritySorter);
9501        }
9502
9503        @Override
9504        protected void dumpFilter(PrintWriter out, String prefix,
9505                PackageParser.ServiceIntentInfo filter) {
9506            out.print(prefix); out.print(
9507                    Integer.toHexString(System.identityHashCode(filter.service)));
9508                    out.print(' ');
9509                    filter.service.printComponentShortName(out);
9510                    out.print(" filter ");
9511                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9512        }
9513
9514        @Override
9515        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9516            return filter.service;
9517        }
9518
9519        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9520            PackageParser.Service service = (PackageParser.Service)label;
9521            out.print(prefix); out.print(
9522                    Integer.toHexString(System.identityHashCode(service)));
9523                    out.print(' ');
9524                    service.printComponentShortName(out);
9525            if (count > 1) {
9526                out.print(" ("); out.print(count); out.print(" filters)");
9527            }
9528            out.println();
9529        }
9530
9531//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9532//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9533//            final List<ResolveInfo> retList = Lists.newArrayList();
9534//            while (i.hasNext()) {
9535//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9536//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9537//                    retList.add(resolveInfo);
9538//                }
9539//            }
9540//            return retList;
9541//        }
9542
9543        // Keys are String (activity class name), values are Activity.
9544        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9545                = new ArrayMap<ComponentName, PackageParser.Service>();
9546        private int mFlags;
9547    };
9548
9549    private final class ProviderIntentResolver
9550            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9551        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9552                boolean defaultOnly, int userId) {
9553            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9554            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9555        }
9556
9557        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9558                int userId) {
9559            if (!sUserManager.exists(userId))
9560                return null;
9561            mFlags = flags;
9562            return super.queryIntent(intent, resolvedType,
9563                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9564        }
9565
9566        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9567                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9568            if (!sUserManager.exists(userId))
9569                return null;
9570            if (packageProviders == null) {
9571                return null;
9572            }
9573            mFlags = flags;
9574            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9575            final int N = packageProviders.size();
9576            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9577                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9578
9579            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9580            for (int i = 0; i < N; ++i) {
9581                intentFilters = packageProviders.get(i).intents;
9582                if (intentFilters != null && intentFilters.size() > 0) {
9583                    PackageParser.ProviderIntentInfo[] array =
9584                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9585                    intentFilters.toArray(array);
9586                    listCut.add(array);
9587                }
9588            }
9589            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9590        }
9591
9592        public final void addProvider(PackageParser.Provider p) {
9593            if (mProviders.containsKey(p.getComponentName())) {
9594                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9595                return;
9596            }
9597
9598            mProviders.put(p.getComponentName(), p);
9599            if (DEBUG_SHOW_INFO) {
9600                Log.v(TAG, "  "
9601                        + (p.info.nonLocalizedLabel != null
9602                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9603                Log.v(TAG, "    Class=" + p.info.name);
9604            }
9605            final int NI = p.intents.size();
9606            int j;
9607            for (j = 0; j < NI; j++) {
9608                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9609                if (DEBUG_SHOW_INFO) {
9610                    Log.v(TAG, "    IntentFilter:");
9611                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9612                }
9613                if (!intent.debugCheck()) {
9614                    Log.w(TAG, "==> For Provider " + p.info.name);
9615                }
9616                addFilter(intent);
9617            }
9618        }
9619
9620        public final void removeProvider(PackageParser.Provider p) {
9621            mProviders.remove(p.getComponentName());
9622            if (DEBUG_SHOW_INFO) {
9623                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9624                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9625                Log.v(TAG, "    Class=" + p.info.name);
9626            }
9627            final int NI = p.intents.size();
9628            int j;
9629            for (j = 0; j < NI; j++) {
9630                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9631                if (DEBUG_SHOW_INFO) {
9632                    Log.v(TAG, "    IntentFilter:");
9633                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9634                }
9635                removeFilter(intent);
9636            }
9637        }
9638
9639        @Override
9640        protected boolean allowFilterResult(
9641                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9642            ProviderInfo filterPi = filter.provider.info;
9643            for (int i = dest.size() - 1; i >= 0; i--) {
9644                ProviderInfo destPi = dest.get(i).providerInfo;
9645                if (destPi.name == filterPi.name
9646                        && destPi.packageName == filterPi.packageName) {
9647                    return false;
9648                }
9649            }
9650            return true;
9651        }
9652
9653        @Override
9654        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9655            return new PackageParser.ProviderIntentInfo[size];
9656        }
9657
9658        @Override
9659        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9660            if (!sUserManager.exists(userId))
9661                return true;
9662            PackageParser.Package p = filter.provider.owner;
9663            if (p != null) {
9664                PackageSetting ps = (PackageSetting) p.mExtras;
9665                if (ps != null) {
9666                    // System apps are never considered stopped for purposes of
9667                    // filtering, because there may be no way for the user to
9668                    // actually re-launch them.
9669                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9670                            && ps.getStopped(userId);
9671                }
9672            }
9673            return false;
9674        }
9675
9676        @Override
9677        protected boolean isPackageForFilter(String packageName,
9678                PackageParser.ProviderIntentInfo info) {
9679            return packageName.equals(info.provider.owner.packageName);
9680        }
9681
9682        @Override
9683        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9684                int match, int userId) {
9685            if (!sUserManager.exists(userId))
9686                return null;
9687            final PackageParser.ProviderIntentInfo info = filter;
9688            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9689                return null;
9690            }
9691            final PackageParser.Provider provider = info.provider;
9692            if (mSafeMode && (provider.info.applicationInfo.flags
9693                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9694                return null;
9695            }
9696            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9697            if (ps == null) {
9698                return null;
9699            }
9700            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9701                    ps.readUserState(userId), userId);
9702            if (pi == null) {
9703                return null;
9704            }
9705            final ResolveInfo res = new ResolveInfo();
9706            res.providerInfo = pi;
9707            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9708                res.filter = filter;
9709            }
9710            res.priority = info.getPriority();
9711            res.preferredOrder = provider.owner.mPreferredOrder;
9712            res.match = match;
9713            res.isDefault = info.hasDefault;
9714            res.labelRes = info.labelRes;
9715            res.nonLocalizedLabel = info.nonLocalizedLabel;
9716            res.icon = info.icon;
9717            res.system = res.providerInfo.applicationInfo.isSystemApp();
9718            return res;
9719        }
9720
9721        @Override
9722        protected void sortResults(List<ResolveInfo> results) {
9723            Collections.sort(results, mResolvePrioritySorter);
9724        }
9725
9726        @Override
9727        protected void dumpFilter(PrintWriter out, String prefix,
9728                PackageParser.ProviderIntentInfo filter) {
9729            out.print(prefix);
9730            out.print(
9731                    Integer.toHexString(System.identityHashCode(filter.provider)));
9732            out.print(' ');
9733            filter.provider.printComponentShortName(out);
9734            out.print(" filter ");
9735            out.println(Integer.toHexString(System.identityHashCode(filter)));
9736        }
9737
9738        @Override
9739        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9740            return filter.provider;
9741        }
9742
9743        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9744            PackageParser.Provider provider = (PackageParser.Provider)label;
9745            out.print(prefix); out.print(
9746                    Integer.toHexString(System.identityHashCode(provider)));
9747                    out.print(' ');
9748                    provider.printComponentShortName(out);
9749            if (count > 1) {
9750                out.print(" ("); out.print(count); out.print(" filters)");
9751            }
9752            out.println();
9753        }
9754
9755        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9756                = new ArrayMap<ComponentName, PackageParser.Provider>();
9757        private int mFlags;
9758    }
9759
9760    private static final class EphemeralIntentResolver
9761            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9762        @Override
9763        protected EphemeralResolveIntentInfo[] newArray(int size) {
9764            return new EphemeralResolveIntentInfo[size];
9765        }
9766
9767        @Override
9768        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9769            return true;
9770        }
9771
9772        @Override
9773        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9774                int userId) {
9775            if (!sUserManager.exists(userId)) {
9776                return null;
9777            }
9778            return info.getEphemeralResolveInfo();
9779        }
9780    }
9781
9782    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9783            new Comparator<ResolveInfo>() {
9784        public int compare(ResolveInfo r1, ResolveInfo r2) {
9785            int v1 = r1.priority;
9786            int v2 = r2.priority;
9787            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9788            if (v1 != v2) {
9789                return (v1 > v2) ? -1 : 1;
9790            }
9791            v1 = r1.preferredOrder;
9792            v2 = r2.preferredOrder;
9793            if (v1 != v2) {
9794                return (v1 > v2) ? -1 : 1;
9795            }
9796            if (r1.isDefault != r2.isDefault) {
9797                return r1.isDefault ? -1 : 1;
9798            }
9799            v1 = r1.match;
9800            v2 = r2.match;
9801            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9802            if (v1 != v2) {
9803                return (v1 > v2) ? -1 : 1;
9804            }
9805            if (r1.system != r2.system) {
9806                return r1.system ? -1 : 1;
9807            }
9808            if (r1.activityInfo != null) {
9809                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9810            }
9811            if (r1.serviceInfo != null) {
9812                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9813            }
9814            if (r1.providerInfo != null) {
9815                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9816            }
9817            return 0;
9818        }
9819    };
9820
9821    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9822            new Comparator<ProviderInfo>() {
9823        public int compare(ProviderInfo p1, ProviderInfo p2) {
9824            final int v1 = p1.initOrder;
9825            final int v2 = p2.initOrder;
9826            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9827        }
9828    };
9829
9830    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9831            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9832            final int[] userIds) {
9833        mHandler.post(new Runnable() {
9834            @Override
9835            public void run() {
9836                try {
9837                    final IActivityManager am = ActivityManagerNative.getDefault();
9838                    if (am == null) return;
9839                    final int[] resolvedUserIds;
9840                    if (userIds == null) {
9841                        resolvedUserIds = am.getRunningUserIds();
9842                    } else {
9843                        resolvedUserIds = userIds;
9844                    }
9845                    for (int id : resolvedUserIds) {
9846                        final Intent intent = new Intent(action,
9847                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9848                        if (extras != null) {
9849                            intent.putExtras(extras);
9850                        }
9851                        if (targetPkg != null) {
9852                            intent.setPackage(targetPkg);
9853                        }
9854                        // Modify the UID when posting to other users
9855                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9856                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9857                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9858                            intent.putExtra(Intent.EXTRA_UID, uid);
9859                        }
9860                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9861                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9862                        if (DEBUG_BROADCASTS) {
9863                            RuntimeException here = new RuntimeException("here");
9864                            here.fillInStackTrace();
9865                            Slog.d(TAG, "Sending to user " + id + ": "
9866                                    + intent.toShortString(false, true, false, false)
9867                                    + " " + intent.getExtras(), here);
9868                        }
9869                        am.broadcastIntent(null, intent, null, finishedReceiver,
9870                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9871                                null, finishedReceiver != null, false, id);
9872                    }
9873                } catch (RemoteException ex) {
9874                }
9875            }
9876        });
9877    }
9878
9879    /**
9880     * Check if the external storage media is available. This is true if there
9881     * is a mounted external storage medium or if the external storage is
9882     * emulated.
9883     */
9884    private boolean isExternalMediaAvailable() {
9885        return mMediaMounted || Environment.isExternalStorageEmulated();
9886    }
9887
9888    @Override
9889    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9890        // writer
9891        synchronized (mPackages) {
9892            if (!isExternalMediaAvailable()) {
9893                // If the external storage is no longer mounted at this point,
9894                // the caller may not have been able to delete all of this
9895                // packages files and can not delete any more.  Bail.
9896                return null;
9897            }
9898            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9899            if (lastPackage != null) {
9900                pkgs.remove(lastPackage);
9901            }
9902            if (pkgs.size() > 0) {
9903                return pkgs.get(0);
9904            }
9905        }
9906        return null;
9907    }
9908
9909    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9910        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9911                userId, andCode ? 1 : 0, packageName);
9912        if (mSystemReady) {
9913            msg.sendToTarget();
9914        } else {
9915            if (mPostSystemReadyMessages == null) {
9916                mPostSystemReadyMessages = new ArrayList<>();
9917            }
9918            mPostSystemReadyMessages.add(msg);
9919        }
9920    }
9921
9922    void startCleaningPackages() {
9923        // reader
9924        synchronized (mPackages) {
9925            if (!isExternalMediaAvailable()) {
9926                return;
9927            }
9928            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9929                return;
9930            }
9931        }
9932        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9933        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9934        IActivityManager am = ActivityManagerNative.getDefault();
9935        if (am != null) {
9936            try {
9937                am.startService(null, intent, null, mContext.getOpPackageName(),
9938                        UserHandle.USER_SYSTEM);
9939            } catch (RemoteException e) {
9940            }
9941        }
9942    }
9943
9944    @Override
9945    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9946            int installFlags, String installerPackageName, VerificationParams verificationParams,
9947            String packageAbiOverride) {
9948        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9949                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9950    }
9951
9952    @Override
9953    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9954            int installFlags, String installerPackageName, VerificationParams verificationParams,
9955            String packageAbiOverride, int userId) {
9956        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9957
9958        final int callingUid = Binder.getCallingUid();
9959        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9960
9961        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9962            try {
9963                if (observer != null) {
9964                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9965                }
9966            } catch (RemoteException re) {
9967            }
9968            return;
9969        }
9970
9971        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9972            installFlags |= PackageManager.INSTALL_FROM_ADB;
9973
9974        } else {
9975            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9976            // about installerPackageName.
9977
9978            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9979            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9980        }
9981
9982        UserHandle user;
9983        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9984            user = UserHandle.ALL;
9985        } else {
9986            user = new UserHandle(userId);
9987        }
9988
9989        // Only system components can circumvent runtime permissions when installing.
9990        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9991                && mContext.checkCallingOrSelfPermission(Manifest.permission
9992                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9993            throw new SecurityException("You need the "
9994                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9995                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9996        }
9997
9998        verificationParams.setInstallerUid(callingUid);
9999
10000        final File originFile = new File(originPath);
10001        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10002
10003        final Message msg = mHandler.obtainMessage(INIT_COPY);
10004        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10005                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10006        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10007        msg.obj = params;
10008
10009        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10010                System.identityHashCode(msg.obj));
10011        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10012                System.identityHashCode(msg.obj));
10013
10014        mHandler.sendMessage(msg);
10015    }
10016
10017    void installStage(String packageName, File stagedDir, String stagedCid,
10018            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10019            String installerPackageName, int installerUid, UserHandle user) {
10020        if (DEBUG_EPHEMERAL) {
10021            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10022                Slog.d(TAG, "Ephemeral install of " + packageName);
10023            }
10024        }
10025        final VerificationParams verifParams = new VerificationParams(
10026                null, sessionParams.originatingUri, sessionParams.referrerUri,
10027                sessionParams.originatingUid);
10028        verifParams.setInstallerUid(installerUid);
10029
10030        final OriginInfo origin;
10031        if (stagedDir != null) {
10032            origin = OriginInfo.fromStagedFile(stagedDir);
10033        } else {
10034            origin = OriginInfo.fromStagedContainer(stagedCid);
10035        }
10036
10037        final Message msg = mHandler.obtainMessage(INIT_COPY);
10038        final InstallParams params = new InstallParams(origin, null, observer,
10039                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10040                verifParams, user, sessionParams.abiOverride,
10041                sessionParams.grantedRuntimePermissions);
10042        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10043        msg.obj = params;
10044
10045        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10046                System.identityHashCode(msg.obj));
10047        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10048                System.identityHashCode(msg.obj));
10049
10050        mHandler.sendMessage(msg);
10051    }
10052
10053    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10054        Bundle extras = new Bundle(1);
10055        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10056
10057        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10058                packageName, extras, 0, null, null, new int[] {userId});
10059        try {
10060            IActivityManager am = ActivityManagerNative.getDefault();
10061            final boolean isSystem =
10062                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10063            if (isSystem && am.isUserRunning(userId, 0)) {
10064                // The just-installed/enabled app is bundled on the system, so presumed
10065                // to be able to run automatically without needing an explicit launch.
10066                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10067                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10068                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10069                        .setPackage(packageName);
10070                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10071                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10072            }
10073        } catch (RemoteException e) {
10074            // shouldn't happen
10075            Slog.w(TAG, "Unable to bootstrap installed package", e);
10076        }
10077    }
10078
10079    @Override
10080    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10081            int userId) {
10082        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10083        PackageSetting pkgSetting;
10084        final int uid = Binder.getCallingUid();
10085        enforceCrossUserPermission(uid, userId, true, true,
10086                "setApplicationHiddenSetting for user " + userId);
10087
10088        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10089            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10090            return false;
10091        }
10092
10093        long callingId = Binder.clearCallingIdentity();
10094        try {
10095            boolean sendAdded = false;
10096            boolean sendRemoved = false;
10097            // writer
10098            synchronized (mPackages) {
10099                pkgSetting = mSettings.mPackages.get(packageName);
10100                if (pkgSetting == null) {
10101                    return false;
10102                }
10103                if (pkgSetting.getHidden(userId) != hidden) {
10104                    pkgSetting.setHidden(hidden, userId);
10105                    mSettings.writePackageRestrictionsLPr(userId);
10106                    if (hidden) {
10107                        sendRemoved = true;
10108                    } else {
10109                        sendAdded = true;
10110                    }
10111                }
10112            }
10113            if (sendAdded) {
10114                sendPackageAddedForUser(packageName, pkgSetting, userId);
10115                return true;
10116            }
10117            if (sendRemoved) {
10118                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10119                        "hiding pkg");
10120                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10121                return true;
10122            }
10123        } finally {
10124            Binder.restoreCallingIdentity(callingId);
10125        }
10126        return false;
10127    }
10128
10129    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10130            int userId) {
10131        final PackageRemovedInfo info = new PackageRemovedInfo();
10132        info.removedPackage = packageName;
10133        info.removedUsers = new int[] {userId};
10134        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10135        info.sendBroadcast(false, false, false);
10136    }
10137
10138    /**
10139     * Returns true if application is not found or there was an error. Otherwise it returns
10140     * the hidden state of the package for the given user.
10141     */
10142    @Override
10143    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10144        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10145        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10146                false, "getApplicationHidden for user " + userId);
10147        PackageSetting pkgSetting;
10148        long callingId = Binder.clearCallingIdentity();
10149        try {
10150            // writer
10151            synchronized (mPackages) {
10152                pkgSetting = mSettings.mPackages.get(packageName);
10153                if (pkgSetting == null) {
10154                    return true;
10155                }
10156                return pkgSetting.getHidden(userId);
10157            }
10158        } finally {
10159            Binder.restoreCallingIdentity(callingId);
10160        }
10161    }
10162
10163    /**
10164     * @hide
10165     */
10166    @Override
10167    public int installExistingPackageAsUser(String packageName, int userId) {
10168        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10169                null);
10170        PackageSetting pkgSetting;
10171        final int uid = Binder.getCallingUid();
10172        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10173                + userId);
10174        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10175            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10176        }
10177
10178        long callingId = Binder.clearCallingIdentity();
10179        try {
10180            boolean sendAdded = false;
10181
10182            // writer
10183            synchronized (mPackages) {
10184                pkgSetting = mSettings.mPackages.get(packageName);
10185                if (pkgSetting == null) {
10186                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10187                }
10188                if (!pkgSetting.getInstalled(userId)) {
10189                    pkgSetting.setInstalled(true, userId);
10190                    pkgSetting.setHidden(false, userId);
10191                    mSettings.writePackageRestrictionsLPr(userId);
10192                    sendAdded = true;
10193                }
10194            }
10195
10196            if (sendAdded) {
10197                sendPackageAddedForUser(packageName, pkgSetting, userId);
10198            }
10199        } finally {
10200            Binder.restoreCallingIdentity(callingId);
10201        }
10202
10203        return PackageManager.INSTALL_SUCCEEDED;
10204    }
10205
10206    boolean isUserRestricted(int userId, String restrictionKey) {
10207        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10208        if (restrictions.getBoolean(restrictionKey, false)) {
10209            Log.w(TAG, "User is restricted: " + restrictionKey);
10210            return true;
10211        }
10212        return false;
10213    }
10214
10215    @Override
10216    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10218        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10219                "setPackageSuspended for user " + userId);
10220
10221        long callingId = Binder.clearCallingIdentity();
10222        try {
10223            synchronized (mPackages) {
10224                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10225                if (pkgSetting != null) {
10226                    if (pkgSetting.getSuspended(userId) != suspended) {
10227                        pkgSetting.setSuspended(suspended, userId);
10228                        mSettings.writePackageRestrictionsLPr(userId);
10229                    }
10230
10231                    // TODO:
10232                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10233                    // * remove app from recents (kill app it if it is running)
10234                    // * erase existing notifications for this app
10235                    return true;
10236                }
10237
10238                return false;
10239            }
10240        } finally {
10241            Binder.restoreCallingIdentity(callingId);
10242        }
10243    }
10244
10245    @Override
10246    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10247        mContext.enforceCallingOrSelfPermission(
10248                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10249                "Only package verification agents can verify applications");
10250
10251        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10252        final PackageVerificationResponse response = new PackageVerificationResponse(
10253                verificationCode, Binder.getCallingUid());
10254        msg.arg1 = id;
10255        msg.obj = response;
10256        mHandler.sendMessage(msg);
10257    }
10258
10259    @Override
10260    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10261            long millisecondsToDelay) {
10262        mContext.enforceCallingOrSelfPermission(
10263                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10264                "Only package verification agents can extend verification timeouts");
10265
10266        final PackageVerificationState state = mPendingVerification.get(id);
10267        final PackageVerificationResponse response = new PackageVerificationResponse(
10268                verificationCodeAtTimeout, Binder.getCallingUid());
10269
10270        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10271            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10272        }
10273        if (millisecondsToDelay < 0) {
10274            millisecondsToDelay = 0;
10275        }
10276        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10277                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10278            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10279        }
10280
10281        if ((state != null) && !state.timeoutExtended()) {
10282            state.extendTimeout();
10283
10284            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10285            msg.arg1 = id;
10286            msg.obj = response;
10287            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10288        }
10289    }
10290
10291    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10292            int verificationCode, UserHandle user) {
10293        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10294        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10295        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10296        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10297        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10298
10299        mContext.sendBroadcastAsUser(intent, user,
10300                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10301    }
10302
10303    private ComponentName matchComponentForVerifier(String packageName,
10304            List<ResolveInfo> receivers) {
10305        ActivityInfo targetReceiver = null;
10306
10307        final int NR = receivers.size();
10308        for (int i = 0; i < NR; i++) {
10309            final ResolveInfo info = receivers.get(i);
10310            if (info.activityInfo == null) {
10311                continue;
10312            }
10313
10314            if (packageName.equals(info.activityInfo.packageName)) {
10315                targetReceiver = info.activityInfo;
10316                break;
10317            }
10318        }
10319
10320        if (targetReceiver == null) {
10321            return null;
10322        }
10323
10324        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10325    }
10326
10327    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10328            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10329        if (pkgInfo.verifiers.length == 0) {
10330            return null;
10331        }
10332
10333        final int N = pkgInfo.verifiers.length;
10334        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10335        for (int i = 0; i < N; i++) {
10336            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10337
10338            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10339                    receivers);
10340            if (comp == null) {
10341                continue;
10342            }
10343
10344            final int verifierUid = getUidForVerifier(verifierInfo);
10345            if (verifierUid == -1) {
10346                continue;
10347            }
10348
10349            if (DEBUG_VERIFY) {
10350                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10351                        + " with the correct signature");
10352            }
10353            sufficientVerifiers.add(comp);
10354            verificationState.addSufficientVerifier(verifierUid);
10355        }
10356
10357        return sufficientVerifiers;
10358    }
10359
10360    private int getUidForVerifier(VerifierInfo verifierInfo) {
10361        synchronized (mPackages) {
10362            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10363            if (pkg == null) {
10364                return -1;
10365            } else if (pkg.mSignatures.length != 1) {
10366                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10367                        + " has more than one signature; ignoring");
10368                return -1;
10369            }
10370
10371            /*
10372             * If the public key of the package's signature does not match
10373             * our expected public key, then this is a different package and
10374             * we should skip.
10375             */
10376
10377            final byte[] expectedPublicKey;
10378            try {
10379                final Signature verifierSig = pkg.mSignatures[0];
10380                final PublicKey publicKey = verifierSig.getPublicKey();
10381                expectedPublicKey = publicKey.getEncoded();
10382            } catch (CertificateException e) {
10383                return -1;
10384            }
10385
10386            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10387
10388            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10389                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10390                        + " does not have the expected public key; ignoring");
10391                return -1;
10392            }
10393
10394            return pkg.applicationInfo.uid;
10395        }
10396    }
10397
10398    @Override
10399    public void finishPackageInstall(int token) {
10400        enforceSystemOrRoot("Only the system is allowed to finish installs");
10401
10402        if (DEBUG_INSTALL) {
10403            Slog.v(TAG, "BM finishing package install for " + token);
10404        }
10405        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10406
10407        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10408        mHandler.sendMessage(msg);
10409    }
10410
10411    /**
10412     * Get the verification agent timeout.
10413     *
10414     * @return verification timeout in milliseconds
10415     */
10416    private long getVerificationTimeout() {
10417        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10418                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10419                DEFAULT_VERIFICATION_TIMEOUT);
10420    }
10421
10422    /**
10423     * Get the default verification agent response code.
10424     *
10425     * @return default verification response code
10426     */
10427    private int getDefaultVerificationResponse() {
10428        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10429                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10430                DEFAULT_VERIFICATION_RESPONSE);
10431    }
10432
10433    /**
10434     * Check whether or not package verification has been enabled.
10435     *
10436     * @return true if verification should be performed
10437     */
10438    private boolean isVerificationEnabled(int userId, int installFlags) {
10439        if (!DEFAULT_VERIFY_ENABLE) {
10440            return false;
10441        }
10442        // Ephemeral apps don't get the full verification treatment
10443        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10444            if (DEBUG_EPHEMERAL) {
10445                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10446            }
10447            return false;
10448        }
10449
10450        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10451
10452        // Check if installing from ADB
10453        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10454            // Do not run verification in a test harness environment
10455            if (ActivityManager.isRunningInTestHarness()) {
10456                return false;
10457            }
10458            if (ensureVerifyAppsEnabled) {
10459                return true;
10460            }
10461            // Check if the developer does not want package verification for ADB installs
10462            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10463                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10464                return false;
10465            }
10466        }
10467
10468        if (ensureVerifyAppsEnabled) {
10469            return true;
10470        }
10471
10472        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10473                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10474    }
10475
10476    @Override
10477    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10478            throws RemoteException {
10479        mContext.enforceCallingOrSelfPermission(
10480                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10481                "Only intentfilter verification agents can verify applications");
10482
10483        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10484        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10485                Binder.getCallingUid(), verificationCode, failedDomains);
10486        msg.arg1 = id;
10487        msg.obj = response;
10488        mHandler.sendMessage(msg);
10489    }
10490
10491    @Override
10492    public int getIntentVerificationStatus(String packageName, int userId) {
10493        synchronized (mPackages) {
10494            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10495        }
10496    }
10497
10498    @Override
10499    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10500        mContext.enforceCallingOrSelfPermission(
10501                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10502
10503        boolean result = false;
10504        synchronized (mPackages) {
10505            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10506        }
10507        if (result) {
10508            scheduleWritePackageRestrictionsLocked(userId);
10509        }
10510        return result;
10511    }
10512
10513    @Override
10514    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10515        synchronized (mPackages) {
10516            return mSettings.getIntentFilterVerificationsLPr(packageName);
10517        }
10518    }
10519
10520    @Override
10521    public List<IntentFilter> getAllIntentFilters(String packageName) {
10522        if (TextUtils.isEmpty(packageName)) {
10523            return Collections.<IntentFilter>emptyList();
10524        }
10525        synchronized (mPackages) {
10526            PackageParser.Package pkg = mPackages.get(packageName);
10527            if (pkg == null || pkg.activities == null) {
10528                return Collections.<IntentFilter>emptyList();
10529            }
10530            final int count = pkg.activities.size();
10531            ArrayList<IntentFilter> result = new ArrayList<>();
10532            for (int n=0; n<count; n++) {
10533                PackageParser.Activity activity = pkg.activities.get(n);
10534                if (activity.intents != null && activity.intents.size() > 0) {
10535                    result.addAll(activity.intents);
10536                }
10537            }
10538            return result;
10539        }
10540    }
10541
10542    @Override
10543    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10544        mContext.enforceCallingOrSelfPermission(
10545                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10546
10547        synchronized (mPackages) {
10548            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10549            if (packageName != null) {
10550                result |= updateIntentVerificationStatus(packageName,
10551                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10552                        userId);
10553                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10554                        packageName, userId);
10555            }
10556            return result;
10557        }
10558    }
10559
10560    @Override
10561    public String getDefaultBrowserPackageName(int userId) {
10562        synchronized (mPackages) {
10563            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10564        }
10565    }
10566
10567    /**
10568     * Get the "allow unknown sources" setting.
10569     *
10570     * @return the current "allow unknown sources" setting
10571     */
10572    private int getUnknownSourcesSettings() {
10573        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10574                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10575                -1);
10576    }
10577
10578    @Override
10579    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10580        final int uid = Binder.getCallingUid();
10581        // writer
10582        synchronized (mPackages) {
10583            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10584            if (targetPackageSetting == null) {
10585                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10586            }
10587
10588            PackageSetting installerPackageSetting;
10589            if (installerPackageName != null) {
10590                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10591                if (installerPackageSetting == null) {
10592                    throw new IllegalArgumentException("Unknown installer package: "
10593                            + installerPackageName);
10594                }
10595            } else {
10596                installerPackageSetting = null;
10597            }
10598
10599            Signature[] callerSignature;
10600            Object obj = mSettings.getUserIdLPr(uid);
10601            if (obj != null) {
10602                if (obj instanceof SharedUserSetting) {
10603                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10604                } else if (obj instanceof PackageSetting) {
10605                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10606                } else {
10607                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10608                }
10609            } else {
10610                throw new SecurityException("Unknown calling UID: " + uid);
10611            }
10612
10613            // Verify: can't set installerPackageName to a package that is
10614            // not signed with the same cert as the caller.
10615            if (installerPackageSetting != null) {
10616                if (compareSignatures(callerSignature,
10617                        installerPackageSetting.signatures.mSignatures)
10618                        != PackageManager.SIGNATURE_MATCH) {
10619                    throw new SecurityException(
10620                            "Caller does not have same cert as new installer package "
10621                            + installerPackageName);
10622                }
10623            }
10624
10625            // Verify: if target already has an installer package, it must
10626            // be signed with the same cert as the caller.
10627            if (targetPackageSetting.installerPackageName != null) {
10628                PackageSetting setting = mSettings.mPackages.get(
10629                        targetPackageSetting.installerPackageName);
10630                // If the currently set package isn't valid, then it's always
10631                // okay to change it.
10632                if (setting != null) {
10633                    if (compareSignatures(callerSignature,
10634                            setting.signatures.mSignatures)
10635                            != PackageManager.SIGNATURE_MATCH) {
10636                        throw new SecurityException(
10637                                "Caller does not have same cert as old installer package "
10638                                + targetPackageSetting.installerPackageName);
10639                    }
10640                }
10641            }
10642
10643            // Okay!
10644            targetPackageSetting.installerPackageName = installerPackageName;
10645            scheduleWriteSettingsLocked();
10646        }
10647    }
10648
10649    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10650        // Queue up an async operation since the package installation may take a little while.
10651        mHandler.post(new Runnable() {
10652            public void run() {
10653                mHandler.removeCallbacks(this);
10654                 // Result object to be returned
10655                PackageInstalledInfo res = new PackageInstalledInfo();
10656                res.returnCode = currentStatus;
10657                res.uid = -1;
10658                res.pkg = null;
10659                res.removedInfo = new PackageRemovedInfo();
10660                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10661                    args.doPreInstall(res.returnCode);
10662                    synchronized (mInstallLock) {
10663                        installPackageTracedLI(args, res);
10664                    }
10665                    args.doPostInstall(res.returnCode, res.uid);
10666                }
10667
10668                // A restore should be performed at this point if (a) the install
10669                // succeeded, (b) the operation is not an update, and (c) the new
10670                // package has not opted out of backup participation.
10671                final boolean update = res.removedInfo.removedPackage != null;
10672                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10673                boolean doRestore = !update
10674                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10675
10676                // Set up the post-install work request bookkeeping.  This will be used
10677                // and cleaned up by the post-install event handling regardless of whether
10678                // there's a restore pass performed.  Token values are >= 1.
10679                int token;
10680                if (mNextInstallToken < 0) mNextInstallToken = 1;
10681                token = mNextInstallToken++;
10682
10683                PostInstallData data = new PostInstallData(args, res);
10684                mRunningInstalls.put(token, data);
10685                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10686
10687                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10688                    // Pass responsibility to the Backup Manager.  It will perform a
10689                    // restore if appropriate, then pass responsibility back to the
10690                    // Package Manager to run the post-install observer callbacks
10691                    // and broadcasts.
10692                    IBackupManager bm = IBackupManager.Stub.asInterface(
10693                            ServiceManager.getService(Context.BACKUP_SERVICE));
10694                    if (bm != null) {
10695                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10696                                + " to BM for possible restore");
10697                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10698                        try {
10699                            // TODO: http://b/22388012
10700                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10701                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10702                            } else {
10703                                doRestore = false;
10704                            }
10705                        } catch (RemoteException e) {
10706                            // can't happen; the backup manager is local
10707                        } catch (Exception e) {
10708                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10709                            doRestore = false;
10710                        }
10711                    } else {
10712                        Slog.e(TAG, "Backup Manager not found!");
10713                        doRestore = false;
10714                    }
10715                }
10716
10717                if (!doRestore) {
10718                    // No restore possible, or the Backup Manager was mysteriously not
10719                    // available -- just fire the post-install work request directly.
10720                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10721
10722                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10723
10724                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10725                    mHandler.sendMessage(msg);
10726                }
10727            }
10728        });
10729    }
10730
10731    private abstract class HandlerParams {
10732        private static final int MAX_RETRIES = 4;
10733
10734        /**
10735         * Number of times startCopy() has been attempted and had a non-fatal
10736         * error.
10737         */
10738        private int mRetries = 0;
10739
10740        /** User handle for the user requesting the information or installation. */
10741        private final UserHandle mUser;
10742        String traceMethod;
10743        int traceCookie;
10744
10745        HandlerParams(UserHandle user) {
10746            mUser = user;
10747        }
10748
10749        UserHandle getUser() {
10750            return mUser;
10751        }
10752
10753        HandlerParams setTraceMethod(String traceMethod) {
10754            this.traceMethod = traceMethod;
10755            return this;
10756        }
10757
10758        HandlerParams setTraceCookie(int traceCookie) {
10759            this.traceCookie = traceCookie;
10760            return this;
10761        }
10762
10763        final boolean startCopy() {
10764            boolean res;
10765            try {
10766                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10767
10768                if (++mRetries > MAX_RETRIES) {
10769                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10770                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10771                    handleServiceError();
10772                    return false;
10773                } else {
10774                    handleStartCopy();
10775                    res = true;
10776                }
10777            } catch (RemoteException e) {
10778                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10779                mHandler.sendEmptyMessage(MCS_RECONNECT);
10780                res = false;
10781            }
10782            handleReturnCode();
10783            return res;
10784        }
10785
10786        final void serviceError() {
10787            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10788            handleServiceError();
10789            handleReturnCode();
10790        }
10791
10792        abstract void handleStartCopy() throws RemoteException;
10793        abstract void handleServiceError();
10794        abstract void handleReturnCode();
10795    }
10796
10797    class MeasureParams extends HandlerParams {
10798        private final PackageStats mStats;
10799        private boolean mSuccess;
10800
10801        private final IPackageStatsObserver mObserver;
10802
10803        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10804            super(new UserHandle(stats.userHandle));
10805            mObserver = observer;
10806            mStats = stats;
10807        }
10808
10809        @Override
10810        public String toString() {
10811            return "MeasureParams{"
10812                + Integer.toHexString(System.identityHashCode(this))
10813                + " " + mStats.packageName + "}";
10814        }
10815
10816        @Override
10817        void handleStartCopy() throws RemoteException {
10818            synchronized (mInstallLock) {
10819                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10820            }
10821
10822            if (mSuccess) {
10823                final boolean mounted;
10824                if (Environment.isExternalStorageEmulated()) {
10825                    mounted = true;
10826                } else {
10827                    final String status = Environment.getExternalStorageState();
10828                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10829                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10830                }
10831
10832                if (mounted) {
10833                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10834
10835                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10836                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10837
10838                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10839                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10840
10841                    // Always subtract cache size, since it's a subdirectory
10842                    mStats.externalDataSize -= mStats.externalCacheSize;
10843
10844                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10845                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10846
10847                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10848                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10849                }
10850            }
10851        }
10852
10853        @Override
10854        void handleReturnCode() {
10855            if (mObserver != null) {
10856                try {
10857                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10858                } catch (RemoteException e) {
10859                    Slog.i(TAG, "Observer no longer exists.");
10860                }
10861            }
10862        }
10863
10864        @Override
10865        void handleServiceError() {
10866            Slog.e(TAG, "Could not measure application " + mStats.packageName
10867                            + " external storage");
10868        }
10869    }
10870
10871    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10872            throws RemoteException {
10873        long result = 0;
10874        for (File path : paths) {
10875            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10876        }
10877        return result;
10878    }
10879
10880    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10881        for (File path : paths) {
10882            try {
10883                mcs.clearDirectory(path.getAbsolutePath());
10884            } catch (RemoteException e) {
10885            }
10886        }
10887    }
10888
10889    static class OriginInfo {
10890        /**
10891         * Location where install is coming from, before it has been
10892         * copied/renamed into place. This could be a single monolithic APK
10893         * file, or a cluster directory. This location may be untrusted.
10894         */
10895        final File file;
10896        final String cid;
10897
10898        /**
10899         * Flag indicating that {@link #file} or {@link #cid} has already been
10900         * staged, meaning downstream users don't need to defensively copy the
10901         * contents.
10902         */
10903        final boolean staged;
10904
10905        /**
10906         * Flag indicating that {@link #file} or {@link #cid} is an already
10907         * installed app that is being moved.
10908         */
10909        final boolean existing;
10910
10911        final String resolvedPath;
10912        final File resolvedFile;
10913
10914        static OriginInfo fromNothing() {
10915            return new OriginInfo(null, null, false, false);
10916        }
10917
10918        static OriginInfo fromUntrustedFile(File file) {
10919            return new OriginInfo(file, null, false, false);
10920        }
10921
10922        static OriginInfo fromExistingFile(File file) {
10923            return new OriginInfo(file, null, false, true);
10924        }
10925
10926        static OriginInfo fromStagedFile(File file) {
10927            return new OriginInfo(file, null, true, false);
10928        }
10929
10930        static OriginInfo fromStagedContainer(String cid) {
10931            return new OriginInfo(null, cid, true, false);
10932        }
10933
10934        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10935            this.file = file;
10936            this.cid = cid;
10937            this.staged = staged;
10938            this.existing = existing;
10939
10940            if (cid != null) {
10941                resolvedPath = PackageHelper.getSdDir(cid);
10942                resolvedFile = new File(resolvedPath);
10943            } else if (file != null) {
10944                resolvedPath = file.getAbsolutePath();
10945                resolvedFile = file;
10946            } else {
10947                resolvedPath = null;
10948                resolvedFile = null;
10949            }
10950        }
10951    }
10952
10953    static class MoveInfo {
10954        final int moveId;
10955        final String fromUuid;
10956        final String toUuid;
10957        final String packageName;
10958        final String dataAppName;
10959        final int appId;
10960        final String seinfo;
10961
10962        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10963                String dataAppName, int appId, String seinfo) {
10964            this.moveId = moveId;
10965            this.fromUuid = fromUuid;
10966            this.toUuid = toUuid;
10967            this.packageName = packageName;
10968            this.dataAppName = dataAppName;
10969            this.appId = appId;
10970            this.seinfo = seinfo;
10971        }
10972    }
10973
10974    class InstallParams extends HandlerParams {
10975        final OriginInfo origin;
10976        final MoveInfo move;
10977        final IPackageInstallObserver2 observer;
10978        int installFlags;
10979        final String installerPackageName;
10980        final String volumeUuid;
10981        final VerificationParams verificationParams;
10982        private InstallArgs mArgs;
10983        private int mRet;
10984        final String packageAbiOverride;
10985        final String[] grantedRuntimePermissions;
10986
10987        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10988                int installFlags, String installerPackageName, String volumeUuid,
10989                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10990                String[] grantedPermissions) {
10991            super(user);
10992            this.origin = origin;
10993            this.move = move;
10994            this.observer = observer;
10995            this.installFlags = installFlags;
10996            this.installerPackageName = installerPackageName;
10997            this.volumeUuid = volumeUuid;
10998            this.verificationParams = verificationParams;
10999            this.packageAbiOverride = packageAbiOverride;
11000            this.grantedRuntimePermissions = grantedPermissions;
11001        }
11002
11003        @Override
11004        public String toString() {
11005            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11006                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11007        }
11008
11009        private int installLocationPolicy(PackageInfoLite pkgLite) {
11010            String packageName = pkgLite.packageName;
11011            int installLocation = pkgLite.installLocation;
11012            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11013            // reader
11014            synchronized (mPackages) {
11015                PackageParser.Package pkg = mPackages.get(packageName);
11016                if (pkg != null) {
11017                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11018                        // Check for downgrading.
11019                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11020                            try {
11021                                checkDowngrade(pkg, pkgLite);
11022                            } catch (PackageManagerException e) {
11023                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11024                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11025                            }
11026                        }
11027                        // Check for updated system application.
11028                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11029                            if (onSd) {
11030                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11031                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11032                            }
11033                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11034                        } else {
11035                            if (onSd) {
11036                                // Install flag overrides everything.
11037                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11038                            }
11039                            // If current upgrade specifies particular preference
11040                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11041                                // Application explicitly specified internal.
11042                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11043                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11044                                // App explictly prefers external. Let policy decide
11045                            } else {
11046                                // Prefer previous location
11047                                if (isExternal(pkg)) {
11048                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11049                                }
11050                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11051                            }
11052                        }
11053                    } else {
11054                        // Invalid install. Return error code
11055                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11056                    }
11057                }
11058            }
11059            // All the special cases have been taken care of.
11060            // Return result based on recommended install location.
11061            if (onSd) {
11062                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11063            }
11064            return pkgLite.recommendedInstallLocation;
11065        }
11066
11067        /*
11068         * Invoke remote method to get package information and install
11069         * location values. Override install location based on default
11070         * policy if needed and then create install arguments based
11071         * on the install location.
11072         */
11073        public void handleStartCopy() throws RemoteException {
11074            int ret = PackageManager.INSTALL_SUCCEEDED;
11075
11076            // If we're already staged, we've firmly committed to an install location
11077            if (origin.staged) {
11078                if (origin.file != null) {
11079                    installFlags |= PackageManager.INSTALL_INTERNAL;
11080                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11081                } else if (origin.cid != null) {
11082                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11083                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11084                } else {
11085                    throw new IllegalStateException("Invalid stage location");
11086                }
11087            }
11088
11089            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11090            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11091            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11092            PackageInfoLite pkgLite = null;
11093
11094            if (onInt && onSd) {
11095                // Check if both bits are set.
11096                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11097                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11098            } else if (onSd && ephemeral) {
11099                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11100                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11101            } else {
11102                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11103                        packageAbiOverride);
11104
11105                if (DEBUG_EPHEMERAL && ephemeral) {
11106                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11107                }
11108
11109                /*
11110                 * If we have too little free space, try to free cache
11111                 * before giving up.
11112                 */
11113                if (!origin.staged && pkgLite.recommendedInstallLocation
11114                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11115                    // TODO: focus freeing disk space on the target device
11116                    final StorageManager storage = StorageManager.from(mContext);
11117                    final long lowThreshold = storage.getStorageLowBytes(
11118                            Environment.getDataDirectory());
11119
11120                    final long sizeBytes = mContainerService.calculateInstalledSize(
11121                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11122
11123                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11124                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11125                                installFlags, packageAbiOverride);
11126                    }
11127
11128                    /*
11129                     * The cache free must have deleted the file we
11130                     * downloaded to install.
11131                     *
11132                     * TODO: fix the "freeCache" call to not delete
11133                     *       the file we care about.
11134                     */
11135                    if (pkgLite.recommendedInstallLocation
11136                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11137                        pkgLite.recommendedInstallLocation
11138                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11139                    }
11140                }
11141            }
11142
11143            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11144                int loc = pkgLite.recommendedInstallLocation;
11145                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11146                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11147                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11148                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11149                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11150                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11151                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11152                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11153                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11154                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11155                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11156                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11157                } else {
11158                    // Override with defaults if needed.
11159                    loc = installLocationPolicy(pkgLite);
11160                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11161                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11162                    } else if (!onSd && !onInt) {
11163                        // Override install location with flags
11164                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11165                            // Set the flag to install on external media.
11166                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11167                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11168                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11169                            if (DEBUG_EPHEMERAL) {
11170                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11171                            }
11172                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11173                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11174                                    |PackageManager.INSTALL_INTERNAL);
11175                        } else {
11176                            // Make sure the flag for installing on external
11177                            // media is unset
11178                            installFlags |= PackageManager.INSTALL_INTERNAL;
11179                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11180                        }
11181                    }
11182                }
11183            }
11184
11185            final InstallArgs args = createInstallArgs(this);
11186            mArgs = args;
11187
11188            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11189                // TODO: http://b/22976637
11190                // Apps installed for "all" users use the device owner to verify the app
11191                UserHandle verifierUser = getUser();
11192                if (verifierUser == UserHandle.ALL) {
11193                    verifierUser = UserHandle.SYSTEM;
11194                }
11195
11196                /*
11197                 * Determine if we have any installed package verifiers. If we
11198                 * do, then we'll defer to them to verify the packages.
11199                 */
11200                final int requiredUid = mRequiredVerifierPackage == null ? -1
11201                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11202                if (!origin.existing && requiredUid != -1
11203                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11204                    final Intent verification = new Intent(
11205                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11206                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11207                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11208                            PACKAGE_MIME_TYPE);
11209                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11210
11211                    // Query all live verifiers based on current user state
11212                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11213                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11214
11215                    if (DEBUG_VERIFY) {
11216                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11217                                + verification.toString() + " with " + pkgLite.verifiers.length
11218                                + " optional verifiers");
11219                    }
11220
11221                    final int verificationId = mPendingVerificationToken++;
11222
11223                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11224
11225                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11226                            installerPackageName);
11227
11228                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11229                            installFlags);
11230
11231                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11232                            pkgLite.packageName);
11233
11234                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11235                            pkgLite.versionCode);
11236
11237                    if (verificationParams != null) {
11238                        if (verificationParams.getVerificationURI() != null) {
11239                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11240                                 verificationParams.getVerificationURI());
11241                        }
11242                        if (verificationParams.getOriginatingURI() != null) {
11243                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11244                                  verificationParams.getOriginatingURI());
11245                        }
11246                        if (verificationParams.getReferrer() != null) {
11247                            verification.putExtra(Intent.EXTRA_REFERRER,
11248                                  verificationParams.getReferrer());
11249                        }
11250                        if (verificationParams.getOriginatingUid() >= 0) {
11251                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11252                                  verificationParams.getOriginatingUid());
11253                        }
11254                        if (verificationParams.getInstallerUid() >= 0) {
11255                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11256                                  verificationParams.getInstallerUid());
11257                        }
11258                    }
11259
11260                    final PackageVerificationState verificationState = new PackageVerificationState(
11261                            requiredUid, args);
11262
11263                    mPendingVerification.append(verificationId, verificationState);
11264
11265                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11266                            receivers, verificationState);
11267
11268                    /*
11269                     * If any sufficient verifiers were listed in the package
11270                     * manifest, attempt to ask them.
11271                     */
11272                    if (sufficientVerifiers != null) {
11273                        final int N = sufficientVerifiers.size();
11274                        if (N == 0) {
11275                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11276                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11277                        } else {
11278                            for (int i = 0; i < N; i++) {
11279                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11280
11281                                final Intent sufficientIntent = new Intent(verification);
11282                                sufficientIntent.setComponent(verifierComponent);
11283                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11284                            }
11285                        }
11286                    }
11287
11288                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11289                            mRequiredVerifierPackage, receivers);
11290                    if (ret == PackageManager.INSTALL_SUCCEEDED
11291                            && mRequiredVerifierPackage != null) {
11292                        Trace.asyncTraceBegin(
11293                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11294                        /*
11295                         * Send the intent to the required verification agent,
11296                         * but only start the verification timeout after the
11297                         * target BroadcastReceivers have run.
11298                         */
11299                        verification.setComponent(requiredVerifierComponent);
11300                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11301                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11302                                new BroadcastReceiver() {
11303                                    @Override
11304                                    public void onReceive(Context context, Intent intent) {
11305                                        final Message msg = mHandler
11306                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11307                                        msg.arg1 = verificationId;
11308                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11309                                    }
11310                                }, null, 0, null, null);
11311
11312                        /*
11313                         * We don't want the copy to proceed until verification
11314                         * succeeds, so null out this field.
11315                         */
11316                        mArgs = null;
11317                    }
11318                } else {
11319                    /*
11320                     * No package verification is enabled, so immediately start
11321                     * the remote call to initiate copy using temporary file.
11322                     */
11323                    ret = args.copyApk(mContainerService, true);
11324                }
11325            }
11326
11327            mRet = ret;
11328        }
11329
11330        @Override
11331        void handleReturnCode() {
11332            // If mArgs is null, then MCS couldn't be reached. When it
11333            // reconnects, it will try again to install. At that point, this
11334            // will succeed.
11335            if (mArgs != null) {
11336                processPendingInstall(mArgs, mRet);
11337            }
11338        }
11339
11340        @Override
11341        void handleServiceError() {
11342            mArgs = createInstallArgs(this);
11343            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11344        }
11345
11346        public boolean isForwardLocked() {
11347            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11348        }
11349    }
11350
11351    /**
11352     * Used during creation of InstallArgs
11353     *
11354     * @param installFlags package installation flags
11355     * @return true if should be installed on external storage
11356     */
11357    private static boolean installOnExternalAsec(int installFlags) {
11358        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11359            return false;
11360        }
11361        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11362            return true;
11363        }
11364        return false;
11365    }
11366
11367    /**
11368     * Used during creation of InstallArgs
11369     *
11370     * @param installFlags package installation flags
11371     * @return true if should be installed as forward locked
11372     */
11373    private static boolean installForwardLocked(int installFlags) {
11374        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11375    }
11376
11377    private InstallArgs createInstallArgs(InstallParams params) {
11378        if (params.move != null) {
11379            return new MoveInstallArgs(params);
11380        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11381            return new AsecInstallArgs(params);
11382        } else {
11383            return new FileInstallArgs(params);
11384        }
11385    }
11386
11387    /**
11388     * Create args that describe an existing installed package. Typically used
11389     * when cleaning up old installs, or used as a move source.
11390     */
11391    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11392            String resourcePath, String[] instructionSets) {
11393        final boolean isInAsec;
11394        if (installOnExternalAsec(installFlags)) {
11395            /* Apps on SD card are always in ASEC containers. */
11396            isInAsec = true;
11397        } else if (installForwardLocked(installFlags)
11398                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11399            /*
11400             * Forward-locked apps are only in ASEC containers if they're the
11401             * new style
11402             */
11403            isInAsec = true;
11404        } else {
11405            isInAsec = false;
11406        }
11407
11408        if (isInAsec) {
11409            return new AsecInstallArgs(codePath, instructionSets,
11410                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11411        } else {
11412            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11413        }
11414    }
11415
11416    static abstract class InstallArgs {
11417        /** @see InstallParams#origin */
11418        final OriginInfo origin;
11419        /** @see InstallParams#move */
11420        final MoveInfo move;
11421
11422        final IPackageInstallObserver2 observer;
11423        // Always refers to PackageManager flags only
11424        final int installFlags;
11425        final String installerPackageName;
11426        final String volumeUuid;
11427        final UserHandle user;
11428        final String abiOverride;
11429        final String[] installGrantPermissions;
11430        /** If non-null, drop an async trace when the install completes */
11431        final String traceMethod;
11432        final int traceCookie;
11433
11434        // The list of instruction sets supported by this app. This is currently
11435        // only used during the rmdex() phase to clean up resources. We can get rid of this
11436        // if we move dex files under the common app path.
11437        /* nullable */ String[] instructionSets;
11438
11439        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11440                int installFlags, String installerPackageName, String volumeUuid,
11441                UserHandle user, String[] instructionSets,
11442                String abiOverride, String[] installGrantPermissions,
11443                String traceMethod, int traceCookie) {
11444            this.origin = origin;
11445            this.move = move;
11446            this.installFlags = installFlags;
11447            this.observer = observer;
11448            this.installerPackageName = installerPackageName;
11449            this.volumeUuid = volumeUuid;
11450            this.user = user;
11451            this.instructionSets = instructionSets;
11452            this.abiOverride = abiOverride;
11453            this.installGrantPermissions = installGrantPermissions;
11454            this.traceMethod = traceMethod;
11455            this.traceCookie = traceCookie;
11456        }
11457
11458        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11459        abstract int doPreInstall(int status);
11460
11461        /**
11462         * Rename package into final resting place. All paths on the given
11463         * scanned package should be updated to reflect the rename.
11464         */
11465        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11466        abstract int doPostInstall(int status, int uid);
11467
11468        /** @see PackageSettingBase#codePathString */
11469        abstract String getCodePath();
11470        /** @see PackageSettingBase#resourcePathString */
11471        abstract String getResourcePath();
11472
11473        // Need installer lock especially for dex file removal.
11474        abstract void cleanUpResourcesLI();
11475        abstract boolean doPostDeleteLI(boolean delete);
11476
11477        /**
11478         * Called before the source arguments are copied. This is used mostly
11479         * for MoveParams when it needs to read the source file to put it in the
11480         * destination.
11481         */
11482        int doPreCopy() {
11483            return PackageManager.INSTALL_SUCCEEDED;
11484        }
11485
11486        /**
11487         * Called after the source arguments are copied. This is used mostly for
11488         * MoveParams when it needs to read the source file to put it in the
11489         * destination.
11490         *
11491         * @return
11492         */
11493        int doPostCopy(int uid) {
11494            return PackageManager.INSTALL_SUCCEEDED;
11495        }
11496
11497        protected boolean isFwdLocked() {
11498            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11499        }
11500
11501        protected boolean isExternalAsec() {
11502            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11503        }
11504
11505        protected boolean isEphemeral() {
11506            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11507        }
11508
11509        UserHandle getUser() {
11510            return user;
11511        }
11512    }
11513
11514    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11515        if (!allCodePaths.isEmpty()) {
11516            if (instructionSets == null) {
11517                throw new IllegalStateException("instructionSet == null");
11518            }
11519            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11520            for (String codePath : allCodePaths) {
11521                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11522                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11523                    if (retCode < 0) {
11524                        Slog.w(TAG, "Couldn't remove dex file for package at location " + codePath
11525                                + ", retcode=" + retCode);
11526                        // we don't consider this to be a failure of the core package deletion
11527                    }
11528                }
11529            }
11530        }
11531    }
11532
11533    /**
11534     * Logic to handle installation of non-ASEC applications, including copying
11535     * and renaming logic.
11536     */
11537    class FileInstallArgs extends InstallArgs {
11538        private File codeFile;
11539        private File resourceFile;
11540
11541        // Example topology:
11542        // /data/app/com.example/base.apk
11543        // /data/app/com.example/split_foo.apk
11544        // /data/app/com.example/lib/arm/libfoo.so
11545        // /data/app/com.example/lib/arm64/libfoo.so
11546        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11547
11548        /** New install */
11549        FileInstallArgs(InstallParams params) {
11550            super(params.origin, params.move, params.observer, params.installFlags,
11551                    params.installerPackageName, params.volumeUuid,
11552                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11553                    params.grantedRuntimePermissions,
11554                    params.traceMethod, params.traceCookie);
11555            if (isFwdLocked()) {
11556                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11557            }
11558        }
11559
11560        /** Existing install */
11561        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11562            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11563                    null, null, null, 0);
11564            this.codeFile = (codePath != null) ? new File(codePath) : null;
11565            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11566        }
11567
11568        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11569            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11570            try {
11571                return doCopyApk(imcs, temp);
11572            } finally {
11573                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11574            }
11575        }
11576
11577        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11578            if (origin.staged) {
11579                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11580                codeFile = origin.file;
11581                resourceFile = origin.file;
11582                return PackageManager.INSTALL_SUCCEEDED;
11583            }
11584
11585            try {
11586                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11587                final File tempDir =
11588                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11589                codeFile = tempDir;
11590                resourceFile = tempDir;
11591            } catch (IOException e) {
11592                Slog.w(TAG, "Failed to create copy file: " + e);
11593                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11594            }
11595
11596            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11597                @Override
11598                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11599                    if (!FileUtils.isValidExtFilename(name)) {
11600                        throw new IllegalArgumentException("Invalid filename: " + name);
11601                    }
11602                    try {
11603                        final File file = new File(codeFile, name);
11604                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11605                                O_RDWR | O_CREAT, 0644);
11606                        Os.chmod(file.getAbsolutePath(), 0644);
11607                        return new ParcelFileDescriptor(fd);
11608                    } catch (ErrnoException e) {
11609                        throw new RemoteException("Failed to open: " + e.getMessage());
11610                    }
11611                }
11612            };
11613
11614            int ret = PackageManager.INSTALL_SUCCEEDED;
11615            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11616            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11617                Slog.e(TAG, "Failed to copy package");
11618                return ret;
11619            }
11620
11621            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11622            NativeLibraryHelper.Handle handle = null;
11623            try {
11624                handle = NativeLibraryHelper.Handle.create(codeFile);
11625                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11626                        abiOverride);
11627            } catch (IOException e) {
11628                Slog.e(TAG, "Copying native libraries failed", e);
11629                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11630            } finally {
11631                IoUtils.closeQuietly(handle);
11632            }
11633
11634            return ret;
11635        }
11636
11637        int doPreInstall(int status) {
11638            if (status != PackageManager.INSTALL_SUCCEEDED) {
11639                cleanUp();
11640            }
11641            return status;
11642        }
11643
11644        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11645            if (status != PackageManager.INSTALL_SUCCEEDED) {
11646                cleanUp();
11647                return false;
11648            }
11649
11650            final File targetDir = codeFile.getParentFile();
11651            final File beforeCodeFile = codeFile;
11652            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11653
11654            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11655            try {
11656                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11657            } catch (ErrnoException e) {
11658                Slog.w(TAG, "Failed to rename", e);
11659                return false;
11660            }
11661
11662            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11663                Slog.w(TAG, "Failed to restorecon");
11664                return false;
11665            }
11666
11667            // Reflect the rename internally
11668            codeFile = afterCodeFile;
11669            resourceFile = afterCodeFile;
11670
11671            // Reflect the rename in scanned details
11672            pkg.codePath = afterCodeFile.getAbsolutePath();
11673            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11674                    pkg.baseCodePath);
11675            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11676                    pkg.splitCodePaths);
11677
11678            // Reflect the rename in app info
11679            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11680            pkg.applicationInfo.setCodePath(pkg.codePath);
11681            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11682            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11683            pkg.applicationInfo.setResourcePath(pkg.codePath);
11684            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11685            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11686
11687            return true;
11688        }
11689
11690        int doPostInstall(int status, int uid) {
11691            if (status != PackageManager.INSTALL_SUCCEEDED) {
11692                cleanUp();
11693            }
11694            return status;
11695        }
11696
11697        @Override
11698        String getCodePath() {
11699            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11700        }
11701
11702        @Override
11703        String getResourcePath() {
11704            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11705        }
11706
11707        private boolean cleanUp() {
11708            if (codeFile == null || !codeFile.exists()) {
11709                return false;
11710            }
11711
11712            if (codeFile.isDirectory()) {
11713                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11714            } else {
11715                codeFile.delete();
11716            }
11717
11718            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11719                resourceFile.delete();
11720            }
11721
11722            return true;
11723        }
11724
11725        void cleanUpResourcesLI() {
11726            // Try enumerating all code paths before deleting
11727            List<String> allCodePaths = Collections.EMPTY_LIST;
11728            if (codeFile != null && codeFile.exists()) {
11729                try {
11730                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11731                    allCodePaths = pkg.getAllCodePaths();
11732                } catch (PackageParserException e) {
11733                    // Ignored; we tried our best
11734                }
11735            }
11736
11737            cleanUp();
11738            removeDexFiles(allCodePaths, instructionSets);
11739        }
11740
11741        boolean doPostDeleteLI(boolean delete) {
11742            // XXX err, shouldn't we respect the delete flag?
11743            cleanUpResourcesLI();
11744            return true;
11745        }
11746    }
11747
11748    private boolean isAsecExternal(String cid) {
11749        final String asecPath = PackageHelper.getSdFilesystem(cid);
11750        return !asecPath.startsWith(mAsecInternalPath);
11751    }
11752
11753    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11754            PackageManagerException {
11755        if (copyRet < 0) {
11756            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11757                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11758                throw new PackageManagerException(copyRet, message);
11759            }
11760        }
11761    }
11762
11763    /**
11764     * Extract the MountService "container ID" from the full code path of an
11765     * .apk.
11766     */
11767    static String cidFromCodePath(String fullCodePath) {
11768        int eidx = fullCodePath.lastIndexOf("/");
11769        String subStr1 = fullCodePath.substring(0, eidx);
11770        int sidx = subStr1.lastIndexOf("/");
11771        return subStr1.substring(sidx+1, eidx);
11772    }
11773
11774    /**
11775     * Logic to handle installation of ASEC applications, including copying and
11776     * renaming logic.
11777     */
11778    class AsecInstallArgs extends InstallArgs {
11779        static final String RES_FILE_NAME = "pkg.apk";
11780        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11781
11782        String cid;
11783        String packagePath;
11784        String resourcePath;
11785
11786        /** New install */
11787        AsecInstallArgs(InstallParams params) {
11788            super(params.origin, params.move, params.observer, params.installFlags,
11789                    params.installerPackageName, params.volumeUuid,
11790                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11791                    params.grantedRuntimePermissions,
11792                    params.traceMethod, params.traceCookie);
11793        }
11794
11795        /** Existing install */
11796        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11797                        boolean isExternal, boolean isForwardLocked) {
11798            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11799                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11800                    instructionSets, null, null, null, 0);
11801            // Hackily pretend we're still looking at a full code path
11802            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11803                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11804            }
11805
11806            // Extract cid from fullCodePath
11807            int eidx = fullCodePath.lastIndexOf("/");
11808            String subStr1 = fullCodePath.substring(0, eidx);
11809            int sidx = subStr1.lastIndexOf("/");
11810            cid = subStr1.substring(sidx+1, eidx);
11811            setMountPath(subStr1);
11812        }
11813
11814        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11815            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11816                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11817                    instructionSets, null, null, null, 0);
11818            this.cid = cid;
11819            setMountPath(PackageHelper.getSdDir(cid));
11820        }
11821
11822        void createCopyFile() {
11823            cid = mInstallerService.allocateExternalStageCidLegacy();
11824        }
11825
11826        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11827            if (origin.staged && origin.cid != null) {
11828                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11829                cid = origin.cid;
11830                setMountPath(PackageHelper.getSdDir(cid));
11831                return PackageManager.INSTALL_SUCCEEDED;
11832            }
11833
11834            if (temp) {
11835                createCopyFile();
11836            } else {
11837                /*
11838                 * Pre-emptively destroy the container since it's destroyed if
11839                 * copying fails due to it existing anyway.
11840                 */
11841                PackageHelper.destroySdDir(cid);
11842            }
11843
11844            final String newMountPath = imcs.copyPackageToContainer(
11845                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11846                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11847
11848            if (newMountPath != null) {
11849                setMountPath(newMountPath);
11850                return PackageManager.INSTALL_SUCCEEDED;
11851            } else {
11852                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11853            }
11854        }
11855
11856        @Override
11857        String getCodePath() {
11858            return packagePath;
11859        }
11860
11861        @Override
11862        String getResourcePath() {
11863            return resourcePath;
11864        }
11865
11866        int doPreInstall(int status) {
11867            if (status != PackageManager.INSTALL_SUCCEEDED) {
11868                // Destroy container
11869                PackageHelper.destroySdDir(cid);
11870            } else {
11871                boolean mounted = PackageHelper.isContainerMounted(cid);
11872                if (!mounted) {
11873                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11874                            Process.SYSTEM_UID);
11875                    if (newMountPath != null) {
11876                        setMountPath(newMountPath);
11877                    } else {
11878                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11879                    }
11880                }
11881            }
11882            return status;
11883        }
11884
11885        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11886            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11887            String newMountPath = null;
11888            if (PackageHelper.isContainerMounted(cid)) {
11889                // Unmount the container
11890                if (!PackageHelper.unMountSdDir(cid)) {
11891                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11892                    return false;
11893                }
11894            }
11895            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11896                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11897                        " which might be stale. Will try to clean up.");
11898                // Clean up the stale container and proceed to recreate.
11899                if (!PackageHelper.destroySdDir(newCacheId)) {
11900                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11901                    return false;
11902                }
11903                // Successfully cleaned up stale container. Try to rename again.
11904                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11905                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11906                            + " inspite of cleaning it up.");
11907                    return false;
11908                }
11909            }
11910            if (!PackageHelper.isContainerMounted(newCacheId)) {
11911                Slog.w(TAG, "Mounting container " + newCacheId);
11912                newMountPath = PackageHelper.mountSdDir(newCacheId,
11913                        getEncryptKey(), Process.SYSTEM_UID);
11914            } else {
11915                newMountPath = PackageHelper.getSdDir(newCacheId);
11916            }
11917            if (newMountPath == null) {
11918                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11919                return false;
11920            }
11921            Log.i(TAG, "Succesfully renamed " + cid +
11922                    " to " + newCacheId +
11923                    " at new path: " + newMountPath);
11924            cid = newCacheId;
11925
11926            final File beforeCodeFile = new File(packagePath);
11927            setMountPath(newMountPath);
11928            final File afterCodeFile = new File(packagePath);
11929
11930            // Reflect the rename in scanned details
11931            pkg.codePath = afterCodeFile.getAbsolutePath();
11932            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11933                    pkg.baseCodePath);
11934            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11935                    pkg.splitCodePaths);
11936
11937            // Reflect the rename in app info
11938            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11939            pkg.applicationInfo.setCodePath(pkg.codePath);
11940            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11941            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11942            pkg.applicationInfo.setResourcePath(pkg.codePath);
11943            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11944            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11945
11946            return true;
11947        }
11948
11949        private void setMountPath(String mountPath) {
11950            final File mountFile = new File(mountPath);
11951
11952            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11953            if (monolithicFile.exists()) {
11954                packagePath = monolithicFile.getAbsolutePath();
11955                if (isFwdLocked()) {
11956                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11957                } else {
11958                    resourcePath = packagePath;
11959                }
11960            } else {
11961                packagePath = mountFile.getAbsolutePath();
11962                resourcePath = packagePath;
11963            }
11964        }
11965
11966        int doPostInstall(int status, int uid) {
11967            if (status != PackageManager.INSTALL_SUCCEEDED) {
11968                cleanUp();
11969            } else {
11970                final int groupOwner;
11971                final String protectedFile;
11972                if (isFwdLocked()) {
11973                    groupOwner = UserHandle.getSharedAppGid(uid);
11974                    protectedFile = RES_FILE_NAME;
11975                } else {
11976                    groupOwner = -1;
11977                    protectedFile = null;
11978                }
11979
11980                if (uid < Process.FIRST_APPLICATION_UID
11981                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11982                    Slog.e(TAG, "Failed to finalize " + cid);
11983                    PackageHelper.destroySdDir(cid);
11984                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11985                }
11986
11987                boolean mounted = PackageHelper.isContainerMounted(cid);
11988                if (!mounted) {
11989                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11990                }
11991            }
11992            return status;
11993        }
11994
11995        private void cleanUp() {
11996            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11997
11998            // Destroy secure container
11999            PackageHelper.destroySdDir(cid);
12000        }
12001
12002        private List<String> getAllCodePaths() {
12003            final File codeFile = new File(getCodePath());
12004            if (codeFile != null && codeFile.exists()) {
12005                try {
12006                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12007                    return pkg.getAllCodePaths();
12008                } catch (PackageParserException e) {
12009                    // Ignored; we tried our best
12010                }
12011            }
12012            return Collections.EMPTY_LIST;
12013        }
12014
12015        void cleanUpResourcesLI() {
12016            // Enumerate all code paths before deleting
12017            cleanUpResourcesLI(getAllCodePaths());
12018        }
12019
12020        private void cleanUpResourcesLI(List<String> allCodePaths) {
12021            cleanUp();
12022            removeDexFiles(allCodePaths, instructionSets);
12023        }
12024
12025        String getPackageName() {
12026            return getAsecPackageName(cid);
12027        }
12028
12029        boolean doPostDeleteLI(boolean delete) {
12030            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12031            final List<String> allCodePaths = getAllCodePaths();
12032            boolean mounted = PackageHelper.isContainerMounted(cid);
12033            if (mounted) {
12034                // Unmount first
12035                if (PackageHelper.unMountSdDir(cid)) {
12036                    mounted = false;
12037                }
12038            }
12039            if (!mounted && delete) {
12040                cleanUpResourcesLI(allCodePaths);
12041            }
12042            return !mounted;
12043        }
12044
12045        @Override
12046        int doPreCopy() {
12047            if (isFwdLocked()) {
12048                if (!PackageHelper.fixSdPermissions(cid,
12049                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12050                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12051                }
12052            }
12053
12054            return PackageManager.INSTALL_SUCCEEDED;
12055        }
12056
12057        @Override
12058        int doPostCopy(int uid) {
12059            if (isFwdLocked()) {
12060                if (uid < Process.FIRST_APPLICATION_UID
12061                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12062                                RES_FILE_NAME)) {
12063                    Slog.e(TAG, "Failed to finalize " + cid);
12064                    PackageHelper.destroySdDir(cid);
12065                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12066                }
12067            }
12068
12069            return PackageManager.INSTALL_SUCCEEDED;
12070        }
12071    }
12072
12073    /**
12074     * Logic to handle movement of existing installed applications.
12075     */
12076    class MoveInstallArgs extends InstallArgs {
12077        private File codeFile;
12078        private File resourceFile;
12079
12080        /** New install */
12081        MoveInstallArgs(InstallParams params) {
12082            super(params.origin, params.move, params.observer, params.installFlags,
12083                    params.installerPackageName, params.volumeUuid,
12084                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12085                    params.grantedRuntimePermissions,
12086                    params.traceMethod, params.traceCookie);
12087        }
12088
12089        int copyApk(IMediaContainerService imcs, boolean temp) {
12090            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12091                    + move.fromUuid + " to " + move.toUuid);
12092            synchronized (mInstaller) {
12093                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12094                        move.dataAppName, move.appId, move.seinfo) != 0) {
12095                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12096                }
12097            }
12098
12099            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12100            resourceFile = codeFile;
12101            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12102
12103            return PackageManager.INSTALL_SUCCEEDED;
12104        }
12105
12106        int doPreInstall(int status) {
12107            if (status != PackageManager.INSTALL_SUCCEEDED) {
12108                cleanUp(move.toUuid);
12109            }
12110            return status;
12111        }
12112
12113        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12114            if (status != PackageManager.INSTALL_SUCCEEDED) {
12115                cleanUp(move.toUuid);
12116                return false;
12117            }
12118
12119            // Reflect the move in app info
12120            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12121            pkg.applicationInfo.setCodePath(pkg.codePath);
12122            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12123            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12124            pkg.applicationInfo.setResourcePath(pkg.codePath);
12125            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12126            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12127
12128            return true;
12129        }
12130
12131        int doPostInstall(int status, int uid) {
12132            if (status == PackageManager.INSTALL_SUCCEEDED) {
12133                cleanUp(move.fromUuid);
12134            } else {
12135                cleanUp(move.toUuid);
12136            }
12137            return status;
12138        }
12139
12140        @Override
12141        String getCodePath() {
12142            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12143        }
12144
12145        @Override
12146        String getResourcePath() {
12147            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12148        }
12149
12150        private boolean cleanUp(String volumeUuid) {
12151            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12152                    move.dataAppName);
12153            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12154            synchronized (mInstallLock) {
12155                // Clean up both app data and code
12156                removeDataDirsLI(volumeUuid, move.packageName);
12157                if (codeFile.isDirectory()) {
12158                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12159                } else {
12160                    codeFile.delete();
12161                }
12162            }
12163            return true;
12164        }
12165
12166        void cleanUpResourcesLI() {
12167            throw new UnsupportedOperationException();
12168        }
12169
12170        boolean doPostDeleteLI(boolean delete) {
12171            throw new UnsupportedOperationException();
12172        }
12173    }
12174
12175    static String getAsecPackageName(String packageCid) {
12176        int idx = packageCid.lastIndexOf("-");
12177        if (idx == -1) {
12178            return packageCid;
12179        }
12180        return packageCid.substring(0, idx);
12181    }
12182
12183    // Utility method used to create code paths based on package name and available index.
12184    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12185        String idxStr = "";
12186        int idx = 1;
12187        // Fall back to default value of idx=1 if prefix is not
12188        // part of oldCodePath
12189        if (oldCodePath != null) {
12190            String subStr = oldCodePath;
12191            // Drop the suffix right away
12192            if (suffix != null && subStr.endsWith(suffix)) {
12193                subStr = subStr.substring(0, subStr.length() - suffix.length());
12194            }
12195            // If oldCodePath already contains prefix find out the
12196            // ending index to either increment or decrement.
12197            int sidx = subStr.lastIndexOf(prefix);
12198            if (sidx != -1) {
12199                subStr = subStr.substring(sidx + prefix.length());
12200                if (subStr != null) {
12201                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12202                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12203                    }
12204                    try {
12205                        idx = Integer.parseInt(subStr);
12206                        if (idx <= 1) {
12207                            idx++;
12208                        } else {
12209                            idx--;
12210                        }
12211                    } catch(NumberFormatException e) {
12212                    }
12213                }
12214            }
12215        }
12216        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12217        return prefix + idxStr;
12218    }
12219
12220    private File getNextCodePath(File targetDir, String packageName) {
12221        int suffix = 1;
12222        File result;
12223        do {
12224            result = new File(targetDir, packageName + "-" + suffix);
12225            suffix++;
12226        } while (result.exists());
12227        return result;
12228    }
12229
12230    // Utility method that returns the relative package path with respect
12231    // to the installation directory. Like say for /data/data/com.test-1.apk
12232    // string com.test-1 is returned.
12233    static String deriveCodePathName(String codePath) {
12234        if (codePath == null) {
12235            return null;
12236        }
12237        final File codeFile = new File(codePath);
12238        final String name = codeFile.getName();
12239        if (codeFile.isDirectory()) {
12240            return name;
12241        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12242            final int lastDot = name.lastIndexOf('.');
12243            return name.substring(0, lastDot);
12244        } else {
12245            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12246            return null;
12247        }
12248    }
12249
12250    static class PackageInstalledInfo {
12251        String name;
12252        int uid;
12253        // The set of users that originally had this package installed.
12254        int[] origUsers;
12255        // The set of users that now have this package installed.
12256        int[] newUsers;
12257        PackageParser.Package pkg;
12258        int returnCode;
12259        String returnMsg;
12260        PackageRemovedInfo removedInfo;
12261
12262        public void setError(int code, String msg) {
12263            returnCode = code;
12264            returnMsg = msg;
12265            Slog.w(TAG, msg);
12266        }
12267
12268        public void setError(String msg, PackageParserException e) {
12269            returnCode = e.error;
12270            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12271            Slog.w(TAG, msg, e);
12272        }
12273
12274        public void setError(String msg, PackageManagerException e) {
12275            returnCode = e.error;
12276            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12277            Slog.w(TAG, msg, e);
12278        }
12279
12280        // In some error cases we want to convey more info back to the observer
12281        String origPackage;
12282        String origPermission;
12283    }
12284
12285    /*
12286     * Install a non-existing package.
12287     */
12288    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12289            UserHandle user, String installerPackageName, String volumeUuid,
12290            PackageInstalledInfo res) {
12291        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12292
12293        // Remember this for later, in case we need to rollback this install
12294        String pkgName = pkg.packageName;
12295
12296        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12297        // TODO: b/23350563
12298        final boolean dataDirExists = Environment
12299                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12300
12301        synchronized(mPackages) {
12302            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12303                // A package with the same name is already installed, though
12304                // it has been renamed to an older name.  The package we
12305                // are trying to install should be installed as an update to
12306                // the existing one, but that has not been requested, so bail.
12307                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12308                        + " without first uninstalling package running as "
12309                        + mSettings.mRenamedPackages.get(pkgName));
12310                return;
12311            }
12312            if (mPackages.containsKey(pkgName)) {
12313                // Don't allow installation over an existing package with the same name.
12314                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12315                        + " without first uninstalling.");
12316                return;
12317            }
12318        }
12319
12320        try {
12321            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12322                    System.currentTimeMillis(), user);
12323
12324            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12325            // delete the partially installed application. the data directory will have to be
12326            // restored if it was already existing
12327            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12328                // remove package from internal structures.  Note that we want deletePackageX to
12329                // delete the package data and cache directories that it created in
12330                // scanPackageLocked, unless those directories existed before we even tried to
12331                // install.
12332                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12333                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12334                                res.removedInfo, true);
12335            }
12336
12337        } catch (PackageManagerException e) {
12338            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12339        }
12340
12341        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12342    }
12343
12344    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12345        // Can't rotate keys during boot or if sharedUser.
12346        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12347                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12348            return false;
12349        }
12350        // app is using upgradeKeySets; make sure all are valid
12351        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12352        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12353        for (int i = 0; i < upgradeKeySets.length; i++) {
12354            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12355                Slog.wtf(TAG, "Package "
12356                         + (oldPs.name != null ? oldPs.name : "<null>")
12357                         + " contains upgrade-key-set reference to unknown key-set: "
12358                         + upgradeKeySets[i]
12359                         + " reverting to signatures check.");
12360                return false;
12361            }
12362        }
12363        return true;
12364    }
12365
12366    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12367        // Upgrade keysets are being used.  Determine if new package has a superset of the
12368        // required keys.
12369        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12370        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12371        for (int i = 0; i < upgradeKeySets.length; i++) {
12372            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12373            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12374                return true;
12375            }
12376        }
12377        return false;
12378    }
12379
12380    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12381            UserHandle user, String installerPackageName, String volumeUuid,
12382            PackageInstalledInfo res) {
12383        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12384
12385        final PackageParser.Package oldPackage;
12386        final String pkgName = pkg.packageName;
12387        final int[] allUsers;
12388        final boolean[] perUserInstalled;
12389
12390        // First find the old package info and check signatures
12391        synchronized(mPackages) {
12392            oldPackage = mPackages.get(pkgName);
12393            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12394            if (isEphemeral && !oldIsEphemeral) {
12395                // can't downgrade from full to ephemeral
12396                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12397                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12398                return;
12399            }
12400            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12401            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12402            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12403                if(!checkUpgradeKeySetLP(ps, pkg)) {
12404                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12405                            "New package not signed by keys specified by upgrade-keysets: "
12406                            + pkgName);
12407                    return;
12408                }
12409            } else {
12410                // default to original signature matching
12411                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12412                    != PackageManager.SIGNATURE_MATCH) {
12413                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12414                            "New package has a different signature: " + pkgName);
12415                    return;
12416                }
12417            }
12418
12419            // In case of rollback, remember per-user/profile install state
12420            allUsers = sUserManager.getUserIds();
12421            perUserInstalled = new boolean[allUsers.length];
12422            for (int i = 0; i < allUsers.length; i++) {
12423                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12424            }
12425        }
12426
12427        boolean sysPkg = (isSystemApp(oldPackage));
12428        if (sysPkg) {
12429            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12430                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12431        } else {
12432            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12433                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12434        }
12435    }
12436
12437    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12438            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12439            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12440            String volumeUuid, PackageInstalledInfo res) {
12441        String pkgName = deletedPackage.packageName;
12442        boolean deletedPkg = true;
12443        boolean updatedSettings = false;
12444
12445        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12446                + deletedPackage);
12447        long origUpdateTime;
12448        if (pkg.mExtras != null) {
12449            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12450        } else {
12451            origUpdateTime = 0;
12452        }
12453
12454        // First delete the existing package while retaining the data directory
12455        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12456                res.removedInfo, true)) {
12457            // If the existing package wasn't successfully deleted
12458            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12459            deletedPkg = false;
12460        } else {
12461            // Successfully deleted the old package; proceed with replace.
12462
12463            // If deleted package lived in a container, give users a chance to
12464            // relinquish resources before killing.
12465            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12466                if (DEBUG_INSTALL) {
12467                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12468                }
12469                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12470                final ArrayList<String> pkgList = new ArrayList<String>(1);
12471                pkgList.add(deletedPackage.applicationInfo.packageName);
12472                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12473            }
12474
12475            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12476            try {
12477                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12478                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12479                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12480                        perUserInstalled, res, user);
12481                updatedSettings = true;
12482            } catch (PackageManagerException e) {
12483                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12484            }
12485        }
12486
12487        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12488            // remove package from internal structures.  Note that we want deletePackageX to
12489            // delete the package data and cache directories that it created in
12490            // scanPackageLocked, unless those directories existed before we even tried to
12491            // install.
12492            if(updatedSettings) {
12493                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12494                deletePackageLI(
12495                        pkgName, null, true, allUsers, perUserInstalled,
12496                        PackageManager.DELETE_KEEP_DATA,
12497                                res.removedInfo, true);
12498            }
12499            // Since we failed to install the new package we need to restore the old
12500            // package that we deleted.
12501            if (deletedPkg) {
12502                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12503                File restoreFile = new File(deletedPackage.codePath);
12504                // Parse old package
12505                boolean oldExternal = isExternal(deletedPackage);
12506                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12507                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12508                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12509                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12510                try {
12511                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12512                            null);
12513                } catch (PackageManagerException e) {
12514                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12515                            + e.getMessage());
12516                    return;
12517                }
12518                // Restore of old package succeeded. Update permissions.
12519                // writer
12520                synchronized (mPackages) {
12521                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12522                            UPDATE_PERMISSIONS_ALL);
12523                    // can downgrade to reader
12524                    mSettings.writeLPr();
12525                }
12526                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12527            }
12528        }
12529    }
12530
12531    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12532            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12533            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12534            String volumeUuid, PackageInstalledInfo res) {
12535        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12536                + ", old=" + deletedPackage);
12537        boolean disabledSystem = false;
12538        boolean updatedSettings = false;
12539        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12540        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12541                != 0) {
12542            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12543        }
12544        String packageName = deletedPackage.packageName;
12545        if (packageName == null) {
12546            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12547                    "Attempt to delete null packageName.");
12548            return;
12549        }
12550        PackageParser.Package oldPkg;
12551        PackageSetting oldPkgSetting;
12552        // reader
12553        synchronized (mPackages) {
12554            oldPkg = mPackages.get(packageName);
12555            oldPkgSetting = mSettings.mPackages.get(packageName);
12556            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12557                    (oldPkgSetting == null)) {
12558                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12559                        "Couldn't find package " + packageName + " information");
12560                return;
12561            }
12562        }
12563
12564        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12565
12566        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12567        res.removedInfo.removedPackage = packageName;
12568        // Remove existing system package
12569        removePackageLI(oldPkgSetting, true);
12570        // writer
12571        synchronized (mPackages) {
12572            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12573            if (!disabledSystem && deletedPackage != null) {
12574                // We didn't need to disable the .apk as a current system package,
12575                // which means we are replacing another update that is already
12576                // installed.  We need to make sure to delete the older one's .apk.
12577                res.removedInfo.args = createInstallArgsForExisting(0,
12578                        deletedPackage.applicationInfo.getCodePath(),
12579                        deletedPackage.applicationInfo.getResourcePath(),
12580                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12581            } else {
12582                res.removedInfo.args = null;
12583            }
12584        }
12585
12586        // Successfully disabled the old package. Now proceed with re-installation
12587        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12588
12589        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12590        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12591
12592        PackageParser.Package newPackage = null;
12593        try {
12594            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12595            if (newPackage.mExtras != null) {
12596                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12597                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12598                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12599
12600                // is the update attempting to change shared user? that isn't going to work...
12601                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12602                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12603                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12604                            + " to " + newPkgSetting.sharedUser);
12605                    updatedSettings = true;
12606                }
12607            }
12608
12609            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12610                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12611                        perUserInstalled, res, user);
12612                updatedSettings = true;
12613            }
12614
12615        } catch (PackageManagerException e) {
12616            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12617        }
12618
12619        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12620            // Re installation failed. Restore old information
12621            // Remove new pkg information
12622            if (newPackage != null) {
12623                removeInstalledPackageLI(newPackage, true);
12624            }
12625            // Add back the old system package
12626            try {
12627                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12628            } catch (PackageManagerException e) {
12629                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12630            }
12631            // Restore the old system information in Settings
12632            synchronized (mPackages) {
12633                if (disabledSystem) {
12634                    mSettings.enableSystemPackageLPw(packageName);
12635                }
12636                if (updatedSettings) {
12637                    mSettings.setInstallerPackageName(packageName,
12638                            oldPkgSetting.installerPackageName);
12639                }
12640                mSettings.writeLPr();
12641            }
12642        }
12643    }
12644
12645    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12646        // Collect all used permissions in the UID
12647        ArraySet<String> usedPermissions = new ArraySet<>();
12648        final int packageCount = su.packages.size();
12649        for (int i = 0; i < packageCount; i++) {
12650            PackageSetting ps = su.packages.valueAt(i);
12651            if (ps.pkg == null) {
12652                continue;
12653            }
12654            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12655            for (int j = 0; j < requestedPermCount; j++) {
12656                String permission = ps.pkg.requestedPermissions.get(j);
12657                BasePermission bp = mSettings.mPermissions.get(permission);
12658                if (bp != null) {
12659                    usedPermissions.add(permission);
12660                }
12661            }
12662        }
12663
12664        PermissionsState permissionsState = su.getPermissionsState();
12665        // Prune install permissions
12666        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12667        final int installPermCount = installPermStates.size();
12668        for (int i = installPermCount - 1; i >= 0;  i--) {
12669            PermissionState permissionState = installPermStates.get(i);
12670            if (!usedPermissions.contains(permissionState.getName())) {
12671                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12672                if (bp != null) {
12673                    permissionsState.revokeInstallPermission(bp);
12674                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12675                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12676                }
12677            }
12678        }
12679
12680        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12681
12682        // Prune runtime permissions
12683        for (int userId : allUserIds) {
12684            List<PermissionState> runtimePermStates = permissionsState
12685                    .getRuntimePermissionStates(userId);
12686            final int runtimePermCount = runtimePermStates.size();
12687            for (int i = runtimePermCount - 1; i >= 0; i--) {
12688                PermissionState permissionState = runtimePermStates.get(i);
12689                if (!usedPermissions.contains(permissionState.getName())) {
12690                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12691                    if (bp != null) {
12692                        permissionsState.revokeRuntimePermission(bp, userId);
12693                        permissionsState.updatePermissionFlags(bp, userId,
12694                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12695                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12696                                runtimePermissionChangedUserIds, userId);
12697                    }
12698                }
12699            }
12700        }
12701
12702        return runtimePermissionChangedUserIds;
12703    }
12704
12705    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12706            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12707            UserHandle user) {
12708        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12709
12710        String pkgName = newPackage.packageName;
12711        synchronized (mPackages) {
12712            //write settings. the installStatus will be incomplete at this stage.
12713            //note that the new package setting would have already been
12714            //added to mPackages. It hasn't been persisted yet.
12715            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12716            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12717            mSettings.writeLPr();
12718            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12719        }
12720
12721        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12722        synchronized (mPackages) {
12723            updatePermissionsLPw(newPackage.packageName, newPackage,
12724                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12725                            ? UPDATE_PERMISSIONS_ALL : 0));
12726            // For system-bundled packages, we assume that installing an upgraded version
12727            // of the package implies that the user actually wants to run that new code,
12728            // so we enable the package.
12729            PackageSetting ps = mSettings.mPackages.get(pkgName);
12730            if (ps != null) {
12731                if (isSystemApp(newPackage)) {
12732                    // NB: implicit assumption that system package upgrades apply to all users
12733                    if (DEBUG_INSTALL) {
12734                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12735                    }
12736                    if (res.origUsers != null) {
12737                        for (int userHandle : res.origUsers) {
12738                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12739                                    userHandle, installerPackageName);
12740                        }
12741                    }
12742                    // Also convey the prior install/uninstall state
12743                    if (allUsers != null && perUserInstalled != null) {
12744                        for (int i = 0; i < allUsers.length; i++) {
12745                            if (DEBUG_INSTALL) {
12746                                Slog.d(TAG, "    user " + allUsers[i]
12747                                        + " => " + perUserInstalled[i]);
12748                            }
12749                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12750                        }
12751                        // these install state changes will be persisted in the
12752                        // upcoming call to mSettings.writeLPr().
12753                    }
12754                }
12755                // It's implied that when a user requests installation, they want the app to be
12756                // installed and enabled.
12757                int userId = user.getIdentifier();
12758                if (userId != UserHandle.USER_ALL) {
12759                    ps.setInstalled(true, userId);
12760                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12761                }
12762            }
12763            res.name = pkgName;
12764            res.uid = newPackage.applicationInfo.uid;
12765            res.pkg = newPackage;
12766            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12767            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12768            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12769            //to update install status
12770            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12771            mSettings.writeLPr();
12772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12773        }
12774
12775        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12776    }
12777
12778    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12779        try {
12780            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12781            installPackageLI(args, res);
12782        } finally {
12783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12784        }
12785    }
12786
12787    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12788        final int installFlags = args.installFlags;
12789        final String installerPackageName = args.installerPackageName;
12790        final String volumeUuid = args.volumeUuid;
12791        final File tmpPackageFile = new File(args.getCodePath());
12792        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12793        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12794                || (args.volumeUuid != null));
12795        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12796        boolean replace = false;
12797        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12798        if (args.move != null) {
12799            // moving a complete application; perfom an initial scan on the new install location
12800            scanFlags |= SCAN_INITIAL;
12801        }
12802        // Result object to be returned
12803        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12804
12805        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12806
12807        // Sanity check
12808        if (ephemeral && (forwardLocked || onExternal)) {
12809            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12810                    + " external=" + onExternal);
12811            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12812            return;
12813        }
12814
12815        // Retrieve PackageSettings and parse package
12816        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12817                | PackageParser.PARSE_ENFORCE_CODE
12818                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12819                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12820                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12821        PackageParser pp = new PackageParser();
12822        pp.setSeparateProcesses(mSeparateProcesses);
12823        pp.setDisplayMetrics(mMetrics);
12824
12825        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12826        final PackageParser.Package pkg;
12827        try {
12828            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12829        } catch (PackageParserException e) {
12830            res.setError("Failed parse during installPackageLI", e);
12831            return;
12832        } finally {
12833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12834        }
12835
12836        // Mark that we have an install time CPU ABI override.
12837        pkg.cpuAbiOverride = args.abiOverride;
12838
12839        String pkgName = res.name = pkg.packageName;
12840        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12841            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12842                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12843                return;
12844            }
12845        }
12846
12847        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12848        try {
12849            pp.collectCertificates(pkg, parseFlags);
12850        } catch (PackageParserException e) {
12851            res.setError("Failed collect during installPackageLI", e);
12852            return;
12853        } finally {
12854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12855        }
12856
12857        // Get rid of all references to package scan path via parser.
12858        pp = null;
12859        String oldCodePath = null;
12860        boolean systemApp = false;
12861        synchronized (mPackages) {
12862            // Check if installing already existing package
12863            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12864                String oldName = mSettings.mRenamedPackages.get(pkgName);
12865                if (pkg.mOriginalPackages != null
12866                        && pkg.mOriginalPackages.contains(oldName)
12867                        && mPackages.containsKey(oldName)) {
12868                    // This package is derived from an original package,
12869                    // and this device has been updating from that original
12870                    // name.  We must continue using the original name, so
12871                    // rename the new package here.
12872                    pkg.setPackageName(oldName);
12873                    pkgName = pkg.packageName;
12874                    replace = true;
12875                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12876                            + oldName + " pkgName=" + pkgName);
12877                } else if (mPackages.containsKey(pkgName)) {
12878                    // This package, under its official name, already exists
12879                    // on the device; we should replace it.
12880                    replace = true;
12881                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12882                }
12883
12884                // Prevent apps opting out from runtime permissions
12885                if (replace) {
12886                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12887                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12888                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12889                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12890                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12891                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12892                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12893                                        + " doesn't support runtime permissions but the old"
12894                                        + " target SDK " + oldTargetSdk + " does.");
12895                        return;
12896                    }
12897                }
12898            }
12899
12900            PackageSetting ps = mSettings.mPackages.get(pkgName);
12901            if (ps != null) {
12902                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12903
12904                // Quick sanity check that we're signed correctly if updating;
12905                // we'll check this again later when scanning, but we want to
12906                // bail early here before tripping over redefined permissions.
12907                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12908                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12909                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12910                                + pkg.packageName + " upgrade keys do not match the "
12911                                + "previously installed version");
12912                        return;
12913                    }
12914                } else {
12915                    try {
12916                        verifySignaturesLP(ps, pkg);
12917                    } catch (PackageManagerException e) {
12918                        res.setError(e.error, e.getMessage());
12919                        return;
12920                    }
12921                }
12922
12923                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12924                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12925                    systemApp = (ps.pkg.applicationInfo.flags &
12926                            ApplicationInfo.FLAG_SYSTEM) != 0;
12927                }
12928                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12929            }
12930
12931            // Check whether the newly-scanned package wants to define an already-defined perm
12932            int N = pkg.permissions.size();
12933            for (int i = N-1; i >= 0; i--) {
12934                PackageParser.Permission perm = pkg.permissions.get(i);
12935                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12936                if (bp != null) {
12937                    // If the defining package is signed with our cert, it's okay.  This
12938                    // also includes the "updating the same package" case, of course.
12939                    // "updating same package" could also involve key-rotation.
12940                    final boolean sigsOk;
12941                    if (bp.sourcePackage.equals(pkg.packageName)
12942                            && (bp.packageSetting instanceof PackageSetting)
12943                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12944                                    scanFlags))) {
12945                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12946                    } else {
12947                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12948                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12949                    }
12950                    if (!sigsOk) {
12951                        // If the owning package is the system itself, we log but allow
12952                        // install to proceed; we fail the install on all other permission
12953                        // redefinitions.
12954                        if (!bp.sourcePackage.equals("android")) {
12955                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12956                                    + pkg.packageName + " attempting to redeclare permission "
12957                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12958                            res.origPermission = perm.info.name;
12959                            res.origPackage = bp.sourcePackage;
12960                            return;
12961                        } else {
12962                            Slog.w(TAG, "Package " + pkg.packageName
12963                                    + " attempting to redeclare system permission "
12964                                    + perm.info.name + "; ignoring new declaration");
12965                            pkg.permissions.remove(i);
12966                        }
12967                    }
12968                }
12969            }
12970
12971        }
12972
12973        if (systemApp) {
12974            if (onExternal) {
12975                // Abort update; system app can't be replaced with app on sdcard
12976                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12977                        "Cannot install updates to system apps on sdcard");
12978                return;
12979            } else if (ephemeral) {
12980                // Abort update; system app can't be replaced with an ephemeral app
12981                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12982                        "Cannot update a system app with an ephemeral app");
12983                return;
12984            }
12985        }
12986
12987        if (args.move != null) {
12988            // We did an in-place move, so dex is ready to roll
12989            scanFlags |= SCAN_NO_DEX;
12990            scanFlags |= SCAN_MOVE;
12991
12992            synchronized (mPackages) {
12993                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12994                if (ps == null) {
12995                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12996                            "Missing settings for moved package " + pkgName);
12997                }
12998
12999                // We moved the entire application as-is, so bring over the
13000                // previously derived ABI information.
13001                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13002                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13003            }
13004
13005        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13006            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13007            scanFlags |= SCAN_NO_DEX;
13008
13009            try {
13010                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13011                        true /* extract libs */);
13012            } catch (PackageManagerException pme) {
13013                Slog.e(TAG, "Error deriving application ABI", pme);
13014                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13015                return;
13016            }
13017        }
13018
13019        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13020            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13021            return;
13022        }
13023
13024        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13025
13026        if (replace) {
13027            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13028                    installerPackageName, volumeUuid, res);
13029        } else {
13030            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13031                    args.user, installerPackageName, volumeUuid, res);
13032        }
13033        synchronized (mPackages) {
13034            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13035            if (ps != null) {
13036                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13037            }
13038        }
13039    }
13040
13041    private void startIntentFilterVerifications(int userId, boolean replacing,
13042            PackageParser.Package pkg) {
13043        if (mIntentFilterVerifierComponent == null) {
13044            Slog.w(TAG, "No IntentFilter verification will not be done as "
13045                    + "there is no IntentFilterVerifier available!");
13046            return;
13047        }
13048
13049        final int verifierUid = getPackageUid(
13050                mIntentFilterVerifierComponent.getPackageName(),
13051                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13052
13053        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13054        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13055        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13056        mHandler.sendMessage(msg);
13057    }
13058
13059    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13060            PackageParser.Package pkg) {
13061        int size = pkg.activities.size();
13062        if (size == 0) {
13063            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13064                    "No activity, so no need to verify any IntentFilter!");
13065            return;
13066        }
13067
13068        final boolean hasDomainURLs = hasDomainURLs(pkg);
13069        if (!hasDomainURLs) {
13070            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13071                    "No domain URLs, so no need to verify any IntentFilter!");
13072            return;
13073        }
13074
13075        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13076                + " if any IntentFilter from the " + size
13077                + " Activities needs verification ...");
13078
13079        int count = 0;
13080        final String packageName = pkg.packageName;
13081
13082        synchronized (mPackages) {
13083            // If this is a new install and we see that we've already run verification for this
13084            // package, we have nothing to do: it means the state was restored from backup.
13085            if (!replacing) {
13086                IntentFilterVerificationInfo ivi =
13087                        mSettings.getIntentFilterVerificationLPr(packageName);
13088                if (ivi != null) {
13089                    if (DEBUG_DOMAIN_VERIFICATION) {
13090                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13091                                + ivi.getStatusString());
13092                    }
13093                    return;
13094                }
13095            }
13096
13097            // If any filters need to be verified, then all need to be.
13098            boolean needToVerify = false;
13099            for (PackageParser.Activity a : pkg.activities) {
13100                for (ActivityIntentInfo filter : a.intents) {
13101                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13102                        if (DEBUG_DOMAIN_VERIFICATION) {
13103                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13104                        }
13105                        needToVerify = true;
13106                        break;
13107                    }
13108                }
13109            }
13110
13111            if (needToVerify) {
13112                final int verificationId = mIntentFilterVerificationToken++;
13113                for (PackageParser.Activity a : pkg.activities) {
13114                    for (ActivityIntentInfo filter : a.intents) {
13115                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13116                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13117                                    "Verification needed for IntentFilter:" + filter.toString());
13118                            mIntentFilterVerifier.addOneIntentFilterVerification(
13119                                    verifierUid, userId, verificationId, filter, packageName);
13120                            count++;
13121                        }
13122                    }
13123                }
13124            }
13125        }
13126
13127        if (count > 0) {
13128            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13129                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13130                    +  " for userId:" + userId);
13131            mIntentFilterVerifier.startVerifications(userId);
13132        } else {
13133            if (DEBUG_DOMAIN_VERIFICATION) {
13134                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13135            }
13136        }
13137    }
13138
13139    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13140        final ComponentName cn  = filter.activity.getComponentName();
13141        final String packageName = cn.getPackageName();
13142
13143        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13144                packageName);
13145        if (ivi == null) {
13146            return true;
13147        }
13148        int status = ivi.getStatus();
13149        switch (status) {
13150            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13151            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13152                return true;
13153
13154            default:
13155                // Nothing to do
13156                return false;
13157        }
13158    }
13159
13160    private static boolean isMultiArch(ApplicationInfo info) {
13161        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13162    }
13163
13164    private static boolean isExternal(PackageParser.Package pkg) {
13165        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13166    }
13167
13168    private static boolean isExternal(PackageSetting ps) {
13169        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13170    }
13171
13172    private static boolean isEphemeral(PackageParser.Package pkg) {
13173        return pkg.applicationInfo.isEphemeralApp();
13174    }
13175
13176    private static boolean isEphemeral(PackageSetting ps) {
13177        return ps.pkg != null && isEphemeral(ps.pkg);
13178    }
13179
13180    private static boolean isSystemApp(PackageParser.Package pkg) {
13181        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13182    }
13183
13184    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13185        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13186    }
13187
13188    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13189        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13190    }
13191
13192    private static boolean isSystemApp(PackageSetting ps) {
13193        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13194    }
13195
13196    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13197        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13198    }
13199
13200    private int packageFlagsToInstallFlags(PackageSetting ps) {
13201        int installFlags = 0;
13202        if (isEphemeral(ps)) {
13203            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13204        }
13205        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13206            // This existing package was an external ASEC install when we have
13207            // the external flag without a UUID
13208            installFlags |= PackageManager.INSTALL_EXTERNAL;
13209        }
13210        if (ps.isForwardLocked()) {
13211            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13212        }
13213        return installFlags;
13214    }
13215
13216    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13217        if (isExternal(pkg)) {
13218            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13219                return StorageManager.UUID_PRIMARY_PHYSICAL;
13220            } else {
13221                return pkg.volumeUuid;
13222            }
13223        } else {
13224            return StorageManager.UUID_PRIVATE_INTERNAL;
13225        }
13226    }
13227
13228    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13229        if (isExternal(pkg)) {
13230            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13231                return mSettings.getExternalVersion();
13232            } else {
13233                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13234            }
13235        } else {
13236            return mSettings.getInternalVersion();
13237        }
13238    }
13239
13240    private void deleteTempPackageFiles() {
13241        final FilenameFilter filter = new FilenameFilter() {
13242            public boolean accept(File dir, String name) {
13243                return name.startsWith("vmdl") && name.endsWith(".tmp");
13244            }
13245        };
13246        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13247            file.delete();
13248        }
13249    }
13250
13251    @Override
13252    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13253            int flags) {
13254        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13255                flags);
13256    }
13257
13258    @Override
13259    public void deletePackage(final String packageName,
13260            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13261        mContext.enforceCallingOrSelfPermission(
13262                android.Manifest.permission.DELETE_PACKAGES, null);
13263        Preconditions.checkNotNull(packageName);
13264        Preconditions.checkNotNull(observer);
13265        final int uid = Binder.getCallingUid();
13266        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13267        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13268        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13269            mContext.enforceCallingOrSelfPermission(
13270                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13271                    "deletePackage for user " + userId);
13272        }
13273
13274        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13275            try {
13276                observer.onPackageDeleted(packageName,
13277                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13278            } catch (RemoteException re) {
13279            }
13280            return;
13281        }
13282
13283        for (int currentUserId : users) {
13284            if (getBlockUninstallForUser(packageName, currentUserId)) {
13285                try {
13286                    observer.onPackageDeleted(packageName,
13287                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13288                } catch (RemoteException re) {
13289                }
13290                return;
13291            }
13292        }
13293
13294        if (DEBUG_REMOVE) {
13295            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13296        }
13297        // Queue up an async operation since the package deletion may take a little while.
13298        mHandler.post(new Runnable() {
13299            public void run() {
13300                mHandler.removeCallbacks(this);
13301                final int returnCode = deletePackageX(packageName, userId, flags);
13302                try {
13303                    observer.onPackageDeleted(packageName, returnCode, null);
13304                } catch (RemoteException e) {
13305                    Log.i(TAG, "Observer no longer exists.");
13306                } //end catch
13307            } //end run
13308        });
13309    }
13310
13311    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13312        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13313                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13314        try {
13315            if (dpm != null) {
13316                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13317                        /* callingUserOnly =*/ false);
13318                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13319                        : deviceOwnerComponentName.getPackageName();
13320                // Does the package contains the device owner?
13321                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13322                // this check is probably not needed, since DO should be registered as a device
13323                // admin on some user too. (Original bug for this: b/17657954)
13324                if (packageName.equals(deviceOwnerPackageName)) {
13325                    return true;
13326                }
13327                // Does it contain a device admin for any user?
13328                int[] users;
13329                if (userId == UserHandle.USER_ALL) {
13330                    users = sUserManager.getUserIds();
13331                } else {
13332                    users = new int[]{userId};
13333                }
13334                for (int i = 0; i < users.length; ++i) {
13335                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13336                        return true;
13337                    }
13338                }
13339            }
13340        } catch (RemoteException e) {
13341        }
13342        return false;
13343    }
13344
13345    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13346        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13347    }
13348
13349    /**
13350     *  This method is an internal method that could be get invoked either
13351     *  to delete an installed package or to clean up a failed installation.
13352     *  After deleting an installed package, a broadcast is sent to notify any
13353     *  listeners that the package has been installed. For cleaning up a failed
13354     *  installation, the broadcast is not necessary since the package's
13355     *  installation wouldn't have sent the initial broadcast either
13356     *  The key steps in deleting a package are
13357     *  deleting the package information in internal structures like mPackages,
13358     *  deleting the packages base directories through installd
13359     *  updating mSettings to reflect current status
13360     *  persisting settings for later use
13361     *  sending a broadcast if necessary
13362     */
13363    private int deletePackageX(String packageName, int userId, int flags) {
13364        final PackageRemovedInfo info = new PackageRemovedInfo();
13365        final boolean res;
13366
13367        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13368                ? UserHandle.ALL : new UserHandle(userId);
13369
13370        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13371            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13372            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13373        }
13374
13375        boolean removedForAllUsers = false;
13376        boolean systemUpdate = false;
13377
13378        PackageParser.Package uninstalledPkg;
13379
13380        // for the uninstall-updates case and restricted profiles, remember the per-
13381        // userhandle installed state
13382        int[] allUsers;
13383        boolean[] perUserInstalled;
13384        synchronized (mPackages) {
13385            uninstalledPkg = mPackages.get(packageName);
13386            PackageSetting ps = mSettings.mPackages.get(packageName);
13387            allUsers = sUserManager.getUserIds();
13388            perUserInstalled = new boolean[allUsers.length];
13389            for (int i = 0; i < allUsers.length; i++) {
13390                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13391            }
13392        }
13393
13394        synchronized (mInstallLock) {
13395            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13396            res = deletePackageLI(packageName, removeForUser,
13397                    true, allUsers, perUserInstalled,
13398                    flags | REMOVE_CHATTY, info, true);
13399            systemUpdate = info.isRemovedPackageSystemUpdate;
13400            synchronized (mPackages) {
13401                if (res) {
13402                    if (!systemUpdate && mPackages.get(packageName) == null) {
13403                        removedForAllUsers = true;
13404                    }
13405                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13406                }
13407            }
13408            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13409                    + " removedForAllUsers=" + removedForAllUsers);
13410        }
13411
13412        if (res) {
13413            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13414
13415            // If the removed package was a system update, the old system package
13416            // was re-enabled; we need to broadcast this information
13417            if (systemUpdate) {
13418                Bundle extras = new Bundle(1);
13419                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13420                        ? info.removedAppId : info.uid);
13421                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13422
13423                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13424                        extras, 0, null, null, null);
13425                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13426                        extras, 0, null, null, null);
13427                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13428                        null, 0, packageName, null, null);
13429            }
13430        }
13431        // Force a gc here.
13432        Runtime.getRuntime().gc();
13433        // Delete the resources here after sending the broadcast to let
13434        // other processes clean up before deleting resources.
13435        if (info.args != null) {
13436            synchronized (mInstallLock) {
13437                info.args.doPostDeleteLI(true);
13438            }
13439        }
13440
13441        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13442    }
13443
13444    class PackageRemovedInfo {
13445        String removedPackage;
13446        int uid = -1;
13447        int removedAppId = -1;
13448        int[] removedUsers = null;
13449        boolean isRemovedPackageSystemUpdate = false;
13450        // Clean up resources deleted packages.
13451        InstallArgs args = null;
13452
13453        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13454            Bundle extras = new Bundle(1);
13455            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13456            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13457            if (replacing) {
13458                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13459            }
13460            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13461            if (removedPackage != null) {
13462                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13463                        extras, 0, null, null, removedUsers);
13464                if (fullRemove && !replacing) {
13465                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13466                            extras, 0, null, null, removedUsers);
13467                }
13468            }
13469            if (removedAppId >= 0) {
13470                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13471                        removedUsers);
13472            }
13473        }
13474    }
13475
13476    /*
13477     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13478     * flag is not set, the data directory is removed as well.
13479     * make sure this flag is set for partially installed apps. If not its meaningless to
13480     * delete a partially installed application.
13481     */
13482    private void removePackageDataLI(PackageSetting ps,
13483            int[] allUserHandles, boolean[] perUserInstalled,
13484            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13485        String packageName = ps.name;
13486        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13487        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13488        // Retrieve object to delete permissions for shared user later on
13489        final PackageSetting deletedPs;
13490        // reader
13491        synchronized (mPackages) {
13492            deletedPs = mSettings.mPackages.get(packageName);
13493            if (outInfo != null) {
13494                outInfo.removedPackage = packageName;
13495                outInfo.removedUsers = deletedPs != null
13496                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13497                        : null;
13498            }
13499        }
13500        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13501            removeDataDirsLI(ps.volumeUuid, packageName);
13502            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13503        }
13504        // writer
13505        synchronized (mPackages) {
13506            if (deletedPs != null) {
13507                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13508                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13509                    clearDefaultBrowserIfNeeded(packageName);
13510                    if (outInfo != null) {
13511                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13512                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13513                    }
13514                    updatePermissionsLPw(deletedPs.name, null, 0);
13515                    if (deletedPs.sharedUser != null) {
13516                        // Remove permissions associated with package. Since runtime
13517                        // permissions are per user we have to kill the removed package
13518                        // or packages running under the shared user of the removed
13519                        // package if revoking the permissions requested only by the removed
13520                        // package is successful and this causes a change in gids.
13521                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13522                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13523                                    userId);
13524                            if (userIdToKill == UserHandle.USER_ALL
13525                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13526                                // If gids changed for this user, kill all affected packages.
13527                                mHandler.post(new Runnable() {
13528                                    @Override
13529                                    public void run() {
13530                                        // This has to happen with no lock held.
13531                                        killApplication(deletedPs.name, deletedPs.appId,
13532                                                KILL_APP_REASON_GIDS_CHANGED);
13533                                    }
13534                                });
13535                                break;
13536                            }
13537                        }
13538                    }
13539                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13540                }
13541                // make sure to preserve per-user disabled state if this removal was just
13542                // a downgrade of a system app to the factory package
13543                if (allUserHandles != null && perUserInstalled != null) {
13544                    if (DEBUG_REMOVE) {
13545                        Slog.d(TAG, "Propagating install state across downgrade");
13546                    }
13547                    for (int i = 0; i < allUserHandles.length; i++) {
13548                        if (DEBUG_REMOVE) {
13549                            Slog.d(TAG, "    user " + allUserHandles[i]
13550                                    + " => " + perUserInstalled[i]);
13551                        }
13552                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13553                    }
13554                }
13555            }
13556            // can downgrade to reader
13557            if (writeSettings) {
13558                // Save settings now
13559                mSettings.writeLPr();
13560            }
13561        }
13562        if (outInfo != null) {
13563            // A user ID was deleted here. Go through all users and remove it
13564            // from KeyStore.
13565            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13566        }
13567    }
13568
13569    static boolean locationIsPrivileged(File path) {
13570        try {
13571            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13572                    .getCanonicalPath();
13573            return path.getCanonicalPath().startsWith(privilegedAppDir);
13574        } catch (IOException e) {
13575            Slog.e(TAG, "Unable to access code path " + path);
13576        }
13577        return false;
13578    }
13579
13580    /*
13581     * Tries to delete system package.
13582     */
13583    private boolean deleteSystemPackageLI(PackageSetting newPs,
13584            int[] allUserHandles, boolean[] perUserInstalled,
13585            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13586        final boolean applyUserRestrictions
13587                = (allUserHandles != null) && (perUserInstalled != null);
13588        PackageSetting disabledPs = null;
13589        // Confirm if the system package has been updated
13590        // An updated system app can be deleted. This will also have to restore
13591        // the system pkg from system partition
13592        // reader
13593        synchronized (mPackages) {
13594            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13595        }
13596        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13597                + " disabledPs=" + disabledPs);
13598        if (disabledPs == null) {
13599            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13600            return false;
13601        } else if (DEBUG_REMOVE) {
13602            Slog.d(TAG, "Deleting system pkg from data partition");
13603        }
13604        if (DEBUG_REMOVE) {
13605            if (applyUserRestrictions) {
13606                Slog.d(TAG, "Remembering install states:");
13607                for (int i = 0; i < allUserHandles.length; i++) {
13608                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13609                }
13610            }
13611        }
13612        // Delete the updated package
13613        outInfo.isRemovedPackageSystemUpdate = true;
13614        if (disabledPs.versionCode < newPs.versionCode) {
13615            // Delete data for downgrades
13616            flags &= ~PackageManager.DELETE_KEEP_DATA;
13617        } else {
13618            // Preserve data by setting flag
13619            flags |= PackageManager.DELETE_KEEP_DATA;
13620        }
13621        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13622                allUserHandles, perUserInstalled, outInfo, writeSettings);
13623        if (!ret) {
13624            return false;
13625        }
13626        // writer
13627        synchronized (mPackages) {
13628            // Reinstate the old system package
13629            mSettings.enableSystemPackageLPw(newPs.name);
13630            // Remove any native libraries from the upgraded package.
13631            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13632        }
13633        // Install the system package
13634        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13635        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13636        if (locationIsPrivileged(disabledPs.codePath)) {
13637            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13638        }
13639
13640        final PackageParser.Package newPkg;
13641        try {
13642            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13643        } catch (PackageManagerException e) {
13644            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13645            return false;
13646        }
13647
13648        // writer
13649        synchronized (mPackages) {
13650            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13651
13652            // Propagate the permissions state as we do not want to drop on the floor
13653            // runtime permissions. The update permissions method below will take
13654            // care of removing obsolete permissions and grant install permissions.
13655            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13656            updatePermissionsLPw(newPkg.packageName, newPkg,
13657                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13658
13659            if (applyUserRestrictions) {
13660                if (DEBUG_REMOVE) {
13661                    Slog.d(TAG, "Propagating install state across reinstall");
13662                }
13663                for (int i = 0; i < allUserHandles.length; i++) {
13664                    if (DEBUG_REMOVE) {
13665                        Slog.d(TAG, "    user " + allUserHandles[i]
13666                                + " => " + perUserInstalled[i]);
13667                    }
13668                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13669
13670                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13671                }
13672                // Regardless of writeSettings we need to ensure that this restriction
13673                // state propagation is persisted
13674                mSettings.writeAllUsersPackageRestrictionsLPr();
13675            }
13676            // can downgrade to reader here
13677            if (writeSettings) {
13678                mSettings.writeLPr();
13679            }
13680        }
13681        return true;
13682    }
13683
13684    private boolean deleteInstalledPackageLI(PackageSetting ps,
13685            boolean deleteCodeAndResources, int flags,
13686            int[] allUserHandles, boolean[] perUserInstalled,
13687            PackageRemovedInfo outInfo, boolean writeSettings) {
13688        if (outInfo != null) {
13689            outInfo.uid = ps.appId;
13690        }
13691
13692        // Delete package data from internal structures and also remove data if flag is set
13693        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13694
13695        // Delete application code and resources
13696        if (deleteCodeAndResources && (outInfo != null)) {
13697            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13698                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13699            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13700        }
13701        return true;
13702    }
13703
13704    @Override
13705    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13706            int userId) {
13707        mContext.enforceCallingOrSelfPermission(
13708                android.Manifest.permission.DELETE_PACKAGES, null);
13709        synchronized (mPackages) {
13710            PackageSetting ps = mSettings.mPackages.get(packageName);
13711            if (ps == null) {
13712                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13713                return false;
13714            }
13715            if (!ps.getInstalled(userId)) {
13716                // Can't block uninstall for an app that is not installed or enabled.
13717                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13718                return false;
13719            }
13720            ps.setBlockUninstall(blockUninstall, userId);
13721            mSettings.writePackageRestrictionsLPr(userId);
13722        }
13723        return true;
13724    }
13725
13726    @Override
13727    public boolean getBlockUninstallForUser(String packageName, int userId) {
13728        synchronized (mPackages) {
13729            PackageSetting ps = mSettings.mPackages.get(packageName);
13730            if (ps == null) {
13731                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13732                return false;
13733            }
13734            return ps.getBlockUninstall(userId);
13735        }
13736    }
13737
13738    @Override
13739    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13740        int callingUid = Binder.getCallingUid();
13741        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13742            throw new SecurityException(
13743                    "setRequiredForSystemUser can only be run by the system or root");
13744        }
13745        synchronized (mPackages) {
13746            PackageSetting ps = mSettings.mPackages.get(packageName);
13747            if (ps == null) {
13748                Log.w(TAG, "Package doesn't exist: " + packageName);
13749                return false;
13750            }
13751            if (systemUserApp) {
13752                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13753            } else {
13754                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13755            }
13756            mSettings.writeLPr();
13757        }
13758        return true;
13759    }
13760
13761    /*
13762     * This method handles package deletion in general
13763     */
13764    private boolean deletePackageLI(String packageName, UserHandle user,
13765            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13766            int flags, PackageRemovedInfo outInfo,
13767            boolean writeSettings) {
13768        if (packageName == null) {
13769            Slog.w(TAG, "Attempt to delete null packageName.");
13770            return false;
13771        }
13772        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13773        PackageSetting ps;
13774        boolean dataOnly = false;
13775        int removeUser = -1;
13776        int appId = -1;
13777        synchronized (mPackages) {
13778            ps = mSettings.mPackages.get(packageName);
13779            if (ps == null) {
13780                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13781                return false;
13782            }
13783            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13784                    && user.getIdentifier() != UserHandle.USER_ALL) {
13785                // The caller is asking that the package only be deleted for a single
13786                // user.  To do this, we just mark its uninstalled state and delete
13787                // its data.  If this is a system app, we only allow this to happen if
13788                // they have set the special DELETE_SYSTEM_APP which requests different
13789                // semantics than normal for uninstalling system apps.
13790                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13791                final int userId = user.getIdentifier();
13792                ps.setUserState(userId,
13793                        COMPONENT_ENABLED_STATE_DEFAULT,
13794                        false, //installed
13795                        true,  //stopped
13796                        true,  //notLaunched
13797                        false, //hidden
13798                        false, //suspended
13799                        null, null, null,
13800                        false, // blockUninstall
13801                        ps.readUserState(userId).domainVerificationStatus, 0);
13802                if (!isSystemApp(ps)) {
13803                    // Do not uninstall the APK if an app should be cached
13804                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13805                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13806                        // Other user still have this package installed, so all
13807                        // we need to do is clear this user's data and save that
13808                        // it is uninstalled.
13809                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13810                        removeUser = user.getIdentifier();
13811                        appId = ps.appId;
13812                        scheduleWritePackageRestrictionsLocked(removeUser);
13813                    } else {
13814                        // We need to set it back to 'installed' so the uninstall
13815                        // broadcasts will be sent correctly.
13816                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13817                        ps.setInstalled(true, user.getIdentifier());
13818                    }
13819                } else {
13820                    // This is a system app, so we assume that the
13821                    // other users still have this package installed, so all
13822                    // we need to do is clear this user's data and save that
13823                    // it is uninstalled.
13824                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13825                    removeUser = user.getIdentifier();
13826                    appId = ps.appId;
13827                    scheduleWritePackageRestrictionsLocked(removeUser);
13828                }
13829            }
13830        }
13831
13832        if (removeUser >= 0) {
13833            // From above, we determined that we are deleting this only
13834            // for a single user.  Continue the work here.
13835            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13836            if (outInfo != null) {
13837                outInfo.removedPackage = packageName;
13838                outInfo.removedAppId = appId;
13839                outInfo.removedUsers = new int[] {removeUser};
13840            }
13841            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13842            removeKeystoreDataIfNeeded(removeUser, appId);
13843            schedulePackageCleaning(packageName, removeUser, false);
13844            synchronized (mPackages) {
13845                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13846                    scheduleWritePackageRestrictionsLocked(removeUser);
13847                }
13848                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13849            }
13850            return true;
13851        }
13852
13853        if (dataOnly) {
13854            // Delete application data first
13855            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13856            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13857            return true;
13858        }
13859
13860        boolean ret = false;
13861        if (isSystemApp(ps)) {
13862            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13863            // When an updated system application is deleted we delete the existing resources as well and
13864            // fall back to existing code in system partition
13865            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13866                    flags, outInfo, writeSettings);
13867        } else {
13868            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13869            // Kill application pre-emptively especially for apps on sd.
13870            killApplication(packageName, ps.appId, "uninstall pkg");
13871            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13872                    allUserHandles, perUserInstalled,
13873                    outInfo, writeSettings);
13874        }
13875
13876        return ret;
13877    }
13878
13879    private final static class ClearStorageConnection implements ServiceConnection {
13880        IMediaContainerService mContainerService;
13881
13882        @Override
13883        public void onServiceConnected(ComponentName name, IBinder service) {
13884            synchronized (this) {
13885                mContainerService = IMediaContainerService.Stub.asInterface(service);
13886                notifyAll();
13887            }
13888        }
13889
13890        @Override
13891        public void onServiceDisconnected(ComponentName name) {
13892        }
13893    }
13894
13895    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13896        final boolean mounted;
13897        if (Environment.isExternalStorageEmulated()) {
13898            mounted = true;
13899        } else {
13900            final String status = Environment.getExternalStorageState();
13901
13902            mounted = status.equals(Environment.MEDIA_MOUNTED)
13903                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13904        }
13905
13906        if (!mounted) {
13907            return;
13908        }
13909
13910        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13911        int[] users;
13912        if (userId == UserHandle.USER_ALL) {
13913            users = sUserManager.getUserIds();
13914        } else {
13915            users = new int[] { userId };
13916        }
13917        final ClearStorageConnection conn = new ClearStorageConnection();
13918        if (mContext.bindServiceAsUser(
13919                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13920            try {
13921                for (int curUser : users) {
13922                    long timeout = SystemClock.uptimeMillis() + 5000;
13923                    synchronized (conn) {
13924                        long now = SystemClock.uptimeMillis();
13925                        while (conn.mContainerService == null && now < timeout) {
13926                            try {
13927                                conn.wait(timeout - now);
13928                            } catch (InterruptedException e) {
13929                            }
13930                        }
13931                    }
13932                    if (conn.mContainerService == null) {
13933                        return;
13934                    }
13935
13936                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13937                    clearDirectory(conn.mContainerService,
13938                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13939                    if (allData) {
13940                        clearDirectory(conn.mContainerService,
13941                                userEnv.buildExternalStorageAppDataDirs(packageName));
13942                        clearDirectory(conn.mContainerService,
13943                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13944                    }
13945                }
13946            } finally {
13947                mContext.unbindService(conn);
13948            }
13949        }
13950    }
13951
13952    @Override
13953    public void clearApplicationUserData(final String packageName,
13954            final IPackageDataObserver observer, final int userId) {
13955        mContext.enforceCallingOrSelfPermission(
13956                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13957        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13958        // Queue up an async operation since the package deletion may take a little while.
13959        mHandler.post(new Runnable() {
13960            public void run() {
13961                mHandler.removeCallbacks(this);
13962                final boolean succeeded;
13963                synchronized (mInstallLock) {
13964                    succeeded = clearApplicationUserDataLI(packageName, userId);
13965                }
13966                clearExternalStorageDataSync(packageName, userId, true);
13967                if (succeeded) {
13968                    // invoke DeviceStorageMonitor's update method to clear any notifications
13969                    DeviceStorageMonitorInternal
13970                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13971                    if (dsm != null) {
13972                        dsm.checkMemory();
13973                    }
13974                }
13975                if(observer != null) {
13976                    try {
13977                        observer.onRemoveCompleted(packageName, succeeded);
13978                    } catch (RemoteException e) {
13979                        Log.i(TAG, "Observer no longer exists.");
13980                    }
13981                } //end if observer
13982            } //end run
13983        });
13984    }
13985
13986    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13987        if (packageName == null) {
13988            Slog.w(TAG, "Attempt to delete null packageName.");
13989            return false;
13990        }
13991
13992        // Try finding details about the requested package
13993        PackageParser.Package pkg;
13994        synchronized (mPackages) {
13995            pkg = mPackages.get(packageName);
13996            if (pkg == null) {
13997                final PackageSetting ps = mSettings.mPackages.get(packageName);
13998                if (ps != null) {
13999                    pkg = ps.pkg;
14000                }
14001            }
14002
14003            if (pkg == null) {
14004                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14005                return false;
14006            }
14007
14008            PackageSetting ps = (PackageSetting) pkg.mExtras;
14009            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14010        }
14011
14012        // Always delete data directories for package, even if we found no other
14013        // record of app. This helps users recover from UID mismatches without
14014        // resorting to a full data wipe.
14015        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14016        if (retCode < 0) {
14017            Slog.w(TAG, "Couldn't remove cache files for package " + packageName);
14018            return false;
14019        }
14020
14021        final int appId = pkg.applicationInfo.uid;
14022        removeKeystoreDataIfNeeded(userId, appId);
14023
14024        // Create a native library symlink only if we have native libraries
14025        // and if the native libraries are 32 bit libraries. We do not provide
14026        // this symlink for 64 bit libraries.
14027        if (pkg.applicationInfo.primaryCpuAbi != null &&
14028                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14029            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14030            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14031                    nativeLibPath, userId) < 0) {
14032                Slog.w(TAG, "Failed linking native library dir");
14033                return false;
14034            }
14035        }
14036
14037        return true;
14038    }
14039
14040    /**
14041     * Reverts user permission state changes (permissions and flags) in
14042     * all packages for a given user.
14043     *
14044     * @param userId The device user for which to do a reset.
14045     */
14046    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14047        final int packageCount = mPackages.size();
14048        for (int i = 0; i < packageCount; i++) {
14049            PackageParser.Package pkg = mPackages.valueAt(i);
14050            PackageSetting ps = (PackageSetting) pkg.mExtras;
14051            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14052        }
14053    }
14054
14055    /**
14056     * Reverts user permission state changes (permissions and flags).
14057     *
14058     * @param ps The package for which to reset.
14059     * @param userId The device user for which to do a reset.
14060     */
14061    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14062            final PackageSetting ps, final int userId) {
14063        if (ps.pkg == null) {
14064            return;
14065        }
14066
14067        // These are flags that can change base on user actions.
14068        final int userSettableMask = FLAG_PERMISSION_USER_SET
14069                | FLAG_PERMISSION_USER_FIXED
14070                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14071                | FLAG_PERMISSION_REVIEW_REQUIRED;
14072
14073        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14074                | FLAG_PERMISSION_POLICY_FIXED;
14075
14076        boolean writeInstallPermissions = false;
14077        boolean writeRuntimePermissions = false;
14078
14079        final int permissionCount = ps.pkg.requestedPermissions.size();
14080        for (int i = 0; i < permissionCount; i++) {
14081            String permission = ps.pkg.requestedPermissions.get(i);
14082
14083            BasePermission bp = mSettings.mPermissions.get(permission);
14084            if (bp == null) {
14085                continue;
14086            }
14087
14088            // If shared user we just reset the state to which only this app contributed.
14089            if (ps.sharedUser != null) {
14090                boolean used = false;
14091                final int packageCount = ps.sharedUser.packages.size();
14092                for (int j = 0; j < packageCount; j++) {
14093                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14094                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14095                            && pkg.pkg.requestedPermissions.contains(permission)) {
14096                        used = true;
14097                        break;
14098                    }
14099                }
14100                if (used) {
14101                    continue;
14102                }
14103            }
14104
14105            PermissionsState permissionsState = ps.getPermissionsState();
14106
14107            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14108
14109            // Always clear the user settable flags.
14110            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14111                    bp.name) != null;
14112            // If permission review is enabled and this is a legacy app, mark the
14113            // permission as requiring a review as this is the initial state.
14114            int flags = 0;
14115            if (Build.PERMISSIONS_REVIEW_REQUIRED
14116                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14117                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14118            }
14119            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14120                if (hasInstallState) {
14121                    writeInstallPermissions = true;
14122                } else {
14123                    writeRuntimePermissions = true;
14124                }
14125            }
14126
14127            // Below is only runtime permission handling.
14128            if (!bp.isRuntime()) {
14129                continue;
14130            }
14131
14132            // Never clobber system or policy.
14133            if ((oldFlags & policyOrSystemFlags) != 0) {
14134                continue;
14135            }
14136
14137            // If this permission was granted by default, make sure it is.
14138            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14139                if (permissionsState.grantRuntimePermission(bp, userId)
14140                        != PERMISSION_OPERATION_FAILURE) {
14141                    writeRuntimePermissions = true;
14142                }
14143            // If permission review is enabled the permissions for a legacy apps
14144            // are represented as constantly granted runtime ones, so don't revoke.
14145            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14146                // Otherwise, reset the permission.
14147                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14148                switch (revokeResult) {
14149                    case PERMISSION_OPERATION_SUCCESS: {
14150                        writeRuntimePermissions = true;
14151                    } break;
14152
14153                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14154                        writeRuntimePermissions = true;
14155                        final int appId = ps.appId;
14156                        mHandler.post(new Runnable() {
14157                            @Override
14158                            public void run() {
14159                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14160                            }
14161                        });
14162                    } break;
14163                }
14164            }
14165        }
14166
14167        // Synchronously write as we are taking permissions away.
14168        if (writeRuntimePermissions) {
14169            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14170        }
14171
14172        // Synchronously write as we are taking permissions away.
14173        if (writeInstallPermissions) {
14174            mSettings.writeLPr();
14175        }
14176    }
14177
14178    /**
14179     * Remove entries from the keystore daemon. Will only remove it if the
14180     * {@code appId} is valid.
14181     */
14182    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14183        if (appId < 0) {
14184            return;
14185        }
14186
14187        final KeyStore keyStore = KeyStore.getInstance();
14188        if (keyStore != null) {
14189            if (userId == UserHandle.USER_ALL) {
14190                for (final int individual : sUserManager.getUserIds()) {
14191                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14192                }
14193            } else {
14194                keyStore.clearUid(UserHandle.getUid(userId, appId));
14195            }
14196        } else {
14197            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14198        }
14199    }
14200
14201    @Override
14202    public void deleteApplicationCacheFiles(final String packageName,
14203            final IPackageDataObserver observer) {
14204        mContext.enforceCallingOrSelfPermission(
14205                android.Manifest.permission.DELETE_CACHE_FILES, null);
14206        // Queue up an async operation since the package deletion may take a little while.
14207        final int userId = UserHandle.getCallingUserId();
14208        mHandler.post(new Runnable() {
14209            public void run() {
14210                mHandler.removeCallbacks(this);
14211                final boolean succeded;
14212                synchronized (mInstallLock) {
14213                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14214                }
14215                clearExternalStorageDataSync(packageName, userId, false);
14216                if (observer != null) {
14217                    try {
14218                        observer.onRemoveCompleted(packageName, succeded);
14219                    } catch (RemoteException e) {
14220                        Log.i(TAG, "Observer no longer exists.");
14221                    }
14222                } //end if observer
14223            } //end run
14224        });
14225    }
14226
14227    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14228        if (packageName == null) {
14229            Slog.w(TAG, "Attempt to delete null packageName.");
14230            return false;
14231        }
14232        PackageParser.Package p;
14233        synchronized (mPackages) {
14234            p = mPackages.get(packageName);
14235        }
14236        if (p == null) {
14237            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14238            return false;
14239        }
14240        final ApplicationInfo applicationInfo = p.applicationInfo;
14241        if (applicationInfo == null) {
14242            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14243            return false;
14244        }
14245        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14246        if (retCode < 0) {
14247            Slog.w(TAG, "Couldn't remove cache files for package "
14248                       + packageName + " u" + userId);
14249            return false;
14250        }
14251        return true;
14252    }
14253
14254    @Override
14255    public void getPackageSizeInfo(final String packageName, int userHandle,
14256            final IPackageStatsObserver observer) {
14257        mContext.enforceCallingOrSelfPermission(
14258                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14259        if (packageName == null) {
14260            throw new IllegalArgumentException("Attempt to get size of null packageName");
14261        }
14262
14263        PackageStats stats = new PackageStats(packageName, userHandle);
14264
14265        /*
14266         * Queue up an async operation since the package measurement may take a
14267         * little while.
14268         */
14269        Message msg = mHandler.obtainMessage(INIT_COPY);
14270        msg.obj = new MeasureParams(stats, observer);
14271        mHandler.sendMessage(msg);
14272    }
14273
14274    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14275            PackageStats pStats) {
14276        if (packageName == null) {
14277            Slog.w(TAG, "Attempt to get size of null packageName.");
14278            return false;
14279        }
14280        PackageParser.Package p;
14281        boolean dataOnly = false;
14282        String libDirRoot = null;
14283        String asecPath = null;
14284        PackageSetting ps = null;
14285        synchronized (mPackages) {
14286            p = mPackages.get(packageName);
14287            ps = mSettings.mPackages.get(packageName);
14288            if(p == null) {
14289                dataOnly = true;
14290                if((ps == null) || (ps.pkg == null)) {
14291                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14292                    return false;
14293                }
14294                p = ps.pkg;
14295            }
14296            if (ps != null) {
14297                libDirRoot = ps.legacyNativeLibraryPathString;
14298            }
14299            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14300                final long token = Binder.clearCallingIdentity();
14301                try {
14302                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14303                    if (secureContainerId != null) {
14304                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14305                    }
14306                } finally {
14307                    Binder.restoreCallingIdentity(token);
14308                }
14309            }
14310        }
14311        String publicSrcDir = null;
14312        if(!dataOnly) {
14313            final ApplicationInfo applicationInfo = p.applicationInfo;
14314            if (applicationInfo == null) {
14315                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14316                return false;
14317            }
14318            if (p.isForwardLocked()) {
14319                publicSrcDir = applicationInfo.getBaseResourcePath();
14320            }
14321        }
14322        // TODO: extend to measure size of split APKs
14323        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14324        // not just the first level.
14325        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14326        // just the primary.
14327        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14328
14329        String apkPath;
14330        File packageDir = new File(p.codePath);
14331
14332        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14333            apkPath = packageDir.getAbsolutePath();
14334            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14335            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14336                libDirRoot = null;
14337            }
14338        } else {
14339            apkPath = p.baseCodePath;
14340        }
14341
14342        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14343                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14344        if (res < 0) {
14345            return false;
14346        }
14347
14348        // Fix-up for forward-locked applications in ASEC containers.
14349        if (!isExternal(p)) {
14350            pStats.codeSize += pStats.externalCodeSize;
14351            pStats.externalCodeSize = 0L;
14352        }
14353
14354        return true;
14355    }
14356
14357
14358    @Override
14359    public void addPackageToPreferred(String packageName) {
14360        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14361    }
14362
14363    @Override
14364    public void removePackageFromPreferred(String packageName) {
14365        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14366    }
14367
14368    @Override
14369    public List<PackageInfo> getPreferredPackages(int flags) {
14370        return new ArrayList<PackageInfo>();
14371    }
14372
14373    private int getUidTargetSdkVersionLockedLPr(int uid) {
14374        Object obj = mSettings.getUserIdLPr(uid);
14375        if (obj instanceof SharedUserSetting) {
14376            final SharedUserSetting sus = (SharedUserSetting) obj;
14377            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14378            final Iterator<PackageSetting> it = sus.packages.iterator();
14379            while (it.hasNext()) {
14380                final PackageSetting ps = it.next();
14381                if (ps.pkg != null) {
14382                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14383                    if (v < vers) vers = v;
14384                }
14385            }
14386            return vers;
14387        } else if (obj instanceof PackageSetting) {
14388            final PackageSetting ps = (PackageSetting) obj;
14389            if (ps.pkg != null) {
14390                return ps.pkg.applicationInfo.targetSdkVersion;
14391            }
14392        }
14393        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14394    }
14395
14396    @Override
14397    public void addPreferredActivity(IntentFilter filter, int match,
14398            ComponentName[] set, ComponentName activity, int userId) {
14399        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14400                "Adding preferred");
14401    }
14402
14403    private void addPreferredActivityInternal(IntentFilter filter, int match,
14404            ComponentName[] set, ComponentName activity, boolean always, int userId,
14405            String opname) {
14406        // writer
14407        int callingUid = Binder.getCallingUid();
14408        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14409        if (filter.countActions() == 0) {
14410            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14411            return;
14412        }
14413        synchronized (mPackages) {
14414            if (mContext.checkCallingOrSelfPermission(
14415                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14416                    != PackageManager.PERMISSION_GRANTED) {
14417                if (getUidTargetSdkVersionLockedLPr(callingUid)
14418                        < Build.VERSION_CODES.FROYO) {
14419                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14420                            + callingUid);
14421                    return;
14422                }
14423                mContext.enforceCallingOrSelfPermission(
14424                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14425            }
14426
14427            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14428            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14429                    + userId + ":");
14430            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14431            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14432            scheduleWritePackageRestrictionsLocked(userId);
14433        }
14434    }
14435
14436    @Override
14437    public void replacePreferredActivity(IntentFilter filter, int match,
14438            ComponentName[] set, ComponentName activity, int userId) {
14439        if (filter.countActions() != 1) {
14440            throw new IllegalArgumentException(
14441                    "replacePreferredActivity expects filter to have only 1 action.");
14442        }
14443        if (filter.countDataAuthorities() != 0
14444                || filter.countDataPaths() != 0
14445                || filter.countDataSchemes() > 1
14446                || filter.countDataTypes() != 0) {
14447            throw new IllegalArgumentException(
14448                    "replacePreferredActivity expects filter to have no data authorities, " +
14449                    "paths, or types; and at most one scheme.");
14450        }
14451
14452        final int callingUid = Binder.getCallingUid();
14453        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14454        synchronized (mPackages) {
14455            if (mContext.checkCallingOrSelfPermission(
14456                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14457                    != PackageManager.PERMISSION_GRANTED) {
14458                if (getUidTargetSdkVersionLockedLPr(callingUid)
14459                        < Build.VERSION_CODES.FROYO) {
14460                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14461                            + Binder.getCallingUid());
14462                    return;
14463                }
14464                mContext.enforceCallingOrSelfPermission(
14465                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14466            }
14467
14468            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14469            if (pir != null) {
14470                // Get all of the existing entries that exactly match this filter.
14471                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14472                if (existing != null && existing.size() == 1) {
14473                    PreferredActivity cur = existing.get(0);
14474                    if (DEBUG_PREFERRED) {
14475                        Slog.i(TAG, "Checking replace of preferred:");
14476                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14477                        if (!cur.mPref.mAlways) {
14478                            Slog.i(TAG, "  -- CUR; not mAlways!");
14479                        } else {
14480                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14481                            Slog.i(TAG, "  -- CUR: mSet="
14482                                    + Arrays.toString(cur.mPref.mSetComponents));
14483                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14484                            Slog.i(TAG, "  -- NEW: mMatch="
14485                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14486                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14487                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14488                        }
14489                    }
14490                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14491                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14492                            && cur.mPref.sameSet(set)) {
14493                        // Setting the preferred activity to what it happens to be already
14494                        if (DEBUG_PREFERRED) {
14495                            Slog.i(TAG, "Replacing with same preferred activity "
14496                                    + cur.mPref.mShortComponent + " for user "
14497                                    + userId + ":");
14498                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14499                        }
14500                        return;
14501                    }
14502                }
14503
14504                if (existing != null) {
14505                    if (DEBUG_PREFERRED) {
14506                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14507                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14508                    }
14509                    for (int i = 0; i < existing.size(); i++) {
14510                        PreferredActivity pa = existing.get(i);
14511                        if (DEBUG_PREFERRED) {
14512                            Slog.i(TAG, "Removing existing preferred activity "
14513                                    + pa.mPref.mComponent + ":");
14514                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14515                        }
14516                        pir.removeFilter(pa);
14517                    }
14518                }
14519            }
14520            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14521                    "Replacing preferred");
14522        }
14523    }
14524
14525    @Override
14526    public void clearPackagePreferredActivities(String packageName) {
14527        final int uid = Binder.getCallingUid();
14528        // writer
14529        synchronized (mPackages) {
14530            PackageParser.Package pkg = mPackages.get(packageName);
14531            if (pkg == null || pkg.applicationInfo.uid != uid) {
14532                if (mContext.checkCallingOrSelfPermission(
14533                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14534                        != PackageManager.PERMISSION_GRANTED) {
14535                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14536                            < Build.VERSION_CODES.FROYO) {
14537                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14538                                + Binder.getCallingUid());
14539                        return;
14540                    }
14541                    mContext.enforceCallingOrSelfPermission(
14542                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14543                }
14544            }
14545
14546            int user = UserHandle.getCallingUserId();
14547            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14548                scheduleWritePackageRestrictionsLocked(user);
14549            }
14550        }
14551    }
14552
14553    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14554    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14555        ArrayList<PreferredActivity> removed = null;
14556        boolean changed = false;
14557        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14558            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14559            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14560            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14561                continue;
14562            }
14563            Iterator<PreferredActivity> it = pir.filterIterator();
14564            while (it.hasNext()) {
14565                PreferredActivity pa = it.next();
14566                // Mark entry for removal only if it matches the package name
14567                // and the entry is of type "always".
14568                if (packageName == null ||
14569                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14570                                && pa.mPref.mAlways)) {
14571                    if (removed == null) {
14572                        removed = new ArrayList<PreferredActivity>();
14573                    }
14574                    removed.add(pa);
14575                }
14576            }
14577            if (removed != null) {
14578                for (int j=0; j<removed.size(); j++) {
14579                    PreferredActivity pa = removed.get(j);
14580                    pir.removeFilter(pa);
14581                }
14582                changed = true;
14583            }
14584        }
14585        return changed;
14586    }
14587
14588    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14589    private void clearIntentFilterVerificationsLPw(int userId) {
14590        final int packageCount = mPackages.size();
14591        for (int i = 0; i < packageCount; i++) {
14592            PackageParser.Package pkg = mPackages.valueAt(i);
14593            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14594        }
14595    }
14596
14597    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14598    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14599        if (userId == UserHandle.USER_ALL) {
14600            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14601                    sUserManager.getUserIds())) {
14602                for (int oneUserId : sUserManager.getUserIds()) {
14603                    scheduleWritePackageRestrictionsLocked(oneUserId);
14604                }
14605            }
14606        } else {
14607            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14608                scheduleWritePackageRestrictionsLocked(userId);
14609            }
14610        }
14611    }
14612
14613    void clearDefaultBrowserIfNeeded(String packageName) {
14614        for (int oneUserId : sUserManager.getUserIds()) {
14615            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14616            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14617            if (packageName.equals(defaultBrowserPackageName)) {
14618                setDefaultBrowserPackageName(null, oneUserId);
14619            }
14620        }
14621    }
14622
14623    @Override
14624    public void resetApplicationPreferences(int userId) {
14625        mContext.enforceCallingOrSelfPermission(
14626                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14627        // writer
14628        synchronized (mPackages) {
14629            final long identity = Binder.clearCallingIdentity();
14630            try {
14631                clearPackagePreferredActivitiesLPw(null, userId);
14632                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14633                // TODO: We have to reset the default SMS and Phone. This requires
14634                // significant refactoring to keep all default apps in the package
14635                // manager (cleaner but more work) or have the services provide
14636                // callbacks to the package manager to request a default app reset.
14637                applyFactoryDefaultBrowserLPw(userId);
14638                clearIntentFilterVerificationsLPw(userId);
14639                primeDomainVerificationsLPw(userId);
14640                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14641                scheduleWritePackageRestrictionsLocked(userId);
14642            } finally {
14643                Binder.restoreCallingIdentity(identity);
14644            }
14645        }
14646    }
14647
14648    @Override
14649    public int getPreferredActivities(List<IntentFilter> outFilters,
14650            List<ComponentName> outActivities, String packageName) {
14651
14652        int num = 0;
14653        final int userId = UserHandle.getCallingUserId();
14654        // reader
14655        synchronized (mPackages) {
14656            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14657            if (pir != null) {
14658                final Iterator<PreferredActivity> it = pir.filterIterator();
14659                while (it.hasNext()) {
14660                    final PreferredActivity pa = it.next();
14661                    if (packageName == null
14662                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14663                                    && pa.mPref.mAlways)) {
14664                        if (outFilters != null) {
14665                            outFilters.add(new IntentFilter(pa));
14666                        }
14667                        if (outActivities != null) {
14668                            outActivities.add(pa.mPref.mComponent);
14669                        }
14670                    }
14671                }
14672            }
14673        }
14674
14675        return num;
14676    }
14677
14678    @Override
14679    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14680            int userId) {
14681        int callingUid = Binder.getCallingUid();
14682        if (callingUid != Process.SYSTEM_UID) {
14683            throw new SecurityException(
14684                    "addPersistentPreferredActivity can only be run by the system");
14685        }
14686        if (filter.countActions() == 0) {
14687            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14688            return;
14689        }
14690        synchronized (mPackages) {
14691            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14692                    ":");
14693            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14694            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14695                    new PersistentPreferredActivity(filter, activity));
14696            scheduleWritePackageRestrictionsLocked(userId);
14697        }
14698    }
14699
14700    @Override
14701    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14702        int callingUid = Binder.getCallingUid();
14703        if (callingUid != Process.SYSTEM_UID) {
14704            throw new SecurityException(
14705                    "clearPackagePersistentPreferredActivities can only be run by the system");
14706        }
14707        ArrayList<PersistentPreferredActivity> removed = null;
14708        boolean changed = false;
14709        synchronized (mPackages) {
14710            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14711                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14712                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14713                        .valueAt(i);
14714                if (userId != thisUserId) {
14715                    continue;
14716                }
14717                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14718                while (it.hasNext()) {
14719                    PersistentPreferredActivity ppa = it.next();
14720                    // Mark entry for removal only if it matches the package name.
14721                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14722                        if (removed == null) {
14723                            removed = new ArrayList<PersistentPreferredActivity>();
14724                        }
14725                        removed.add(ppa);
14726                    }
14727                }
14728                if (removed != null) {
14729                    for (int j=0; j<removed.size(); j++) {
14730                        PersistentPreferredActivity ppa = removed.get(j);
14731                        ppir.removeFilter(ppa);
14732                    }
14733                    changed = true;
14734                }
14735            }
14736
14737            if (changed) {
14738                scheduleWritePackageRestrictionsLocked(userId);
14739            }
14740        }
14741    }
14742
14743    /**
14744     * Common machinery for picking apart a restored XML blob and passing
14745     * it to a caller-supplied functor to be applied to the running system.
14746     */
14747    private void restoreFromXml(XmlPullParser parser, int userId,
14748            String expectedStartTag, BlobXmlRestorer functor)
14749            throws IOException, XmlPullParserException {
14750        int type;
14751        while ((type = parser.next()) != XmlPullParser.START_TAG
14752                && type != XmlPullParser.END_DOCUMENT) {
14753        }
14754        if (type != XmlPullParser.START_TAG) {
14755            // oops didn't find a start tag?!
14756            if (DEBUG_BACKUP) {
14757                Slog.e(TAG, "Didn't find start tag during restore");
14758            }
14759            return;
14760        }
14761
14762        // this is supposed to be TAG_PREFERRED_BACKUP
14763        if (!expectedStartTag.equals(parser.getName())) {
14764            if (DEBUG_BACKUP) {
14765                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14766            }
14767            return;
14768        }
14769
14770        // skip interfering stuff, then we're aligned with the backing implementation
14771        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14772        functor.apply(parser, userId);
14773    }
14774
14775    private interface BlobXmlRestorer {
14776        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14777    }
14778
14779    /**
14780     * Non-Binder method, support for the backup/restore mechanism: write the
14781     * full set of preferred activities in its canonical XML format.  Returns the
14782     * XML output as a byte array, or null if there is none.
14783     */
14784    @Override
14785    public byte[] getPreferredActivityBackup(int userId) {
14786        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14787            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14788        }
14789
14790        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14791        try {
14792            final XmlSerializer serializer = new FastXmlSerializer();
14793            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14794            serializer.startDocument(null, true);
14795            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14796
14797            synchronized (mPackages) {
14798                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14799            }
14800
14801            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14802            serializer.endDocument();
14803            serializer.flush();
14804        } catch (Exception e) {
14805            if (DEBUG_BACKUP) {
14806                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14807            }
14808            return null;
14809        }
14810
14811        return dataStream.toByteArray();
14812    }
14813
14814    @Override
14815    public void restorePreferredActivities(byte[] backup, int userId) {
14816        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14817            throw new SecurityException("Only the system may call restorePreferredActivities()");
14818        }
14819
14820        try {
14821            final XmlPullParser parser = Xml.newPullParser();
14822            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14823            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14824                    new BlobXmlRestorer() {
14825                        @Override
14826                        public void apply(XmlPullParser parser, int userId)
14827                                throws XmlPullParserException, IOException {
14828                            synchronized (mPackages) {
14829                                mSettings.readPreferredActivitiesLPw(parser, userId);
14830                            }
14831                        }
14832                    } );
14833        } catch (Exception e) {
14834            if (DEBUG_BACKUP) {
14835                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14836            }
14837        }
14838    }
14839
14840    /**
14841     * Non-Binder method, support for the backup/restore mechanism: write the
14842     * default browser (etc) settings in its canonical XML format.  Returns the default
14843     * browser XML representation as a byte array, or null if there is none.
14844     */
14845    @Override
14846    public byte[] getDefaultAppsBackup(int userId) {
14847        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14848            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14849        }
14850
14851        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14852        try {
14853            final XmlSerializer serializer = new FastXmlSerializer();
14854            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14855            serializer.startDocument(null, true);
14856            serializer.startTag(null, TAG_DEFAULT_APPS);
14857
14858            synchronized (mPackages) {
14859                mSettings.writeDefaultAppsLPr(serializer, userId);
14860            }
14861
14862            serializer.endTag(null, TAG_DEFAULT_APPS);
14863            serializer.endDocument();
14864            serializer.flush();
14865        } catch (Exception e) {
14866            if (DEBUG_BACKUP) {
14867                Slog.e(TAG, "Unable to write default apps for backup", e);
14868            }
14869            return null;
14870        }
14871
14872        return dataStream.toByteArray();
14873    }
14874
14875    @Override
14876    public void restoreDefaultApps(byte[] backup, int userId) {
14877        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14878            throw new SecurityException("Only the system may call restoreDefaultApps()");
14879        }
14880
14881        try {
14882            final XmlPullParser parser = Xml.newPullParser();
14883            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14884            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14885                    new BlobXmlRestorer() {
14886                        @Override
14887                        public void apply(XmlPullParser parser, int userId)
14888                                throws XmlPullParserException, IOException {
14889                            synchronized (mPackages) {
14890                                mSettings.readDefaultAppsLPw(parser, userId);
14891                            }
14892                        }
14893                    } );
14894        } catch (Exception e) {
14895            if (DEBUG_BACKUP) {
14896                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14897            }
14898        }
14899    }
14900
14901    @Override
14902    public byte[] getIntentFilterVerificationBackup(int userId) {
14903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14904            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14905        }
14906
14907        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14908        try {
14909            final XmlSerializer serializer = new FastXmlSerializer();
14910            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14911            serializer.startDocument(null, true);
14912            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14913
14914            synchronized (mPackages) {
14915                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14916            }
14917
14918            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14919            serializer.endDocument();
14920            serializer.flush();
14921        } catch (Exception e) {
14922            if (DEBUG_BACKUP) {
14923                Slog.e(TAG, "Unable to write default apps for backup", e);
14924            }
14925            return null;
14926        }
14927
14928        return dataStream.toByteArray();
14929    }
14930
14931    @Override
14932    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14933        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14934            throw new SecurityException("Only the system may call restorePreferredActivities()");
14935        }
14936
14937        try {
14938            final XmlPullParser parser = Xml.newPullParser();
14939            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14940            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14941                    new BlobXmlRestorer() {
14942                        @Override
14943                        public void apply(XmlPullParser parser, int userId)
14944                                throws XmlPullParserException, IOException {
14945                            synchronized (mPackages) {
14946                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14947                                mSettings.writeLPr();
14948                            }
14949                        }
14950                    } );
14951        } catch (Exception e) {
14952            if (DEBUG_BACKUP) {
14953                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14954            }
14955        }
14956    }
14957
14958    @Override
14959    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14960            int sourceUserId, int targetUserId, int flags) {
14961        mContext.enforceCallingOrSelfPermission(
14962                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14963        int callingUid = Binder.getCallingUid();
14964        enforceOwnerRights(ownerPackage, callingUid);
14965        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14966        if (intentFilter.countActions() == 0) {
14967            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14968            return;
14969        }
14970        synchronized (mPackages) {
14971            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14972                    ownerPackage, targetUserId, flags);
14973            CrossProfileIntentResolver resolver =
14974                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14975            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14976            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14977            if (existing != null) {
14978                int size = existing.size();
14979                for (int i = 0; i < size; i++) {
14980                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14981                        return;
14982                    }
14983                }
14984            }
14985            resolver.addFilter(newFilter);
14986            scheduleWritePackageRestrictionsLocked(sourceUserId);
14987        }
14988    }
14989
14990    @Override
14991    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14992        mContext.enforceCallingOrSelfPermission(
14993                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14994        int callingUid = Binder.getCallingUid();
14995        enforceOwnerRights(ownerPackage, callingUid);
14996        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14997        synchronized (mPackages) {
14998            CrossProfileIntentResolver resolver =
14999                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15000            ArraySet<CrossProfileIntentFilter> set =
15001                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15002            for (CrossProfileIntentFilter filter : set) {
15003                if (filter.getOwnerPackage().equals(ownerPackage)) {
15004                    resolver.removeFilter(filter);
15005                }
15006            }
15007            scheduleWritePackageRestrictionsLocked(sourceUserId);
15008        }
15009    }
15010
15011    // Enforcing that callingUid is owning pkg on userId
15012    private void enforceOwnerRights(String pkg, int callingUid) {
15013        // The system owns everything.
15014        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15015            return;
15016        }
15017        int callingUserId = UserHandle.getUserId(callingUid);
15018        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15019        if (pi == null) {
15020            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15021                    + callingUserId);
15022        }
15023        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15024            throw new SecurityException("Calling uid " + callingUid
15025                    + " does not own package " + pkg);
15026        }
15027    }
15028
15029    @Override
15030    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15031        Intent intent = new Intent(Intent.ACTION_MAIN);
15032        intent.addCategory(Intent.CATEGORY_HOME);
15033
15034        final int callingUserId = UserHandle.getCallingUserId();
15035        List<ResolveInfo> list = queryIntentActivities(intent, null,
15036                PackageManager.GET_META_DATA, callingUserId);
15037        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15038                true, false, false, callingUserId);
15039
15040        allHomeCandidates.clear();
15041        if (list != null) {
15042            for (ResolveInfo ri : list) {
15043                allHomeCandidates.add(ri);
15044            }
15045        }
15046        return (preferred == null || preferred.activityInfo == null)
15047                ? null
15048                : new ComponentName(preferred.activityInfo.packageName,
15049                        preferred.activityInfo.name);
15050    }
15051
15052    @Override
15053    public void setApplicationEnabledSetting(String appPackageName,
15054            int newState, int flags, int userId, String callingPackage) {
15055        if (!sUserManager.exists(userId)) return;
15056        if (callingPackage == null) {
15057            callingPackage = Integer.toString(Binder.getCallingUid());
15058        }
15059        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15060    }
15061
15062    @Override
15063    public void setComponentEnabledSetting(ComponentName componentName,
15064            int newState, int flags, int userId) {
15065        if (!sUserManager.exists(userId)) return;
15066        setEnabledSetting(componentName.getPackageName(),
15067                componentName.getClassName(), newState, flags, userId, null);
15068    }
15069
15070    private void setEnabledSetting(final String packageName, String className, int newState,
15071            final int flags, int userId, String callingPackage) {
15072        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15073              || newState == COMPONENT_ENABLED_STATE_ENABLED
15074              || newState == COMPONENT_ENABLED_STATE_DISABLED
15075              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15076              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15077            throw new IllegalArgumentException("Invalid new component state: "
15078                    + newState);
15079        }
15080        PackageSetting pkgSetting;
15081        final int uid = Binder.getCallingUid();
15082        final int permission = mContext.checkCallingOrSelfPermission(
15083                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15084        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15085        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15086        boolean sendNow = false;
15087        boolean isApp = (className == null);
15088        String componentName = isApp ? packageName : className;
15089        int packageUid = -1;
15090        ArrayList<String> components;
15091
15092        // writer
15093        synchronized (mPackages) {
15094            pkgSetting = mSettings.mPackages.get(packageName);
15095            if (pkgSetting == null) {
15096                if (className == null) {
15097                    throw new IllegalArgumentException("Unknown package: " + packageName);
15098                }
15099                throw new IllegalArgumentException(
15100                        "Unknown component: " + packageName + "/" + className);
15101            }
15102            // Allow root and verify that userId is not being specified by a different user
15103            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15104                throw new SecurityException(
15105                        "Permission Denial: attempt to change component state from pid="
15106                        + Binder.getCallingPid()
15107                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15108            }
15109            if (className == null) {
15110                // We're dealing with an application/package level state change
15111                if (pkgSetting.getEnabled(userId) == newState) {
15112                    // Nothing to do
15113                    return;
15114                }
15115                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15116                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15117                    // Don't care about who enables an app.
15118                    callingPackage = null;
15119                }
15120                pkgSetting.setEnabled(newState, userId, callingPackage);
15121                // pkgSetting.pkg.mSetEnabled = newState;
15122            } else {
15123                // We're dealing with a component level state change
15124                // First, verify that this is a valid class name.
15125                PackageParser.Package pkg = pkgSetting.pkg;
15126                if (pkg == null || !pkg.hasComponentClassName(className)) {
15127                    if (pkg != null &&
15128                            pkg.applicationInfo.targetSdkVersion >=
15129                                    Build.VERSION_CODES.JELLY_BEAN) {
15130                        throw new IllegalArgumentException("Component class " + className
15131                                + " does not exist in " + packageName);
15132                    } else {
15133                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15134                                + className + " does not exist in " + packageName);
15135                    }
15136                }
15137                switch (newState) {
15138                case COMPONENT_ENABLED_STATE_ENABLED:
15139                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15140                        return;
15141                    }
15142                    break;
15143                case COMPONENT_ENABLED_STATE_DISABLED:
15144                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15145                        return;
15146                    }
15147                    break;
15148                case COMPONENT_ENABLED_STATE_DEFAULT:
15149                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15150                        return;
15151                    }
15152                    break;
15153                default:
15154                    Slog.e(TAG, "Invalid new component state: " + newState);
15155                    return;
15156                }
15157            }
15158            scheduleWritePackageRestrictionsLocked(userId);
15159            components = mPendingBroadcasts.get(userId, packageName);
15160            final boolean newPackage = components == null;
15161            if (newPackage) {
15162                components = new ArrayList<String>();
15163            }
15164            if (!components.contains(componentName)) {
15165                components.add(componentName);
15166            }
15167            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15168                sendNow = true;
15169                // Purge entry from pending broadcast list if another one exists already
15170                // since we are sending one right away.
15171                mPendingBroadcasts.remove(userId, packageName);
15172            } else {
15173                if (newPackage) {
15174                    mPendingBroadcasts.put(userId, packageName, components);
15175                }
15176                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15177                    // Schedule a message
15178                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15179                }
15180            }
15181        }
15182
15183        long callingId = Binder.clearCallingIdentity();
15184        try {
15185            if (sendNow) {
15186                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15187                sendPackageChangedBroadcast(packageName,
15188                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15189            }
15190        } finally {
15191            Binder.restoreCallingIdentity(callingId);
15192        }
15193    }
15194
15195    private void sendPackageChangedBroadcast(String packageName,
15196            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15197        if (DEBUG_INSTALL)
15198            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15199                    + componentNames);
15200        Bundle extras = new Bundle(4);
15201        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15202        String nameList[] = new String[componentNames.size()];
15203        componentNames.toArray(nameList);
15204        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15205        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15206        extras.putInt(Intent.EXTRA_UID, packageUid);
15207        // If this is not reporting a change of the overall package, then only send it
15208        // to registered receivers.  We don't want to launch a swath of apps for every
15209        // little component state change.
15210        final int flags = !componentNames.contains(packageName)
15211                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15212        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15213                new int[] {UserHandle.getUserId(packageUid)});
15214    }
15215
15216    @Override
15217    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15218        if (!sUserManager.exists(userId)) return;
15219        final int uid = Binder.getCallingUid();
15220        final int permission = mContext.checkCallingOrSelfPermission(
15221                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15222        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15223        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15224        // writer
15225        synchronized (mPackages) {
15226            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15227                    allowedByPermission, uid, userId)) {
15228                scheduleWritePackageRestrictionsLocked(userId);
15229            }
15230        }
15231    }
15232
15233    @Override
15234    public String getInstallerPackageName(String packageName) {
15235        // reader
15236        synchronized (mPackages) {
15237            return mSettings.getInstallerPackageNameLPr(packageName);
15238        }
15239    }
15240
15241    @Override
15242    public int getApplicationEnabledSetting(String packageName, int userId) {
15243        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15244        int uid = Binder.getCallingUid();
15245        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15246        // reader
15247        synchronized (mPackages) {
15248            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15249        }
15250    }
15251
15252    @Override
15253    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15254        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15255        int uid = Binder.getCallingUid();
15256        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15257        // reader
15258        synchronized (mPackages) {
15259            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15260        }
15261    }
15262
15263    @Override
15264    public void enterSafeMode() {
15265        enforceSystemOrRoot("Only the system can request entering safe mode");
15266
15267        if (!mSystemReady) {
15268            mSafeMode = true;
15269        }
15270    }
15271
15272    @Override
15273    public void systemReady() {
15274        mSystemReady = true;
15275
15276        // Read the compatibilty setting when the system is ready.
15277        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15278                mContext.getContentResolver(),
15279                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15280        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15281        if (DEBUG_SETTINGS) {
15282            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15283        }
15284
15285        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15286
15287        synchronized (mPackages) {
15288            // Verify that all of the preferred activity components actually
15289            // exist.  It is possible for applications to be updated and at
15290            // that point remove a previously declared activity component that
15291            // had been set as a preferred activity.  We try to clean this up
15292            // the next time we encounter that preferred activity, but it is
15293            // possible for the user flow to never be able to return to that
15294            // situation so here we do a sanity check to make sure we haven't
15295            // left any junk around.
15296            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15297            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15298                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15299                removed.clear();
15300                for (PreferredActivity pa : pir.filterSet()) {
15301                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15302                        removed.add(pa);
15303                    }
15304                }
15305                if (removed.size() > 0) {
15306                    for (int r=0; r<removed.size(); r++) {
15307                        PreferredActivity pa = removed.get(r);
15308                        Slog.w(TAG, "Removing dangling preferred activity: "
15309                                + pa.mPref.mComponent);
15310                        pir.removeFilter(pa);
15311                    }
15312                    mSettings.writePackageRestrictionsLPr(
15313                            mSettings.mPreferredActivities.keyAt(i));
15314                }
15315            }
15316
15317            for (int userId : UserManagerService.getInstance().getUserIds()) {
15318                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15319                    grantPermissionsUserIds = ArrayUtils.appendInt(
15320                            grantPermissionsUserIds, userId);
15321                }
15322            }
15323        }
15324        sUserManager.systemReady();
15325
15326        // If we upgraded grant all default permissions before kicking off.
15327        for (int userId : grantPermissionsUserIds) {
15328            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15329        }
15330
15331        // Kick off any messages waiting for system ready
15332        if (mPostSystemReadyMessages != null) {
15333            for (Message msg : mPostSystemReadyMessages) {
15334                msg.sendToTarget();
15335            }
15336            mPostSystemReadyMessages = null;
15337        }
15338
15339        // Watch for external volumes that come and go over time
15340        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15341        storage.registerListener(mStorageListener);
15342
15343        mInstallerService.systemReady();
15344        mPackageDexOptimizer.systemReady();
15345
15346        MountServiceInternal mountServiceInternal = LocalServices.getService(
15347                MountServiceInternal.class);
15348        mountServiceInternal.addExternalStoragePolicy(
15349                new MountServiceInternal.ExternalStorageMountPolicy() {
15350            @Override
15351            public int getMountMode(int uid, String packageName) {
15352                if (Process.isIsolated(uid)) {
15353                    return Zygote.MOUNT_EXTERNAL_NONE;
15354                }
15355                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15356                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15357                }
15358                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15359                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15360                }
15361                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15362                    return Zygote.MOUNT_EXTERNAL_READ;
15363                }
15364                return Zygote.MOUNT_EXTERNAL_WRITE;
15365            }
15366
15367            @Override
15368            public boolean hasExternalStorage(int uid, String packageName) {
15369                return true;
15370            }
15371        });
15372    }
15373
15374    @Override
15375    public boolean isSafeMode() {
15376        return mSafeMode;
15377    }
15378
15379    @Override
15380    public boolean hasSystemUidErrors() {
15381        return mHasSystemUidErrors;
15382    }
15383
15384    static String arrayToString(int[] array) {
15385        StringBuffer buf = new StringBuffer(128);
15386        buf.append('[');
15387        if (array != null) {
15388            for (int i=0; i<array.length; i++) {
15389                if (i > 0) buf.append(", ");
15390                buf.append(array[i]);
15391            }
15392        }
15393        buf.append(']');
15394        return buf.toString();
15395    }
15396
15397    static class DumpState {
15398        public static final int DUMP_LIBS = 1 << 0;
15399        public static final int DUMP_FEATURES = 1 << 1;
15400        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15401        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15402        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15403        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15404        public static final int DUMP_PERMISSIONS = 1 << 6;
15405        public static final int DUMP_PACKAGES = 1 << 7;
15406        public static final int DUMP_SHARED_USERS = 1 << 8;
15407        public static final int DUMP_MESSAGES = 1 << 9;
15408        public static final int DUMP_PROVIDERS = 1 << 10;
15409        public static final int DUMP_VERIFIERS = 1 << 11;
15410        public static final int DUMP_PREFERRED = 1 << 12;
15411        public static final int DUMP_PREFERRED_XML = 1 << 13;
15412        public static final int DUMP_KEYSETS = 1 << 14;
15413        public static final int DUMP_VERSION = 1 << 15;
15414        public static final int DUMP_INSTALLS = 1 << 16;
15415        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15416        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15417
15418        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15419
15420        private int mTypes;
15421
15422        private int mOptions;
15423
15424        private boolean mTitlePrinted;
15425
15426        private SharedUserSetting mSharedUser;
15427
15428        public boolean isDumping(int type) {
15429            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15430                return true;
15431            }
15432
15433            return (mTypes & type) != 0;
15434        }
15435
15436        public void setDump(int type) {
15437            mTypes |= type;
15438        }
15439
15440        public boolean isOptionEnabled(int option) {
15441            return (mOptions & option) != 0;
15442        }
15443
15444        public void setOptionEnabled(int option) {
15445            mOptions |= option;
15446        }
15447
15448        public boolean onTitlePrinted() {
15449            final boolean printed = mTitlePrinted;
15450            mTitlePrinted = true;
15451            return printed;
15452        }
15453
15454        public boolean getTitlePrinted() {
15455            return mTitlePrinted;
15456        }
15457
15458        public void setTitlePrinted(boolean enabled) {
15459            mTitlePrinted = enabled;
15460        }
15461
15462        public SharedUserSetting getSharedUser() {
15463            return mSharedUser;
15464        }
15465
15466        public void setSharedUser(SharedUserSetting user) {
15467            mSharedUser = user;
15468        }
15469    }
15470
15471    @Override
15472    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15473            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15474        (new PackageManagerShellCommand(this)).exec(
15475                this, in, out, err, args, resultReceiver);
15476    }
15477
15478    @Override
15479    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15480        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15481                != PackageManager.PERMISSION_GRANTED) {
15482            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15483                    + Binder.getCallingPid()
15484                    + ", uid=" + Binder.getCallingUid()
15485                    + " without permission "
15486                    + android.Manifest.permission.DUMP);
15487            return;
15488        }
15489
15490        DumpState dumpState = new DumpState();
15491        boolean fullPreferred = false;
15492        boolean checkin = false;
15493
15494        String packageName = null;
15495        ArraySet<String> permissionNames = null;
15496
15497        int opti = 0;
15498        while (opti < args.length) {
15499            String opt = args[opti];
15500            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15501                break;
15502            }
15503            opti++;
15504
15505            if ("-a".equals(opt)) {
15506                // Right now we only know how to print all.
15507            } else if ("-h".equals(opt)) {
15508                pw.println("Package manager dump options:");
15509                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15510                pw.println("    --checkin: dump for a checkin");
15511                pw.println("    -f: print details of intent filters");
15512                pw.println("    -h: print this help");
15513                pw.println("  cmd may be one of:");
15514                pw.println("    l[ibraries]: list known shared libraries");
15515                pw.println("    f[eatures]: list device features");
15516                pw.println("    k[eysets]: print known keysets");
15517                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15518                pw.println("    perm[issions]: dump permissions");
15519                pw.println("    permission [name ...]: dump declaration and use of given permission");
15520                pw.println("    pref[erred]: print preferred package settings");
15521                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15522                pw.println("    prov[iders]: dump content providers");
15523                pw.println("    p[ackages]: dump installed packages");
15524                pw.println("    s[hared-users]: dump shared user IDs");
15525                pw.println("    m[essages]: print collected runtime messages");
15526                pw.println("    v[erifiers]: print package verifier info");
15527                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15528                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15529                pw.println("    version: print database version info");
15530                pw.println("    write: write current settings now");
15531                pw.println("    installs: details about install sessions");
15532                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15533                pw.println("    <package.name>: info about given package");
15534                return;
15535            } else if ("--checkin".equals(opt)) {
15536                checkin = true;
15537            } else if ("-f".equals(opt)) {
15538                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15539            } else {
15540                pw.println("Unknown argument: " + opt + "; use -h for help");
15541            }
15542        }
15543
15544        // Is the caller requesting to dump a particular piece of data?
15545        if (opti < args.length) {
15546            String cmd = args[opti];
15547            opti++;
15548            // Is this a package name?
15549            if ("android".equals(cmd) || cmd.contains(".")) {
15550                packageName = cmd;
15551                // When dumping a single package, we always dump all of its
15552                // filter information since the amount of data will be reasonable.
15553                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15554            } else if ("check-permission".equals(cmd)) {
15555                if (opti >= args.length) {
15556                    pw.println("Error: check-permission missing permission argument");
15557                    return;
15558                }
15559                String perm = args[opti];
15560                opti++;
15561                if (opti >= args.length) {
15562                    pw.println("Error: check-permission missing package argument");
15563                    return;
15564                }
15565                String pkg = args[opti];
15566                opti++;
15567                int user = UserHandle.getUserId(Binder.getCallingUid());
15568                if (opti < args.length) {
15569                    try {
15570                        user = Integer.parseInt(args[opti]);
15571                    } catch (NumberFormatException e) {
15572                        pw.println("Error: check-permission user argument is not a number: "
15573                                + args[opti]);
15574                        return;
15575                    }
15576                }
15577                pw.println(checkPermission(perm, pkg, user));
15578                return;
15579            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15580                dumpState.setDump(DumpState.DUMP_LIBS);
15581            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15582                dumpState.setDump(DumpState.DUMP_FEATURES);
15583            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15584                if (opti >= args.length) {
15585                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15586                            | DumpState.DUMP_SERVICE_RESOLVERS
15587                            | DumpState.DUMP_RECEIVER_RESOLVERS
15588                            | DumpState.DUMP_CONTENT_RESOLVERS);
15589                } else {
15590                    while (opti < args.length) {
15591                        String name = args[opti];
15592                        if ("a".equals(name) || "activity".equals(name)) {
15593                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15594                        } else if ("s".equals(name) || "service".equals(name)) {
15595                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15596                        } else if ("r".equals(name) || "receiver".equals(name)) {
15597                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15598                        } else if ("c".equals(name) || "content".equals(name)) {
15599                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15600                        } else {
15601                            pw.println("Error: unknown resolver table type: " + name);
15602                            return;
15603                        }
15604                        opti++;
15605                    }
15606                }
15607            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15608                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15609            } else if ("permission".equals(cmd)) {
15610                if (opti >= args.length) {
15611                    pw.println("Error: permission requires permission name");
15612                    return;
15613                }
15614                permissionNames = new ArraySet<>();
15615                while (opti < args.length) {
15616                    permissionNames.add(args[opti]);
15617                    opti++;
15618                }
15619                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15620                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15621            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15622                dumpState.setDump(DumpState.DUMP_PREFERRED);
15623            } else if ("preferred-xml".equals(cmd)) {
15624                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15625                if (opti < args.length && "--full".equals(args[opti])) {
15626                    fullPreferred = true;
15627                    opti++;
15628                }
15629            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15630                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15631            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15632                dumpState.setDump(DumpState.DUMP_PACKAGES);
15633            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15634                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15635            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15636                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15637            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15638                dumpState.setDump(DumpState.DUMP_MESSAGES);
15639            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15640                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15641            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15642                    || "intent-filter-verifiers".equals(cmd)) {
15643                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15644            } else if ("version".equals(cmd)) {
15645                dumpState.setDump(DumpState.DUMP_VERSION);
15646            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15647                dumpState.setDump(DumpState.DUMP_KEYSETS);
15648            } else if ("installs".equals(cmd)) {
15649                dumpState.setDump(DumpState.DUMP_INSTALLS);
15650            } else if ("write".equals(cmd)) {
15651                synchronized (mPackages) {
15652                    mSettings.writeLPr();
15653                    pw.println("Settings written.");
15654                    return;
15655                }
15656            }
15657        }
15658
15659        if (checkin) {
15660            pw.println("vers,1");
15661        }
15662
15663        // reader
15664        synchronized (mPackages) {
15665            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15666                if (!checkin) {
15667                    if (dumpState.onTitlePrinted())
15668                        pw.println();
15669                    pw.println("Database versions:");
15670                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15671                }
15672            }
15673
15674            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15675                if (!checkin) {
15676                    if (dumpState.onTitlePrinted())
15677                        pw.println();
15678                    pw.println("Verifiers:");
15679                    pw.print("  Required: ");
15680                    pw.print(mRequiredVerifierPackage);
15681                    pw.print(" (uid=");
15682                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15683                    pw.println(")");
15684                } else if (mRequiredVerifierPackage != null) {
15685                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15686                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15687                }
15688            }
15689
15690            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15691                    packageName == null) {
15692                if (mIntentFilterVerifierComponent != null) {
15693                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15694                    if (!checkin) {
15695                        if (dumpState.onTitlePrinted())
15696                            pw.println();
15697                        pw.println("Intent Filter Verifier:");
15698                        pw.print("  Using: ");
15699                        pw.print(verifierPackageName);
15700                        pw.print(" (uid=");
15701                        pw.print(getPackageUid(verifierPackageName, 0));
15702                        pw.println(")");
15703                    } else if (verifierPackageName != null) {
15704                        pw.print("ifv,"); pw.print(verifierPackageName);
15705                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15706                    }
15707                } else {
15708                    pw.println();
15709                    pw.println("No Intent Filter Verifier available!");
15710                }
15711            }
15712
15713            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15714                boolean printedHeader = false;
15715                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15716                while (it.hasNext()) {
15717                    String name = it.next();
15718                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15719                    if (!checkin) {
15720                        if (!printedHeader) {
15721                            if (dumpState.onTitlePrinted())
15722                                pw.println();
15723                            pw.println("Libraries:");
15724                            printedHeader = true;
15725                        }
15726                        pw.print("  ");
15727                    } else {
15728                        pw.print("lib,");
15729                    }
15730                    pw.print(name);
15731                    if (!checkin) {
15732                        pw.print(" -> ");
15733                    }
15734                    if (ent.path != null) {
15735                        if (!checkin) {
15736                            pw.print("(jar) ");
15737                            pw.print(ent.path);
15738                        } else {
15739                            pw.print(",jar,");
15740                            pw.print(ent.path);
15741                        }
15742                    } else {
15743                        if (!checkin) {
15744                            pw.print("(apk) ");
15745                            pw.print(ent.apk);
15746                        } else {
15747                            pw.print(",apk,");
15748                            pw.print(ent.apk);
15749                        }
15750                    }
15751                    pw.println();
15752                }
15753            }
15754
15755            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15756                if (dumpState.onTitlePrinted())
15757                    pw.println();
15758                if (!checkin) {
15759                    pw.println("Features:");
15760                }
15761                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15762                while (it.hasNext()) {
15763                    String name = it.next();
15764                    if (!checkin) {
15765                        pw.print("  ");
15766                    } else {
15767                        pw.print("feat,");
15768                    }
15769                    pw.println(name);
15770                }
15771            }
15772
15773            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15774                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15775                        : "Activity Resolver Table:", "  ", packageName,
15776                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15777                    dumpState.setTitlePrinted(true);
15778                }
15779            }
15780            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15781                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15782                        : "Receiver Resolver Table:", "  ", packageName,
15783                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15784                    dumpState.setTitlePrinted(true);
15785                }
15786            }
15787            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15788                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15789                        : "Service Resolver Table:", "  ", packageName,
15790                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15791                    dumpState.setTitlePrinted(true);
15792                }
15793            }
15794            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15795                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15796                        : "Provider Resolver Table:", "  ", packageName,
15797                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15798                    dumpState.setTitlePrinted(true);
15799                }
15800            }
15801
15802            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15803                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15804                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15805                    int user = mSettings.mPreferredActivities.keyAt(i);
15806                    if (pir.dump(pw,
15807                            dumpState.getTitlePrinted()
15808                                ? "\nPreferred Activities User " + user + ":"
15809                                : "Preferred Activities User " + user + ":", "  ",
15810                            packageName, true, false)) {
15811                        dumpState.setTitlePrinted(true);
15812                    }
15813                }
15814            }
15815
15816            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15817                pw.flush();
15818                FileOutputStream fout = new FileOutputStream(fd);
15819                BufferedOutputStream str = new BufferedOutputStream(fout);
15820                XmlSerializer serializer = new FastXmlSerializer();
15821                try {
15822                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15823                    serializer.startDocument(null, true);
15824                    serializer.setFeature(
15825                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15826                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15827                    serializer.endDocument();
15828                    serializer.flush();
15829                } catch (IllegalArgumentException e) {
15830                    pw.println("Failed writing: " + e);
15831                } catch (IllegalStateException e) {
15832                    pw.println("Failed writing: " + e);
15833                } catch (IOException e) {
15834                    pw.println("Failed writing: " + e);
15835                }
15836            }
15837
15838            if (!checkin
15839                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15840                    && packageName == null) {
15841                pw.println();
15842                int count = mSettings.mPackages.size();
15843                if (count == 0) {
15844                    pw.println("No applications!");
15845                    pw.println();
15846                } else {
15847                    final String prefix = "  ";
15848                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15849                    if (allPackageSettings.size() == 0) {
15850                        pw.println("No domain preferred apps!");
15851                        pw.println();
15852                    } else {
15853                        pw.println("App verification status:");
15854                        pw.println();
15855                        count = 0;
15856                        for (PackageSetting ps : allPackageSettings) {
15857                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15858                            if (ivi == null || ivi.getPackageName() == null) continue;
15859                            pw.println(prefix + "Package: " + ivi.getPackageName());
15860                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15861                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15862                            pw.println();
15863                            count++;
15864                        }
15865                        if (count == 0) {
15866                            pw.println(prefix + "No app verification established.");
15867                            pw.println();
15868                        }
15869                        for (int userId : sUserManager.getUserIds()) {
15870                            pw.println("App linkages for user " + userId + ":");
15871                            pw.println();
15872                            count = 0;
15873                            for (PackageSetting ps : allPackageSettings) {
15874                                final long status = ps.getDomainVerificationStatusForUser(userId);
15875                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15876                                    continue;
15877                                }
15878                                pw.println(prefix + "Package: " + ps.name);
15879                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15880                                String statusStr = IntentFilterVerificationInfo.
15881                                        getStatusStringFromValue(status);
15882                                pw.println(prefix + "Status:  " + statusStr);
15883                                pw.println();
15884                                count++;
15885                            }
15886                            if (count == 0) {
15887                                pw.println(prefix + "No configured app linkages.");
15888                                pw.println();
15889                            }
15890                        }
15891                    }
15892                }
15893            }
15894
15895            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15896                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15897                if (packageName == null && permissionNames == null) {
15898                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15899                        if (iperm == 0) {
15900                            if (dumpState.onTitlePrinted())
15901                                pw.println();
15902                            pw.println("AppOp Permissions:");
15903                        }
15904                        pw.print("  AppOp Permission ");
15905                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15906                        pw.println(":");
15907                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15908                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15909                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15910                        }
15911                    }
15912                }
15913            }
15914
15915            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15916                boolean printedSomething = false;
15917                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15918                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15919                        continue;
15920                    }
15921                    if (!printedSomething) {
15922                        if (dumpState.onTitlePrinted())
15923                            pw.println();
15924                        pw.println("Registered ContentProviders:");
15925                        printedSomething = true;
15926                    }
15927                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15928                    pw.print("    "); pw.println(p.toString());
15929                }
15930                printedSomething = false;
15931                for (Map.Entry<String, PackageParser.Provider> entry :
15932                        mProvidersByAuthority.entrySet()) {
15933                    PackageParser.Provider p = entry.getValue();
15934                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15935                        continue;
15936                    }
15937                    if (!printedSomething) {
15938                        if (dumpState.onTitlePrinted())
15939                            pw.println();
15940                        pw.println("ContentProvider Authorities:");
15941                        printedSomething = true;
15942                    }
15943                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15944                    pw.print("    "); pw.println(p.toString());
15945                    if (p.info != null && p.info.applicationInfo != null) {
15946                        final String appInfo = p.info.applicationInfo.toString();
15947                        pw.print("      applicationInfo="); pw.println(appInfo);
15948                    }
15949                }
15950            }
15951
15952            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15953                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15954            }
15955
15956            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15957                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15958            }
15959
15960            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15961                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15962            }
15963
15964            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15965                // XXX should handle packageName != null by dumping only install data that
15966                // the given package is involved with.
15967                if (dumpState.onTitlePrinted()) pw.println();
15968                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15969            }
15970
15971            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15972                if (dumpState.onTitlePrinted()) pw.println();
15973                mSettings.dumpReadMessagesLPr(pw, dumpState);
15974
15975                pw.println();
15976                pw.println("Package warning messages:");
15977                BufferedReader in = null;
15978                String line = null;
15979                try {
15980                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15981                    while ((line = in.readLine()) != null) {
15982                        if (line.contains("ignored: updated version")) continue;
15983                        pw.println(line);
15984                    }
15985                } catch (IOException ignored) {
15986                } finally {
15987                    IoUtils.closeQuietly(in);
15988                }
15989            }
15990
15991            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15992                BufferedReader in = null;
15993                String line = null;
15994                try {
15995                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15996                    while ((line = in.readLine()) != null) {
15997                        if (line.contains("ignored: updated version")) continue;
15998                        pw.print("msg,");
15999                        pw.println(line);
16000                    }
16001                } catch (IOException ignored) {
16002                } finally {
16003                    IoUtils.closeQuietly(in);
16004                }
16005            }
16006        }
16007    }
16008
16009    private String dumpDomainString(String packageName) {
16010        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16011        List<IntentFilter> filters = getAllIntentFilters(packageName);
16012
16013        ArraySet<String> result = new ArraySet<>();
16014        if (iviList.size() > 0) {
16015            for (IntentFilterVerificationInfo ivi : iviList) {
16016                for (String host : ivi.getDomains()) {
16017                    result.add(host);
16018                }
16019            }
16020        }
16021        if (filters != null && filters.size() > 0) {
16022            for (IntentFilter filter : filters) {
16023                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16024                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16025                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16026                    result.addAll(filter.getHostsList());
16027                }
16028            }
16029        }
16030
16031        StringBuilder sb = new StringBuilder(result.size() * 16);
16032        for (String domain : result) {
16033            if (sb.length() > 0) sb.append(" ");
16034            sb.append(domain);
16035        }
16036        return sb.toString();
16037    }
16038
16039    // ------- apps on sdcard specific code -------
16040    static final boolean DEBUG_SD_INSTALL = false;
16041
16042    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16043
16044    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16045
16046    private boolean mMediaMounted = false;
16047
16048    static String getEncryptKey() {
16049        try {
16050            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16051                    SD_ENCRYPTION_KEYSTORE_NAME);
16052            if (sdEncKey == null) {
16053                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16054                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16055                if (sdEncKey == null) {
16056                    Slog.e(TAG, "Failed to create encryption keys");
16057                    return null;
16058                }
16059            }
16060            return sdEncKey;
16061        } catch (NoSuchAlgorithmException nsae) {
16062            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16063            return null;
16064        } catch (IOException ioe) {
16065            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16066            return null;
16067        }
16068    }
16069
16070    /*
16071     * Update media status on PackageManager.
16072     */
16073    @Override
16074    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16075        int callingUid = Binder.getCallingUid();
16076        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16077            throw new SecurityException("Media status can only be updated by the system");
16078        }
16079        // reader; this apparently protects mMediaMounted, but should probably
16080        // be a different lock in that case.
16081        synchronized (mPackages) {
16082            Log.i(TAG, "Updating external media status from "
16083                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16084                    + (mediaStatus ? "mounted" : "unmounted"));
16085            if (DEBUG_SD_INSTALL)
16086                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16087                        + ", mMediaMounted=" + mMediaMounted);
16088            if (mediaStatus == mMediaMounted) {
16089                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16090                        : 0, -1);
16091                mHandler.sendMessage(msg);
16092                return;
16093            }
16094            mMediaMounted = mediaStatus;
16095        }
16096        // Queue up an async operation since the package installation may take a
16097        // little while.
16098        mHandler.post(new Runnable() {
16099            public void run() {
16100                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16101            }
16102        });
16103    }
16104
16105    /**
16106     * Called by MountService when the initial ASECs to scan are available.
16107     * Should block until all the ASEC containers are finished being scanned.
16108     */
16109    public void scanAvailableAsecs() {
16110        updateExternalMediaStatusInner(true, false, false);
16111        if (mShouldRestoreconData) {
16112            SELinuxMMAC.setRestoreconDone();
16113            mShouldRestoreconData = false;
16114        }
16115    }
16116
16117    /*
16118     * Collect information of applications on external media, map them against
16119     * existing containers and update information based on current mount status.
16120     * Please note that we always have to report status if reportStatus has been
16121     * set to true especially when unloading packages.
16122     */
16123    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16124            boolean externalStorage) {
16125        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16126        int[] uidArr = EmptyArray.INT;
16127
16128        final String[] list = PackageHelper.getSecureContainerList();
16129        if (ArrayUtils.isEmpty(list)) {
16130            Log.i(TAG, "No secure containers found");
16131        } else {
16132            // Process list of secure containers and categorize them
16133            // as active or stale based on their package internal state.
16134
16135            // reader
16136            synchronized (mPackages) {
16137                for (String cid : list) {
16138                    // Leave stages untouched for now; installer service owns them
16139                    if (PackageInstallerService.isStageName(cid)) continue;
16140
16141                    if (DEBUG_SD_INSTALL)
16142                        Log.i(TAG, "Processing container " + cid);
16143                    String pkgName = getAsecPackageName(cid);
16144                    if (pkgName == null) {
16145                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16146                        continue;
16147                    }
16148                    if (DEBUG_SD_INSTALL)
16149                        Log.i(TAG, "Looking for pkg : " + pkgName);
16150
16151                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16152                    if (ps == null) {
16153                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16154                        continue;
16155                    }
16156
16157                    /*
16158                     * Skip packages that are not external if we're unmounting
16159                     * external storage.
16160                     */
16161                    if (externalStorage && !isMounted && !isExternal(ps)) {
16162                        continue;
16163                    }
16164
16165                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16166                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16167                    // The package status is changed only if the code path
16168                    // matches between settings and the container id.
16169                    if (ps.codePathString != null
16170                            && ps.codePathString.startsWith(args.getCodePath())) {
16171                        if (DEBUG_SD_INSTALL) {
16172                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16173                                    + " at code path: " + ps.codePathString);
16174                        }
16175
16176                        // We do have a valid package installed on sdcard
16177                        processCids.put(args, ps.codePathString);
16178                        final int uid = ps.appId;
16179                        if (uid != -1) {
16180                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16181                        }
16182                    } else {
16183                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16184                                + ps.codePathString);
16185                    }
16186                }
16187            }
16188
16189            Arrays.sort(uidArr);
16190        }
16191
16192        // Process packages with valid entries.
16193        if (isMounted) {
16194            if (DEBUG_SD_INSTALL)
16195                Log.i(TAG, "Loading packages");
16196            loadMediaPackages(processCids, uidArr, externalStorage);
16197            startCleaningPackages();
16198            mInstallerService.onSecureContainersAvailable();
16199        } else {
16200            if (DEBUG_SD_INSTALL)
16201                Log.i(TAG, "Unloading packages");
16202            unloadMediaPackages(processCids, uidArr, reportStatus);
16203        }
16204    }
16205
16206    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16207            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16208        final int size = infos.size();
16209        final String[] packageNames = new String[size];
16210        final int[] packageUids = new int[size];
16211        for (int i = 0; i < size; i++) {
16212            final ApplicationInfo info = infos.get(i);
16213            packageNames[i] = info.packageName;
16214            packageUids[i] = info.uid;
16215        }
16216        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16217                finishedReceiver);
16218    }
16219
16220    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16221            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16222        sendResourcesChangedBroadcast(mediaStatus, replacing,
16223                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16224    }
16225
16226    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16227            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16228        int size = pkgList.length;
16229        if (size > 0) {
16230            // Send broadcasts here
16231            Bundle extras = new Bundle();
16232            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16233            if (uidArr != null) {
16234                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16235            }
16236            if (replacing) {
16237                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16238            }
16239            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16240                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16241            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16242        }
16243    }
16244
16245   /*
16246     * Look at potentially valid container ids from processCids If package
16247     * information doesn't match the one on record or package scanning fails,
16248     * the cid is added to list of removeCids. We currently don't delete stale
16249     * containers.
16250     */
16251    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16252            boolean externalStorage) {
16253        ArrayList<String> pkgList = new ArrayList<String>();
16254        Set<AsecInstallArgs> keys = processCids.keySet();
16255
16256        for (AsecInstallArgs args : keys) {
16257            String codePath = processCids.get(args);
16258            if (DEBUG_SD_INSTALL)
16259                Log.i(TAG, "Loading container : " + args.cid);
16260            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16261            try {
16262                // Make sure there are no container errors first.
16263                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16264                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16265                            + " when installing from sdcard");
16266                    continue;
16267                }
16268                // Check code path here.
16269                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16270                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16271                            + " does not match one in settings " + codePath);
16272                    continue;
16273                }
16274                // Parse package
16275                int parseFlags = mDefParseFlags;
16276                if (args.isExternalAsec()) {
16277                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16278                }
16279                if (args.isFwdLocked()) {
16280                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16281                }
16282
16283                synchronized (mInstallLock) {
16284                    PackageParser.Package pkg = null;
16285                    try {
16286                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16287                    } catch (PackageManagerException e) {
16288                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16289                    }
16290                    // Scan the package
16291                    if (pkg != null) {
16292                        /*
16293                         * TODO why is the lock being held? doPostInstall is
16294                         * called in other places without the lock. This needs
16295                         * to be straightened out.
16296                         */
16297                        // writer
16298                        synchronized (mPackages) {
16299                            retCode = PackageManager.INSTALL_SUCCEEDED;
16300                            pkgList.add(pkg.packageName);
16301                            // Post process args
16302                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16303                                    pkg.applicationInfo.uid);
16304                        }
16305                    } else {
16306                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16307                    }
16308                }
16309
16310            } finally {
16311                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16312                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16313                }
16314            }
16315        }
16316        // writer
16317        synchronized (mPackages) {
16318            // If the platform SDK has changed since the last time we booted,
16319            // we need to re-grant app permission to catch any new ones that
16320            // appear. This is really a hack, and means that apps can in some
16321            // cases get permissions that the user didn't initially explicitly
16322            // allow... it would be nice to have some better way to handle
16323            // this situation.
16324            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16325                    : mSettings.getInternalVersion();
16326            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16327                    : StorageManager.UUID_PRIVATE_INTERNAL;
16328
16329            int updateFlags = UPDATE_PERMISSIONS_ALL;
16330            if (ver.sdkVersion != mSdkVersion) {
16331                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16332                        + mSdkVersion + "; regranting permissions for external");
16333                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16334            }
16335            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16336
16337            // Yay, everything is now upgraded
16338            ver.forceCurrent();
16339
16340            // can downgrade to reader
16341            // Persist settings
16342            mSettings.writeLPr();
16343        }
16344        // Send a broadcast to let everyone know we are done processing
16345        if (pkgList.size() > 0) {
16346            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16347        }
16348    }
16349
16350   /*
16351     * Utility method to unload a list of specified containers
16352     */
16353    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16354        // Just unmount all valid containers.
16355        for (AsecInstallArgs arg : cidArgs) {
16356            synchronized (mInstallLock) {
16357                arg.doPostDeleteLI(false);
16358           }
16359       }
16360   }
16361
16362    /*
16363     * Unload packages mounted on external media. This involves deleting package
16364     * data from internal structures, sending broadcasts about diabled packages,
16365     * gc'ing to free up references, unmounting all secure containers
16366     * corresponding to packages on external media, and posting a
16367     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16368     * that we always have to post this message if status has been requested no
16369     * matter what.
16370     */
16371    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16372            final boolean reportStatus) {
16373        if (DEBUG_SD_INSTALL)
16374            Log.i(TAG, "unloading media packages");
16375        ArrayList<String> pkgList = new ArrayList<String>();
16376        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16377        final Set<AsecInstallArgs> keys = processCids.keySet();
16378        for (AsecInstallArgs args : keys) {
16379            String pkgName = args.getPackageName();
16380            if (DEBUG_SD_INSTALL)
16381                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16382            // Delete package internally
16383            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16384            synchronized (mInstallLock) {
16385                boolean res = deletePackageLI(pkgName, null, false, null, null,
16386                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16387                if (res) {
16388                    pkgList.add(pkgName);
16389                } else {
16390                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16391                    failedList.add(args);
16392                }
16393            }
16394        }
16395
16396        // reader
16397        synchronized (mPackages) {
16398            // We didn't update the settings after removing each package;
16399            // write them now for all packages.
16400            mSettings.writeLPr();
16401        }
16402
16403        // We have to absolutely send UPDATED_MEDIA_STATUS only
16404        // after confirming that all the receivers processed the ordered
16405        // broadcast when packages get disabled, force a gc to clean things up.
16406        // and unload all the containers.
16407        if (pkgList.size() > 0) {
16408            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16409                    new IIntentReceiver.Stub() {
16410                public void performReceive(Intent intent, int resultCode, String data,
16411                        Bundle extras, boolean ordered, boolean sticky,
16412                        int sendingUser) throws RemoteException {
16413                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16414                            reportStatus ? 1 : 0, 1, keys);
16415                    mHandler.sendMessage(msg);
16416                }
16417            });
16418        } else {
16419            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16420                    keys);
16421            mHandler.sendMessage(msg);
16422        }
16423    }
16424
16425    private void loadPrivatePackages(final VolumeInfo vol) {
16426        mHandler.post(new Runnable() {
16427            @Override
16428            public void run() {
16429                loadPrivatePackagesInner(vol);
16430            }
16431        });
16432    }
16433
16434    private void loadPrivatePackagesInner(VolumeInfo vol) {
16435        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16436        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16437
16438        final VersionInfo ver;
16439        final List<PackageSetting> packages;
16440        synchronized (mPackages) {
16441            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16442            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16443        }
16444
16445        for (PackageSetting ps : packages) {
16446            synchronized (mInstallLock) {
16447                final PackageParser.Package pkg;
16448                try {
16449                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16450                    loaded.add(pkg.applicationInfo);
16451                } catch (PackageManagerException e) {
16452                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16453                }
16454
16455                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16456                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16457                }
16458            }
16459        }
16460
16461        synchronized (mPackages) {
16462            int updateFlags = UPDATE_PERMISSIONS_ALL;
16463            if (ver.sdkVersion != mSdkVersion) {
16464                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16465                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16466                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16467            }
16468            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16469
16470            // Yay, everything is now upgraded
16471            ver.forceCurrent();
16472
16473            mSettings.writeLPr();
16474        }
16475
16476        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16477        sendResourcesChangedBroadcast(true, false, loaded, null);
16478    }
16479
16480    private void unloadPrivatePackages(final VolumeInfo vol) {
16481        mHandler.post(new Runnable() {
16482            @Override
16483            public void run() {
16484                unloadPrivatePackagesInner(vol);
16485            }
16486        });
16487    }
16488
16489    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16490        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16491        synchronized (mInstallLock) {
16492        synchronized (mPackages) {
16493            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16494            for (PackageSetting ps : packages) {
16495                if (ps.pkg == null) continue;
16496
16497                final ApplicationInfo info = ps.pkg.applicationInfo;
16498                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16499                if (deletePackageLI(ps.name, null, false, null, null,
16500                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16501                    unloaded.add(info);
16502                } else {
16503                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16504                }
16505            }
16506
16507            mSettings.writeLPr();
16508        }
16509        }
16510
16511        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16512        sendResourcesChangedBroadcast(false, false, unloaded, null);
16513    }
16514
16515    /**
16516     * Examine all users present on given mounted volume, and destroy data
16517     * belonging to users that are no longer valid, or whose user ID has been
16518     * recycled.
16519     */
16520    private void reconcileUsers(String volumeUuid) {
16521        final File[] files = FileUtils
16522                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16523        for (File file : files) {
16524            if (!file.isDirectory()) continue;
16525
16526            final int userId;
16527            final UserInfo info;
16528            try {
16529                userId = Integer.parseInt(file.getName());
16530                info = sUserManager.getUserInfo(userId);
16531            } catch (NumberFormatException e) {
16532                Slog.w(TAG, "Invalid user directory " + file);
16533                continue;
16534            }
16535
16536            boolean destroyUser = false;
16537            if (info == null) {
16538                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16539                        + " because no matching user was found");
16540                destroyUser = true;
16541            } else {
16542                try {
16543                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16544                } catch (IOException e) {
16545                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16546                            + " because we failed to enforce serial number: " + e);
16547                    destroyUser = true;
16548                }
16549            }
16550
16551            if (destroyUser) {
16552                synchronized (mInstallLock) {
16553                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16554                }
16555            }
16556        }
16557
16558        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16559        final UserManager um = mContext.getSystemService(UserManager.class);
16560        for (UserInfo user : um.getUsers()) {
16561            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16562            if (userDir.exists()) continue;
16563
16564            try {
16565                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16566                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16567            } catch (IOException e) {
16568                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16569            }
16570        }
16571    }
16572
16573    /**
16574     * Examine all apps present on given mounted volume, and destroy apps that
16575     * aren't expected, either due to uninstallation or reinstallation on
16576     * another volume.
16577     */
16578    private void reconcileApps(String volumeUuid) {
16579        final File[] files = FileUtils
16580                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16581        for (File file : files) {
16582            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16583                    && !PackageInstallerService.isStageName(file.getName());
16584            if (!isPackage) {
16585                // Ignore entries which are not packages
16586                continue;
16587            }
16588
16589            boolean destroyApp = false;
16590            String packageName = null;
16591            try {
16592                final PackageLite pkg = PackageParser.parsePackageLite(file,
16593                        PackageParser.PARSE_MUST_BE_APK);
16594                packageName = pkg.packageName;
16595
16596                synchronized (mPackages) {
16597                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16598                    if (ps == null) {
16599                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16600                                + volumeUuid + " because we found no install record");
16601                        destroyApp = true;
16602                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16603                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16604                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16605                        destroyApp = true;
16606                    }
16607                }
16608
16609            } catch (PackageParserException e) {
16610                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16611                destroyApp = true;
16612            }
16613
16614            if (destroyApp) {
16615                synchronized (mInstallLock) {
16616                    if (packageName != null) {
16617                        removeDataDirsLI(volumeUuid, packageName);
16618                    }
16619                    if (file.isDirectory()) {
16620                        mInstaller.rmPackageDir(file.getAbsolutePath());
16621                    } else {
16622                        file.delete();
16623                    }
16624                }
16625            }
16626        }
16627    }
16628
16629    private void unfreezePackage(String packageName) {
16630        synchronized (mPackages) {
16631            final PackageSetting ps = mSettings.mPackages.get(packageName);
16632            if (ps != null) {
16633                ps.frozen = false;
16634            }
16635        }
16636    }
16637
16638    @Override
16639    public int movePackage(final String packageName, final String volumeUuid) {
16640        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16641
16642        final int moveId = mNextMoveId.getAndIncrement();
16643        mHandler.post(new Runnable() {
16644            @Override
16645            public void run() {
16646                try {
16647                    movePackageInternal(packageName, volumeUuid, moveId);
16648                } catch (PackageManagerException e) {
16649                    Slog.w(TAG, "Failed to move " + packageName, e);
16650                    mMoveCallbacks.notifyStatusChanged(moveId,
16651                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16652                }
16653            }
16654        });
16655        return moveId;
16656    }
16657
16658    private void movePackageInternal(final String packageName, final String volumeUuid,
16659            final int moveId) throws PackageManagerException {
16660        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16661        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16662        final PackageManager pm = mContext.getPackageManager();
16663
16664        final boolean currentAsec;
16665        final String currentVolumeUuid;
16666        final File codeFile;
16667        final String installerPackageName;
16668        final String packageAbiOverride;
16669        final int appId;
16670        final String seinfo;
16671        final String label;
16672
16673        // reader
16674        synchronized (mPackages) {
16675            final PackageParser.Package pkg = mPackages.get(packageName);
16676            final PackageSetting ps = mSettings.mPackages.get(packageName);
16677            if (pkg == null || ps == null) {
16678                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16679            }
16680
16681            if (pkg.applicationInfo.isSystemApp()) {
16682                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16683                        "Cannot move system application");
16684            }
16685
16686            if (pkg.applicationInfo.isExternalAsec()) {
16687                currentAsec = true;
16688                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16689            } else if (pkg.applicationInfo.isForwardLocked()) {
16690                currentAsec = true;
16691                currentVolumeUuid = "forward_locked";
16692            } else {
16693                currentAsec = false;
16694                currentVolumeUuid = ps.volumeUuid;
16695
16696                final File probe = new File(pkg.codePath);
16697                final File probeOat = new File(probe, "oat");
16698                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16699                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16700                            "Move only supported for modern cluster style installs");
16701                }
16702            }
16703
16704            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16705                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16706                        "Package already moved to " + volumeUuid);
16707            }
16708
16709            if (ps.frozen) {
16710                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16711                        "Failed to move already frozen package");
16712            }
16713            ps.frozen = true;
16714
16715            codeFile = new File(pkg.codePath);
16716            installerPackageName = ps.installerPackageName;
16717            packageAbiOverride = ps.cpuAbiOverrideString;
16718            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16719            seinfo = pkg.applicationInfo.seinfo;
16720            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16721        }
16722
16723        // Now that we're guarded by frozen state, kill app during move
16724        final long token = Binder.clearCallingIdentity();
16725        try {
16726            killApplication(packageName, appId, "move pkg");
16727        } finally {
16728            Binder.restoreCallingIdentity(token);
16729        }
16730
16731        final Bundle extras = new Bundle();
16732        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16733        extras.putString(Intent.EXTRA_TITLE, label);
16734        mMoveCallbacks.notifyCreated(moveId, extras);
16735
16736        int installFlags;
16737        final boolean moveCompleteApp;
16738        final File measurePath;
16739
16740        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16741            installFlags = INSTALL_INTERNAL;
16742            moveCompleteApp = !currentAsec;
16743            measurePath = Environment.getDataAppDirectory(volumeUuid);
16744        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16745            installFlags = INSTALL_EXTERNAL;
16746            moveCompleteApp = false;
16747            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16748        } else {
16749            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16750            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16751                    || !volume.isMountedWritable()) {
16752                unfreezePackage(packageName);
16753                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16754                        "Move location not mounted private volume");
16755            }
16756
16757            Preconditions.checkState(!currentAsec);
16758
16759            installFlags = INSTALL_INTERNAL;
16760            moveCompleteApp = true;
16761            measurePath = Environment.getDataAppDirectory(volumeUuid);
16762        }
16763
16764        final PackageStats stats = new PackageStats(null, -1);
16765        synchronized (mInstaller) {
16766            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16767                unfreezePackage(packageName);
16768                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16769                        "Failed to measure package size");
16770            }
16771        }
16772
16773        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16774                + stats.dataSize);
16775
16776        final long startFreeBytes = measurePath.getFreeSpace();
16777        final long sizeBytes;
16778        if (moveCompleteApp) {
16779            sizeBytes = stats.codeSize + stats.dataSize;
16780        } else {
16781            sizeBytes = stats.codeSize;
16782        }
16783
16784        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16785            unfreezePackage(packageName);
16786            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16787                    "Not enough free space to move");
16788        }
16789
16790        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16791
16792        final CountDownLatch installedLatch = new CountDownLatch(1);
16793        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16794            @Override
16795            public void onUserActionRequired(Intent intent) throws RemoteException {
16796                throw new IllegalStateException();
16797            }
16798
16799            @Override
16800            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16801                    Bundle extras) throws RemoteException {
16802                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16803                        + PackageManager.installStatusToString(returnCode, msg));
16804
16805                installedLatch.countDown();
16806
16807                // Regardless of success or failure of the move operation,
16808                // always unfreeze the package
16809                unfreezePackage(packageName);
16810
16811                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16812                switch (status) {
16813                    case PackageInstaller.STATUS_SUCCESS:
16814                        mMoveCallbacks.notifyStatusChanged(moveId,
16815                                PackageManager.MOVE_SUCCEEDED);
16816                        break;
16817                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16818                        mMoveCallbacks.notifyStatusChanged(moveId,
16819                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16820                        break;
16821                    default:
16822                        mMoveCallbacks.notifyStatusChanged(moveId,
16823                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16824                        break;
16825                }
16826            }
16827        };
16828
16829        final MoveInfo move;
16830        if (moveCompleteApp) {
16831            // Kick off a thread to report progress estimates
16832            new Thread() {
16833                @Override
16834                public void run() {
16835                    while (true) {
16836                        try {
16837                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16838                                break;
16839                            }
16840                        } catch (InterruptedException ignored) {
16841                        }
16842
16843                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16844                        final int progress = 10 + (int) MathUtils.constrain(
16845                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16846                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16847                    }
16848                }
16849            }.start();
16850
16851            final String dataAppName = codeFile.getName();
16852            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16853                    dataAppName, appId, seinfo);
16854        } else {
16855            move = null;
16856        }
16857
16858        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16859
16860        final Message msg = mHandler.obtainMessage(INIT_COPY);
16861        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16862        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16863                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16864        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16865        msg.obj = params;
16866
16867        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16868                System.identityHashCode(msg.obj));
16869        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16870                System.identityHashCode(msg.obj));
16871
16872        mHandler.sendMessage(msg);
16873    }
16874
16875    @Override
16876    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16877        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16878
16879        final int realMoveId = mNextMoveId.getAndIncrement();
16880        final Bundle extras = new Bundle();
16881        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16882        mMoveCallbacks.notifyCreated(realMoveId, extras);
16883
16884        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16885            @Override
16886            public void onCreated(int moveId, Bundle extras) {
16887                // Ignored
16888            }
16889
16890            @Override
16891            public void onStatusChanged(int moveId, int status, long estMillis) {
16892                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16893            }
16894        };
16895
16896        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16897        storage.setPrimaryStorageUuid(volumeUuid, callback);
16898        return realMoveId;
16899    }
16900
16901    @Override
16902    public int getMoveStatus(int moveId) {
16903        mContext.enforceCallingOrSelfPermission(
16904                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16905        return mMoveCallbacks.mLastStatus.get(moveId);
16906    }
16907
16908    @Override
16909    public void registerMoveCallback(IPackageMoveObserver callback) {
16910        mContext.enforceCallingOrSelfPermission(
16911                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16912        mMoveCallbacks.register(callback);
16913    }
16914
16915    @Override
16916    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16917        mContext.enforceCallingOrSelfPermission(
16918                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16919        mMoveCallbacks.unregister(callback);
16920    }
16921
16922    @Override
16923    public boolean setInstallLocation(int loc) {
16924        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16925                null);
16926        if (getInstallLocation() == loc) {
16927            return true;
16928        }
16929        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16930                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16931            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16932                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16933            return true;
16934        }
16935        return false;
16936   }
16937
16938    @Override
16939    public int getInstallLocation() {
16940        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16941                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16942                PackageHelper.APP_INSTALL_AUTO);
16943    }
16944
16945    /** Called by UserManagerService */
16946    void cleanUpUser(UserManagerService userManager, int userHandle) {
16947        synchronized (mPackages) {
16948            mDirtyUsers.remove(userHandle);
16949            mUserNeedsBadging.delete(userHandle);
16950            mSettings.removeUserLPw(userHandle);
16951            mPendingBroadcasts.remove(userHandle);
16952            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16953        }
16954        synchronized (mInstallLock) {
16955            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16956            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16957                final String volumeUuid = vol.getFsUuid();
16958                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16959                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16960            }
16961            synchronized (mPackages) {
16962                removeUnusedPackagesLILPw(userManager, userHandle);
16963            }
16964        }
16965    }
16966
16967    /**
16968     * We're removing userHandle and would like to remove any downloaded packages
16969     * that are no longer in use by any other user.
16970     * @param userHandle the user being removed
16971     */
16972    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16973        final boolean DEBUG_CLEAN_APKS = false;
16974        int [] users = userManager.getUserIds();
16975        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16976        while (psit.hasNext()) {
16977            PackageSetting ps = psit.next();
16978            if (ps.pkg == null) {
16979                continue;
16980            }
16981            final String packageName = ps.pkg.packageName;
16982            // Skip over if system app
16983            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16984                continue;
16985            }
16986            if (DEBUG_CLEAN_APKS) {
16987                Slog.i(TAG, "Checking package " + packageName);
16988            }
16989            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16990            if (keep) {
16991                if (DEBUG_CLEAN_APKS) {
16992                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16993                }
16994            } else {
16995                for (int i = 0; i < users.length; i++) {
16996                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16997                        keep = true;
16998                        if (DEBUG_CLEAN_APKS) {
16999                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17000                                    + users[i]);
17001                        }
17002                        break;
17003                    }
17004                }
17005            }
17006            if (!keep) {
17007                if (DEBUG_CLEAN_APKS) {
17008                    Slog.i(TAG, "  Removing package " + packageName);
17009                }
17010                mHandler.post(new Runnable() {
17011                    public void run() {
17012                        deletePackageX(packageName, userHandle, 0);
17013                    } //end run
17014                });
17015            }
17016        }
17017    }
17018
17019    /** Called by UserManagerService */
17020    void createNewUser(int userHandle) {
17021        synchronized (mInstallLock) {
17022            mInstaller.createUserConfig(userHandle);
17023            mSettings.createNewUserLI(this, mInstaller, userHandle);
17024        }
17025        synchronized (mPackages) {
17026            applyFactoryDefaultBrowserLPw(userHandle);
17027            primeDomainVerificationsLPw(userHandle);
17028        }
17029    }
17030
17031    void newUserCreated(final int userHandle) {
17032        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17033        // If permission review for legacy apps is required, we represent
17034        // dagerous permissions for such apps as always granted runtime
17035        // permissions to keep per user flag state whether review is needed.
17036        // Hence, if a new user is added we have to propagate dangerous
17037        // permission grants for these legacy apps.
17038        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17039            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17040                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17041        }
17042    }
17043
17044    @Override
17045    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17046        mContext.enforceCallingOrSelfPermission(
17047                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17048                "Only package verification agents can read the verifier device identity");
17049
17050        synchronized (mPackages) {
17051            return mSettings.getVerifierDeviceIdentityLPw();
17052        }
17053    }
17054
17055    @Override
17056    public void setPermissionEnforced(String permission, boolean enforced) {
17057        // TODO: Now that we no longer change GID for storage, this should to away.
17058        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17059                "setPermissionEnforced");
17060        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17061            synchronized (mPackages) {
17062                if (mSettings.mReadExternalStorageEnforced == null
17063                        || mSettings.mReadExternalStorageEnforced != enforced) {
17064                    mSettings.mReadExternalStorageEnforced = enforced;
17065                    mSettings.writeLPr();
17066                }
17067            }
17068            // kill any non-foreground processes so we restart them and
17069            // grant/revoke the GID.
17070            final IActivityManager am = ActivityManagerNative.getDefault();
17071            if (am != null) {
17072                final long token = Binder.clearCallingIdentity();
17073                try {
17074                    am.killProcessesBelowForeground("setPermissionEnforcement");
17075                } catch (RemoteException e) {
17076                } finally {
17077                    Binder.restoreCallingIdentity(token);
17078                }
17079            }
17080        } else {
17081            throw new IllegalArgumentException("No selective enforcement for " + permission);
17082        }
17083    }
17084
17085    @Override
17086    @Deprecated
17087    public boolean isPermissionEnforced(String permission) {
17088        return true;
17089    }
17090
17091    @Override
17092    public boolean isStorageLow() {
17093        final long token = Binder.clearCallingIdentity();
17094        try {
17095            final DeviceStorageMonitorInternal
17096                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17097            if (dsm != null) {
17098                return dsm.isMemoryLow();
17099            } else {
17100                return false;
17101            }
17102        } finally {
17103            Binder.restoreCallingIdentity(token);
17104        }
17105    }
17106
17107    @Override
17108    public IPackageInstaller getPackageInstaller() {
17109        return mInstallerService;
17110    }
17111
17112    private boolean userNeedsBadging(int userId) {
17113        int index = mUserNeedsBadging.indexOfKey(userId);
17114        if (index < 0) {
17115            final UserInfo userInfo;
17116            final long token = Binder.clearCallingIdentity();
17117            try {
17118                userInfo = sUserManager.getUserInfo(userId);
17119            } finally {
17120                Binder.restoreCallingIdentity(token);
17121            }
17122            final boolean b;
17123            if (userInfo != null && userInfo.isManagedProfile()) {
17124                b = true;
17125            } else {
17126                b = false;
17127            }
17128            mUserNeedsBadging.put(userId, b);
17129            return b;
17130        }
17131        return mUserNeedsBadging.valueAt(index);
17132    }
17133
17134    @Override
17135    public KeySet getKeySetByAlias(String packageName, String alias) {
17136        if (packageName == null || alias == null) {
17137            return null;
17138        }
17139        synchronized(mPackages) {
17140            final PackageParser.Package pkg = mPackages.get(packageName);
17141            if (pkg == null) {
17142                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17143                throw new IllegalArgumentException("Unknown package: " + packageName);
17144            }
17145            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17146            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17147        }
17148    }
17149
17150    @Override
17151    public KeySet getSigningKeySet(String packageName) {
17152        if (packageName == null) {
17153            return null;
17154        }
17155        synchronized(mPackages) {
17156            final PackageParser.Package pkg = mPackages.get(packageName);
17157            if (pkg == null) {
17158                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17159                throw new IllegalArgumentException("Unknown package: " + packageName);
17160            }
17161            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17162                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17163                throw new SecurityException("May not access signing KeySet of other apps.");
17164            }
17165            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17166            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17167        }
17168    }
17169
17170    @Override
17171    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17172        if (packageName == null || ks == null) {
17173            return false;
17174        }
17175        synchronized(mPackages) {
17176            final PackageParser.Package pkg = mPackages.get(packageName);
17177            if (pkg == null) {
17178                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17179                throw new IllegalArgumentException("Unknown package: " + packageName);
17180            }
17181            IBinder ksh = ks.getToken();
17182            if (ksh instanceof KeySetHandle) {
17183                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17184                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17185            }
17186            return false;
17187        }
17188    }
17189
17190    @Override
17191    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17192        if (packageName == null || ks == null) {
17193            return false;
17194        }
17195        synchronized(mPackages) {
17196            final PackageParser.Package pkg = mPackages.get(packageName);
17197            if (pkg == null) {
17198                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17199                throw new IllegalArgumentException("Unknown package: " + packageName);
17200            }
17201            IBinder ksh = ks.getToken();
17202            if (ksh instanceof KeySetHandle) {
17203                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17204                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17205            }
17206            return false;
17207        }
17208    }
17209
17210    private void deletePackageIfUnusedLPr(final String packageName) {
17211        PackageSetting ps = mSettings.mPackages.get(packageName);
17212        if (ps == null) {
17213            return;
17214        }
17215        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17216            // TODO Implement atomic delete if package is unused
17217            // It is currently possible that the package will be deleted even if it is installed
17218            // after this method returns.
17219            mHandler.post(new Runnable() {
17220                public void run() {
17221                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17222                }
17223            });
17224        }
17225    }
17226
17227    /**
17228     * Check and throw if the given before/after packages would be considered a
17229     * downgrade.
17230     */
17231    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17232            throws PackageManagerException {
17233        if (after.versionCode < before.mVersionCode) {
17234            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17235                    "Update version code " + after.versionCode + " is older than current "
17236                    + before.mVersionCode);
17237        } else if (after.versionCode == before.mVersionCode) {
17238            if (after.baseRevisionCode < before.baseRevisionCode) {
17239                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17240                        "Update base revision code " + after.baseRevisionCode
17241                        + " is older than current " + before.baseRevisionCode);
17242            }
17243
17244            if (!ArrayUtils.isEmpty(after.splitNames)) {
17245                for (int i = 0; i < after.splitNames.length; i++) {
17246                    final String splitName = after.splitNames[i];
17247                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17248                    if (j != -1) {
17249                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17250                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17251                                    "Update split " + splitName + " revision code "
17252                                    + after.splitRevisionCodes[i] + " is older than current "
17253                                    + before.splitRevisionCodes[j]);
17254                        }
17255                    }
17256                }
17257            }
17258        }
17259    }
17260
17261    private static class MoveCallbacks extends Handler {
17262        private static final int MSG_CREATED = 1;
17263        private static final int MSG_STATUS_CHANGED = 2;
17264
17265        private final RemoteCallbackList<IPackageMoveObserver>
17266                mCallbacks = new RemoteCallbackList<>();
17267
17268        private final SparseIntArray mLastStatus = new SparseIntArray();
17269
17270        public MoveCallbacks(Looper looper) {
17271            super(looper);
17272        }
17273
17274        public void register(IPackageMoveObserver callback) {
17275            mCallbacks.register(callback);
17276        }
17277
17278        public void unregister(IPackageMoveObserver callback) {
17279            mCallbacks.unregister(callback);
17280        }
17281
17282        @Override
17283        public void handleMessage(Message msg) {
17284            final SomeArgs args = (SomeArgs) msg.obj;
17285            final int n = mCallbacks.beginBroadcast();
17286            for (int i = 0; i < n; i++) {
17287                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17288                try {
17289                    invokeCallback(callback, msg.what, args);
17290                } catch (RemoteException ignored) {
17291                }
17292            }
17293            mCallbacks.finishBroadcast();
17294            args.recycle();
17295        }
17296
17297        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17298                throws RemoteException {
17299            switch (what) {
17300                case MSG_CREATED: {
17301                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17302                    break;
17303                }
17304                case MSG_STATUS_CHANGED: {
17305                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17306                    break;
17307                }
17308            }
17309        }
17310
17311        private void notifyCreated(int moveId, Bundle extras) {
17312            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17313
17314            final SomeArgs args = SomeArgs.obtain();
17315            args.argi1 = moveId;
17316            args.arg2 = extras;
17317            obtainMessage(MSG_CREATED, args).sendToTarget();
17318        }
17319
17320        private void notifyStatusChanged(int moveId, int status) {
17321            notifyStatusChanged(moveId, status, -1);
17322        }
17323
17324        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17325            Slog.v(TAG, "Move " + moveId + " status " + status);
17326
17327            final SomeArgs args = SomeArgs.obtain();
17328            args.argi1 = moveId;
17329            args.argi2 = status;
17330            args.arg3 = estMillis;
17331            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17332
17333            synchronized (mLastStatus) {
17334                mLastStatus.put(moveId, status);
17335            }
17336        }
17337    }
17338
17339    private final static class OnPermissionChangeListeners extends Handler {
17340        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17341
17342        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17343                new RemoteCallbackList<>();
17344
17345        public OnPermissionChangeListeners(Looper looper) {
17346            super(looper);
17347        }
17348
17349        @Override
17350        public void handleMessage(Message msg) {
17351            switch (msg.what) {
17352                case MSG_ON_PERMISSIONS_CHANGED: {
17353                    final int uid = msg.arg1;
17354                    handleOnPermissionsChanged(uid);
17355                } break;
17356            }
17357        }
17358
17359        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17360            mPermissionListeners.register(listener);
17361
17362        }
17363
17364        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17365            mPermissionListeners.unregister(listener);
17366        }
17367
17368        public void onPermissionsChanged(int uid) {
17369            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17370                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17371            }
17372        }
17373
17374        private void handleOnPermissionsChanged(int uid) {
17375            final int count = mPermissionListeners.beginBroadcast();
17376            try {
17377                for (int i = 0; i < count; i++) {
17378                    IOnPermissionsChangeListener callback = mPermissionListeners
17379                            .getBroadcastItem(i);
17380                    try {
17381                        callback.onPermissionsChanged(uid);
17382                    } catch (RemoteException e) {
17383                        Log.e(TAG, "Permission listener is dead", e);
17384                    }
17385                }
17386            } finally {
17387                mPermissionListeners.finishBroadcast();
17388            }
17389        }
17390    }
17391
17392    private class PackageManagerInternalImpl extends PackageManagerInternal {
17393        @Override
17394        public void setLocationPackagesProvider(PackagesProvider provider) {
17395            synchronized (mPackages) {
17396                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17397            }
17398        }
17399
17400        @Override
17401        public void setImePackagesProvider(PackagesProvider provider) {
17402            synchronized (mPackages) {
17403                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17404            }
17405        }
17406
17407        @Override
17408        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17409            synchronized (mPackages) {
17410                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17411            }
17412        }
17413
17414        @Override
17415        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17416            synchronized (mPackages) {
17417                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17418            }
17419        }
17420
17421        @Override
17422        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17423            synchronized (mPackages) {
17424                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17425            }
17426        }
17427
17428        @Override
17429        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17430            synchronized (mPackages) {
17431                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17432            }
17433        }
17434
17435        @Override
17436        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17437            synchronized (mPackages) {
17438                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17439            }
17440        }
17441
17442        @Override
17443        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17444            synchronized (mPackages) {
17445                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17446                        packageName, userId);
17447            }
17448        }
17449
17450        @Override
17451        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17452            synchronized (mPackages) {
17453                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17454                        packageName, userId);
17455            }
17456        }
17457
17458        @Override
17459        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17460            synchronized (mPackages) {
17461                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17462                        packageName, userId);
17463            }
17464        }
17465
17466        @Override
17467        public void setKeepUninstalledPackages(final List<String> packageList) {
17468            Preconditions.checkNotNull(packageList);
17469            List<String> removedFromList = null;
17470            synchronized (mPackages) {
17471                if (mKeepUninstalledPackages != null) {
17472                    final int packagesCount = mKeepUninstalledPackages.size();
17473                    for (int i = 0; i < packagesCount; i++) {
17474                        String oldPackage = mKeepUninstalledPackages.get(i);
17475                        if (packageList != null && packageList.contains(oldPackage)) {
17476                            continue;
17477                        }
17478                        if (removedFromList == null) {
17479                            removedFromList = new ArrayList<>();
17480                        }
17481                        removedFromList.add(oldPackage);
17482                    }
17483                }
17484                mKeepUninstalledPackages = new ArrayList<>(packageList);
17485                if (removedFromList != null) {
17486                    final int removedCount = removedFromList.size();
17487                    for (int i = 0; i < removedCount; i++) {
17488                        deletePackageIfUnusedLPr(removedFromList.get(i));
17489                    }
17490                }
17491            }
17492        }
17493
17494        @Override
17495        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17496            synchronized (mPackages) {
17497                // If we do not support permission review, done.
17498                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17499                    return false;
17500                }
17501
17502                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17503                if (packageSetting == null) {
17504                    return false;
17505                }
17506
17507                // Permission review applies only to apps not supporting the new permission model.
17508                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17509                    return false;
17510                }
17511
17512                // Legacy apps have the permission and get user consent on launch.
17513                PermissionsState permissionsState = packageSetting.getPermissionsState();
17514                return permissionsState.isPermissionReviewRequired(userId);
17515            }
17516        }
17517    }
17518
17519    @Override
17520    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17521        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17522        synchronized (mPackages) {
17523            final long identity = Binder.clearCallingIdentity();
17524            try {
17525                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17526                        packageNames, userId);
17527            } finally {
17528                Binder.restoreCallingIdentity(identity);
17529            }
17530        }
17531    }
17532
17533    private static void enforceSystemOrPhoneCaller(String tag) {
17534        int callingUid = Binder.getCallingUid();
17535        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17536            throw new SecurityException(
17537                    "Cannot call " + tag + " from UID " + callingUid);
17538        }
17539    }
17540}
17541