PackageManagerService.java revision bc68463602b6c26cca8988e55df8dbf48ca653e5
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_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
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_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
71import static android.system.OsConstants.O_CREAT;
72import static android.system.OsConstants.O_RDWR;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
77import static com.android.internal.util.ArrayUtils.appendInt;
78import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
86
87import android.Manifest;
88import android.app.ActivityManager;
89import android.app.ActivityManagerNative;
90import android.app.AppGlobals;
91import android.app.IActivityManager;
92import android.app.admin.IDevicePolicyManager;
93import android.app.backup.IBackupManager;
94import android.app.usage.UsageStats;
95import android.app.usage.UsageStatsManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.FeatureInfo;
108import android.content.pm.IOnPermissionsChangeListener;
109import android.content.pm.IPackageDataObserver;
110import android.content.pm.IPackageDeleteObserver;
111import android.content.pm.IPackageDeleteObserver2;
112import android.content.pm.IPackageInstallObserver2;
113import android.content.pm.IPackageInstaller;
114import android.content.pm.IPackageManager;
115import android.content.pm.IPackageMoveObserver;
116import android.content.pm.IPackageStatsObserver;
117import android.content.pm.InstrumentationInfo;
118import android.content.pm.IntentFilterVerificationInfo;
119import android.content.pm.KeySet;
120import android.content.pm.ManifestDigest;
121import android.content.pm.PackageCleanItem;
122import android.content.pm.PackageInfo;
123import android.content.pm.PackageInfoLite;
124import android.content.pm.PackageInstaller;
125import android.content.pm.PackageManager;
126import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
127import android.content.pm.PackageManagerInternal;
128import android.content.pm.PackageParser;
129import android.content.pm.PackageParser.ActivityIntentInfo;
130import android.content.pm.PackageParser.PackageLite;
131import android.content.pm.PackageParser.PackageParserException;
132import android.content.pm.PackageStats;
133import android.content.pm.PackageUserState;
134import android.content.pm.ParceledListSlice;
135import android.content.pm.PermissionGroupInfo;
136import android.content.pm.PermissionInfo;
137import android.content.pm.ProviderInfo;
138import android.content.pm.ResolveInfo;
139import android.content.pm.ServiceInfo;
140import android.content.pm.Signature;
141import android.content.pm.UserInfo;
142import android.content.pm.VerificationParams;
143import android.content.pm.VerifierDeviceIdentity;
144import android.content.pm.VerifierInfo;
145import android.content.res.Resources;
146import android.hardware.display.DisplayManager;
147import android.net.Uri;
148import android.os.Debug;
149import android.os.Binder;
150import android.os.Build;
151import android.os.Bundle;
152import android.os.Environment;
153import android.os.Environment.UserEnvironment;
154import android.os.FileUtils;
155import android.os.Handler;
156import android.os.IBinder;
157import android.os.Looper;
158import android.os.Message;
159import android.os.Parcel;
160import android.os.ParcelFileDescriptor;
161import android.os.Process;
162import android.os.RemoteCallbackList;
163import android.os.RemoteException;
164import android.os.SELinux;
165import android.os.ServiceManager;
166import android.os.SystemClock;
167import android.os.SystemProperties;
168import android.os.Trace;
169import android.os.UserHandle;
170import android.os.UserManager;
171import android.os.storage.IMountService;
172import android.os.storage.MountServiceInternal;
173import android.os.storage.StorageEventListener;
174import android.os.storage.StorageManager;
175import android.os.storage.VolumeInfo;
176import android.os.storage.VolumeRecord;
177import android.security.KeyStore;
178import android.security.SystemKeyStore;
179import android.system.ErrnoException;
180import android.system.Os;
181import android.system.StructStat;
182import android.text.TextUtils;
183import android.text.format.DateUtils;
184import android.util.ArrayMap;
185import android.util.ArraySet;
186import android.util.AtomicFile;
187import android.util.DisplayMetrics;
188import android.util.EventLog;
189import android.util.ExceptionUtils;
190import android.util.Log;
191import android.util.LogPrinter;
192import android.util.MathUtils;
193import android.util.PrintStreamPrinter;
194import android.util.Slog;
195import android.util.SparseArray;
196import android.util.SparseBooleanArray;
197import android.util.SparseIntArray;
198import android.util.Xml;
199import android.view.Display;
200
201import dalvik.system.DexFile;
202import dalvik.system.VMRuntime;
203
204import libcore.io.IoUtils;
205import libcore.util.EmptyArray;
206
207import com.android.internal.R;
208import com.android.internal.annotations.GuardedBy;
209import com.android.internal.app.IMediaContainerService;
210import com.android.internal.app.ResolverActivity;
211import com.android.internal.content.NativeLibraryHelper;
212import com.android.internal.content.PackageHelper;
213import com.android.internal.os.IParcelFileDescriptorFactory;
214import com.android.internal.os.SomeArgs;
215import com.android.internal.os.Zygote;
216import com.android.internal.util.ArrayUtils;
217import com.android.internal.util.FastPrintWriter;
218import com.android.internal.util.FastXmlSerializer;
219import com.android.internal.util.IndentingPrintWriter;
220import com.android.internal.util.Preconditions;
221import com.android.server.EventLogTags;
222import com.android.server.FgThread;
223import com.android.server.IntentResolver;
224import com.android.server.LocalServices;
225import com.android.server.ServiceThread;
226import com.android.server.SystemConfig;
227import com.android.server.Watchdog;
228import com.android.server.pm.PermissionsState.PermissionState;
229import com.android.server.pm.Settings.DatabaseVersion;
230import com.android.server.pm.Settings.VersionInfo;
231import com.android.server.storage.DeviceStorageMonitorInternal;
232
233import org.xmlpull.v1.XmlPullParser;
234import org.xmlpull.v1.XmlPullParserException;
235import org.xmlpull.v1.XmlSerializer;
236
237import java.io.BufferedInputStream;
238import java.io.BufferedOutputStream;
239import java.io.BufferedReader;
240import java.io.ByteArrayInputStream;
241import java.io.ByteArrayOutputStream;
242import java.io.File;
243import java.io.FileDescriptor;
244import java.io.FileNotFoundException;
245import java.io.FileOutputStream;
246import java.io.FileReader;
247import java.io.FilenameFilter;
248import java.io.IOException;
249import java.io.InputStream;
250import java.io.PrintWriter;
251import java.nio.charset.StandardCharsets;
252import java.security.NoSuchAlgorithmException;
253import java.security.PublicKey;
254import java.security.cert.CertificateEncodingException;
255import java.security.cert.CertificateException;
256import java.text.SimpleDateFormat;
257import java.util.ArrayList;
258import java.util.Arrays;
259import java.util.Collection;
260import java.util.Collections;
261import java.util.Comparator;
262import java.util.Date;
263import java.util.Iterator;
264import java.util.List;
265import java.util.Map;
266import java.util.Objects;
267import java.util.Set;
268import java.util.concurrent.CountDownLatch;
269import java.util.concurrent.TimeUnit;
270import java.util.concurrent.atomic.AtomicBoolean;
271import java.util.concurrent.atomic.AtomicInteger;
272import java.util.concurrent.atomic.AtomicLong;
273
274/**
275 * Keep track of all those .apks everywhere.
276 *
277 * This is very central to the platform's security; please run the unit
278 * tests whenever making modifications here:
279 *
280runtest -c android.content.pm.PackageManagerTests frameworks-core
281 *
282 * {@hide}
283 */
284public class PackageManagerService extends IPackageManager.Stub {
285    static final String TAG = "PackageManager";
286    static final boolean DEBUG_SETTINGS = false;
287    static final boolean DEBUG_PREFERRED = false;
288    static final boolean DEBUG_UPGRADE = false;
289    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290    private static final boolean DEBUG_BACKUP = false;
291    private static final boolean DEBUG_INSTALL = false;
292    private static final boolean DEBUG_REMOVE = false;
293    private static final boolean DEBUG_BROADCASTS = false;
294    private static final boolean DEBUG_SHOW_INFO = false;
295    private static final boolean DEBUG_PACKAGE_INFO = false;
296    private static final boolean DEBUG_INTENT_MATCHING = false;
297    private static final boolean DEBUG_PACKAGE_SCANNING = false;
298    private static final boolean DEBUG_VERIFY = false;
299    private static final boolean DEBUG_DEXOPT = false;
300    private static final boolean DEBUG_ABI_SELECTION = false;
301
302    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
303
304    private static final int RADIO_UID = Process.PHONE_UID;
305    private static final int LOG_UID = Process.LOG_UID;
306    private static final int NFC_UID = Process.NFC_UID;
307    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
308    private static final int SHELL_UID = Process.SHELL_UID;
309
310    // Cap the size of permission trees that 3rd party apps can define
311    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
312
313    // Suffix used during package installation when copying/moving
314    // package apks to install directory.
315    private static final String INSTALL_PACKAGE_SUFFIX = "-";
316
317    static final int SCAN_NO_DEX = 1<<1;
318    static final int SCAN_FORCE_DEX = 1<<2;
319    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
320    static final int SCAN_NEW_INSTALL = 1<<4;
321    static final int SCAN_NO_PATHS = 1<<5;
322    static final int SCAN_UPDATE_TIME = 1<<6;
323    static final int SCAN_DEFER_DEX = 1<<7;
324    static final int SCAN_BOOTING = 1<<8;
325    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
326    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
327    static final int SCAN_REPLACING = 1<<11;
328    static final int SCAN_REQUIRE_KNOWN = 1<<12;
329    static final int SCAN_MOVE = 1<<13;
330    static final int SCAN_INITIAL = 1<<14;
331
332    static final int REMOVE_CHATTY = 1<<16;
333
334    private static final int[] EMPTY_INT_ARRAY = new int[0];
335
336    /**
337     * Timeout (in milliseconds) after which the watchdog should declare that
338     * our handler thread is wedged.  The usual default for such things is one
339     * minute but we sometimes do very lengthy I/O operations on this thread,
340     * such as installing multi-gigabyte applications, so ours needs to be longer.
341     */
342    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
343
344    /**
345     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
346     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
347     * settings entry if available, otherwise we use the hardcoded default.  If it's been
348     * more than this long since the last fstrim, we force one during the boot sequence.
349     *
350     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
351     * one gets run at the next available charging+idle time.  This final mandatory
352     * no-fstrim check kicks in only of the other scheduling criteria is never met.
353     */
354    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
355
356    /**
357     * Whether verification is enabled by default.
358     */
359    private static final boolean DEFAULT_VERIFY_ENABLE = true;
360
361    /**
362     * The default maximum time to wait for the verification agent to return in
363     * milliseconds.
364     */
365    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
366
367    /**
368     * The default response for package verification timeout.
369     *
370     * This can be either PackageManager.VERIFICATION_ALLOW or
371     * PackageManager.VERIFICATION_REJECT.
372     */
373    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
374
375    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
376
377    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
378            DEFAULT_CONTAINER_PACKAGE,
379            "com.android.defcontainer.DefaultContainerService");
380
381    private static final String KILL_APP_REASON_GIDS_CHANGED =
382            "permission grant or revoke changed gids";
383
384    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
385            "permissions revoked";
386
387    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
388
389    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
390
391    /** Permission grant: not grant the permission. */
392    private static final int GRANT_DENIED = 1;
393
394    /** Permission grant: grant the permission as an install permission. */
395    private static final int GRANT_INSTALL = 2;
396
397    /** Permission grant: grant the permission as an install permission for a legacy app. */
398    private static final int GRANT_INSTALL_LEGACY = 3;
399
400    /** Permission grant: grant the permission as a runtime one. */
401    private static final int GRANT_RUNTIME = 4;
402
403    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
404    private static final int GRANT_UPGRADE = 5;
405
406    /** Canonical intent used to identify what counts as a "web browser" app */
407    private static final Intent sBrowserIntent;
408    static {
409        sBrowserIntent = new Intent();
410        sBrowserIntent.setAction(Intent.ACTION_VIEW);
411        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
412        sBrowserIntent.setData(Uri.parse("http:"));
413    }
414
415    final ServiceThread mHandlerThread;
416
417    final PackageHandler mHandler;
418
419    /**
420     * Messages for {@link #mHandler} that need to wait for system ready before
421     * being dispatched.
422     */
423    private ArrayList<Message> mPostSystemReadyMessages;
424
425    final int mSdkVersion = Build.VERSION.SDK_INT;
426
427    final Context mContext;
428    final boolean mFactoryTest;
429    final boolean mOnlyCore;
430    final boolean mLazyDexOpt;
431    final long mDexOptLRUThresholdInMills;
432    final DisplayMetrics mMetrics;
433    final int mDefParseFlags;
434    final String[] mSeparateProcesses;
435    final boolean mIsUpgrade;
436
437    // This is where all application persistent data goes.
438    final File mAppDataDir;
439
440    // This is where all application persistent data goes for secondary users.
441    final File mUserAppDataDir;
442
443    /** The location for ASEC container files on internal storage. */
444    final String mAsecInternalPath;
445
446    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
447    // LOCK HELD.  Can be called with mInstallLock held.
448    @GuardedBy("mInstallLock")
449    final Installer mInstaller;
450
451    /** Directory where installed third-party apps stored */
452    final File mAppInstallDir;
453
454    /**
455     * Directory to which applications installed internally have their
456     * 32 bit native libraries copied.
457     */
458    private File mAppLib32InstallDir;
459
460    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
461    // apps.
462    final File mDrmAppPrivateInstallDir;
463
464    // ----------------------------------------------------------------
465
466    // Lock for state used when installing and doing other long running
467    // operations.  Methods that must be called with this lock held have
468    // the suffix "LI".
469    final Object mInstallLock = new Object();
470
471    // ----------------------------------------------------------------
472
473    // Keys are String (package name), values are Package.  This also serves
474    // as the lock for the global state.  Methods that must be called with
475    // this lock held have the prefix "LP".
476    @GuardedBy("mPackages")
477    final ArrayMap<String, PackageParser.Package> mPackages =
478            new ArrayMap<String, PackageParser.Package>();
479
480    // Tracks available target package names -> overlay package paths.
481    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
482        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
483
484    /**
485     * Tracks new system packages [received in an OTA] that we expect to
486     * find updated user-installed versions. Keys are package name, values
487     * are package location.
488     */
489    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
490
491    /**
492     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
493     */
494    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
495    /**
496     * Whether or not system app permissions should be promoted from install to runtime.
497     */
498    boolean mPromoteSystemApps;
499
500    final Settings mSettings;
501    boolean mRestoredSettings;
502
503    // System configuration read by SystemConfig.
504    final int[] mGlobalGids;
505    final SparseArray<ArraySet<String>> mSystemPermissions;
506    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
507
508    // If mac_permissions.xml was found for seinfo labeling.
509    boolean mFoundPolicyFile;
510
511    // If a recursive restorecon of /data/data/<pkg> is needed.
512    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
513
514    public static final class SharedLibraryEntry {
515        public final String path;
516        public final String apk;
517
518        SharedLibraryEntry(String _path, String _apk) {
519            path = _path;
520            apk = _apk;
521        }
522    }
523
524    // Currently known shared libraries.
525    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
526            new ArrayMap<String, SharedLibraryEntry>();
527
528    // All available activities, for your resolving pleasure.
529    final ActivityIntentResolver mActivities =
530            new ActivityIntentResolver();
531
532    // All available receivers, for your resolving pleasure.
533    final ActivityIntentResolver mReceivers =
534            new ActivityIntentResolver();
535
536    // All available services, for your resolving pleasure.
537    final ServiceIntentResolver mServices = new ServiceIntentResolver();
538
539    // All available providers, for your resolving pleasure.
540    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
541
542    // Mapping from provider base names (first directory in content URI codePath)
543    // to the provider information.
544    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
545            new ArrayMap<String, PackageParser.Provider>();
546
547    // Mapping from instrumentation class names to info about them.
548    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
549            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
550
551    // Mapping from permission names to info about them.
552    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
553            new ArrayMap<String, PackageParser.PermissionGroup>();
554
555    // Packages whose data we have transfered into another package, thus
556    // should no longer exist.
557    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
558
559    // Broadcast actions that are only available to the system.
560    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
561
562    /** List of packages waiting for verification. */
563    final SparseArray<PackageVerificationState> mPendingVerification
564            = new SparseArray<PackageVerificationState>();
565
566    /** Set of packages associated with each app op permission. */
567    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
568
569    final PackageInstallerService mInstallerService;
570
571    private final PackageDexOptimizer mPackageDexOptimizer;
572
573    private AtomicInteger mNextMoveId = new AtomicInteger();
574    private final MoveCallbacks mMoveCallbacks;
575
576    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
577
578    // Cache of users who need badging.
579    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
580
581    /** Token for keys in mPendingVerification. */
582    private int mPendingVerificationToken = 0;
583
584    volatile boolean mSystemReady;
585    volatile boolean mSafeMode;
586    volatile boolean mHasSystemUidErrors;
587
588    ApplicationInfo mAndroidApplication;
589    final ActivityInfo mResolveActivity = new ActivityInfo();
590    final ResolveInfo mResolveInfo = new ResolveInfo();
591    ComponentName mResolveComponentName;
592    PackageParser.Package mPlatformPackage;
593    ComponentName mCustomResolverComponentName;
594
595    boolean mResolverReplaced = false;
596
597    private final ComponentName mIntentFilterVerifierComponent;
598    private int mIntentFilterVerificationToken = 0;
599
600    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
601            = new SparseArray<IntentFilterVerificationState>();
602
603    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
604            new DefaultPermissionGrantPolicy(this);
605
606    private static class IFVerificationParams {
607        PackageParser.Package pkg;
608        boolean replacing;
609        int userId;
610        int verifierUid;
611
612        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
613                int _userId, int _verifierUid) {
614            pkg = _pkg;
615            replacing = _replacing;
616            userId = _userId;
617            replacing = _replacing;
618            verifierUid = _verifierUid;
619        }
620    }
621
622    private interface IntentFilterVerifier<T extends IntentFilter> {
623        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
624                                               T filter, String packageName);
625        void startVerifications(int userId);
626        void receiveVerificationResponse(int verificationId);
627    }
628
629    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
630        private Context mContext;
631        private ComponentName mIntentFilterVerifierComponent;
632        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
633
634        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
635            mContext = context;
636            mIntentFilterVerifierComponent = verifierComponent;
637        }
638
639        private String getDefaultScheme() {
640            return IntentFilter.SCHEME_HTTPS;
641        }
642
643        @Override
644        public void startVerifications(int userId) {
645            // Launch verifications requests
646            int count = mCurrentIntentFilterVerifications.size();
647            for (int n=0; n<count; n++) {
648                int verificationId = mCurrentIntentFilterVerifications.get(n);
649                final IntentFilterVerificationState ivs =
650                        mIntentFilterVerificationStates.get(verificationId);
651
652                String packageName = ivs.getPackageName();
653
654                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
655                final int filterCount = filters.size();
656                ArraySet<String> domainsSet = new ArraySet<>();
657                for (int m=0; m<filterCount; m++) {
658                    PackageParser.ActivityIntentInfo filter = filters.get(m);
659                    domainsSet.addAll(filter.getHostsList());
660                }
661                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
662                synchronized (mPackages) {
663                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
664                            packageName, domainsList) != null) {
665                        scheduleWriteSettingsLocked();
666                    }
667                }
668                sendVerificationRequest(userId, verificationId, ivs);
669            }
670            mCurrentIntentFilterVerifications.clear();
671        }
672
673        private void sendVerificationRequest(int userId, int verificationId,
674                IntentFilterVerificationState ivs) {
675
676            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
677            verificationIntent.putExtra(
678                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
679                    verificationId);
680            verificationIntent.putExtra(
681                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
682                    getDefaultScheme());
683            verificationIntent.putExtra(
684                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
685                    ivs.getHostsString());
686            verificationIntent.putExtra(
687                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
688                    ivs.getPackageName());
689            verificationIntent.setComponent(mIntentFilterVerifierComponent);
690            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
691
692            UserHandle user = new UserHandle(userId);
693            mContext.sendBroadcastAsUser(verificationIntent, user);
694            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
695                    "Sending IntentFilter verification broadcast");
696        }
697
698        public void receiveVerificationResponse(int verificationId) {
699            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
700
701            final boolean verified = ivs.isVerified();
702
703            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
704            final int count = filters.size();
705            if (DEBUG_DOMAIN_VERIFICATION) {
706                Slog.i(TAG, "Received verification response " + verificationId
707                        + " for " + count + " filters, verified=" + verified);
708            }
709            for (int n=0; n<count; n++) {
710                PackageParser.ActivityIntentInfo filter = filters.get(n);
711                filter.setVerified(verified);
712
713                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
714                        + " verified with result:" + verified + " and hosts:"
715                        + ivs.getHostsString());
716            }
717
718            mIntentFilterVerificationStates.remove(verificationId);
719
720            final String packageName = ivs.getPackageName();
721            IntentFilterVerificationInfo ivi = null;
722
723            synchronized (mPackages) {
724                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
725            }
726            if (ivi == null) {
727                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
728                        + verificationId + " packageName:" + packageName);
729                return;
730            }
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Updating IntentFilterVerificationInfo for package " + packageName
733                            +" verificationId:" + verificationId);
734
735            synchronized (mPackages) {
736                if (verified) {
737                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
738                } else {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
740                }
741                scheduleWriteSettingsLocked();
742
743                final int userId = ivs.getUserId();
744                if (userId != UserHandle.USER_ALL) {
745                    final int userStatus =
746                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
747
748                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
749                    boolean needUpdate = false;
750
751                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
752                    // already been set by the User thru the Disambiguation dialog
753                    switch (userStatus) {
754                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
755                            if (verified) {
756                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
757                            } else {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
759                            }
760                            needUpdate = true;
761                            break;
762
763                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
764                            if (verified) {
765                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
766                                needUpdate = true;
767                            }
768                            break;
769
770                        default:
771                            // Nothing to do
772                    }
773
774                    if (needUpdate) {
775                        mSettings.updateIntentFilterVerificationStatusLPw(
776                                packageName, updatedStatus, userId);
777                        scheduleWritePackageRestrictionsLocked(userId);
778                    }
779                }
780            }
781        }
782
783        @Override
784        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
785                    ActivityIntentInfo filter, String packageName) {
786            if (!hasValidDomains(filter)) {
787                return false;
788            }
789            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
790            if (ivs == null) {
791                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
792                        packageName);
793            }
794            if (DEBUG_DOMAIN_VERIFICATION) {
795                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
796            }
797            ivs.addFilter(filter);
798            return true;
799        }
800
801        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
802                int userId, int verificationId, String packageName) {
803            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
804                    verifierUid, userId, packageName);
805            ivs.setPendingState();
806            synchronized (mPackages) {
807                mIntentFilterVerificationStates.append(verificationId, ivs);
808                mCurrentIntentFilterVerifications.add(verificationId);
809            }
810            return ivs;
811        }
812    }
813
814    private static boolean hasValidDomains(ActivityIntentInfo filter) {
815        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
816                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
817                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
818    }
819
820    private IntentFilterVerifier mIntentFilterVerifier;
821
822    // Set of pending broadcasts for aggregating enable/disable of components.
823    static class PendingPackageBroadcasts {
824        // for each user id, a map of <package name -> components within that package>
825        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
826
827        public PendingPackageBroadcasts() {
828            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
829        }
830
831        public ArrayList<String> get(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
833            return packages.get(packageName);
834        }
835
836        public void put(int userId, String packageName, ArrayList<String> components) {
837            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
838            packages.put(packageName, components);
839        }
840
841        public void remove(int userId, String packageName) {
842            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
843            if (packages != null) {
844                packages.remove(packageName);
845            }
846        }
847
848        public void remove(int userId) {
849            mUidMap.remove(userId);
850        }
851
852        public int userIdCount() {
853            return mUidMap.size();
854        }
855
856        public int userIdAt(int n) {
857            return mUidMap.keyAt(n);
858        }
859
860        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
861            return mUidMap.get(userId);
862        }
863
864        public int size() {
865            // total number of pending broadcast entries across all userIds
866            int num = 0;
867            for (int i = 0; i< mUidMap.size(); i++) {
868                num += mUidMap.valueAt(i).size();
869            }
870            return num;
871        }
872
873        public void clear() {
874            mUidMap.clear();
875        }
876
877        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
878            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
879            if (map == null) {
880                map = new ArrayMap<String, ArrayList<String>>();
881                mUidMap.put(userId, map);
882            }
883            return map;
884        }
885    }
886    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
887
888    // Service Connection to remote media container service to copy
889    // package uri's from external media onto secure containers
890    // or internal storage.
891    private IMediaContainerService mContainerService = null;
892
893    static final int SEND_PENDING_BROADCAST = 1;
894    static final int MCS_BOUND = 3;
895    static final int END_COPY = 4;
896    static final int INIT_COPY = 5;
897    static final int MCS_UNBIND = 6;
898    static final int START_CLEANING_PACKAGE = 7;
899    static final int FIND_INSTALL_LOC = 8;
900    static final int POST_INSTALL = 9;
901    static final int MCS_RECONNECT = 10;
902    static final int MCS_GIVE_UP = 11;
903    static final int UPDATED_MEDIA_STATUS = 12;
904    static final int WRITE_SETTINGS = 13;
905    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
906    static final int PACKAGE_VERIFIED = 15;
907    static final int CHECK_PENDING_VERIFICATION = 16;
908    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
909    static final int INTENT_FILTER_VERIFIED = 18;
910
911    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
912
913    // Delay time in millisecs
914    static final int BROADCAST_DELAY = 10 * 1000;
915
916    static UserManagerService sUserManager;
917
918    // Stores a list of users whose package restrictions file needs to be updated
919    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
920
921    final private DefaultContainerConnection mDefContainerConn =
922            new DefaultContainerConnection();
923    class DefaultContainerConnection implements ServiceConnection {
924        public void onServiceConnected(ComponentName name, IBinder service) {
925            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
926            IMediaContainerService imcs =
927                IMediaContainerService.Stub.asInterface(service);
928            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
929        }
930
931        public void onServiceDisconnected(ComponentName name) {
932            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
933        }
934    }
935
936    // Recordkeeping of restore-after-install operations that are currently in flight
937    // between the Package Manager and the Backup Manager
938    class PostInstallData {
939        public InstallArgs args;
940        public PackageInstalledInfo res;
941
942        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
943            args = _a;
944            res = _r;
945        }
946    }
947
948    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
949    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
950
951    // XML tags for backup/restore of various bits of state
952    private static final String TAG_PREFERRED_BACKUP = "pa";
953    private static final String TAG_DEFAULT_APPS = "da";
954    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
955
956    final String mRequiredVerifierPackage;
957    final String mRequiredInstallerPackage;
958
959    private final PackageUsage mPackageUsage = new PackageUsage();
960
961    private class PackageUsage {
962        private static final int WRITE_INTERVAL
963            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
964
965        private final Object mFileLock = new Object();
966        private final AtomicLong mLastWritten = new AtomicLong(0);
967        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
968
969        private boolean mIsHistoricalPackageUsageAvailable = true;
970
971        boolean isHistoricalPackageUsageAvailable() {
972            return mIsHistoricalPackageUsageAvailable;
973        }
974
975        void write(boolean force) {
976            if (force) {
977                writeInternal();
978                return;
979            }
980            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
981                && !DEBUG_DEXOPT) {
982                return;
983            }
984            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
985                new Thread("PackageUsage_DiskWriter") {
986                    @Override
987                    public void run() {
988                        try {
989                            writeInternal();
990                        } finally {
991                            mBackgroundWriteRunning.set(false);
992                        }
993                    }
994                }.start();
995            }
996        }
997
998        private void writeInternal() {
999            synchronized (mPackages) {
1000                synchronized (mFileLock) {
1001                    AtomicFile file = getFile();
1002                    FileOutputStream f = null;
1003                    try {
1004                        f = file.startWrite();
1005                        BufferedOutputStream out = new BufferedOutputStream(f);
1006                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1007                        StringBuilder sb = new StringBuilder();
1008                        for (PackageParser.Package pkg : mPackages.values()) {
1009                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1010                                continue;
1011                            }
1012                            sb.setLength(0);
1013                            sb.append(pkg.packageName);
1014                            sb.append(' ');
1015                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1016                            sb.append('\n');
1017                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1018                        }
1019                        out.flush();
1020                        file.finishWrite(f);
1021                    } catch (IOException e) {
1022                        if (f != null) {
1023                            file.failWrite(f);
1024                        }
1025                        Log.e(TAG, "Failed to write package usage times", e);
1026                    }
1027                }
1028            }
1029            mLastWritten.set(SystemClock.elapsedRealtime());
1030        }
1031
1032        void readLP() {
1033            synchronized (mFileLock) {
1034                AtomicFile file = getFile();
1035                BufferedInputStream in = null;
1036                try {
1037                    in = new BufferedInputStream(file.openRead());
1038                    StringBuffer sb = new StringBuffer();
1039                    while (true) {
1040                        String packageName = readToken(in, sb, ' ');
1041                        if (packageName == null) {
1042                            break;
1043                        }
1044                        String timeInMillisString = readToken(in, sb, '\n');
1045                        if (timeInMillisString == null) {
1046                            throw new IOException("Failed to find last usage time for package "
1047                                                  + packageName);
1048                        }
1049                        PackageParser.Package pkg = mPackages.get(packageName);
1050                        if (pkg == null) {
1051                            continue;
1052                        }
1053                        long timeInMillis;
1054                        try {
1055                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1056                        } catch (NumberFormatException e) {
1057                            throw new IOException("Failed to parse " + timeInMillisString
1058                                                  + " as a long.", e);
1059                        }
1060                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1061                    }
1062                } catch (FileNotFoundException expected) {
1063                    mIsHistoricalPackageUsageAvailable = false;
1064                } catch (IOException e) {
1065                    Log.w(TAG, "Failed to read package usage times", e);
1066                } finally {
1067                    IoUtils.closeQuietly(in);
1068                }
1069            }
1070            mLastWritten.set(SystemClock.elapsedRealtime());
1071        }
1072
1073        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1074                throws IOException {
1075            sb.setLength(0);
1076            while (true) {
1077                int ch = in.read();
1078                if (ch == -1) {
1079                    if (sb.length() == 0) {
1080                        return null;
1081                    }
1082                    throw new IOException("Unexpected EOF");
1083                }
1084                if (ch == endOfToken) {
1085                    return sb.toString();
1086                }
1087                sb.append((char)ch);
1088            }
1089        }
1090
1091        private AtomicFile getFile() {
1092            File dataDir = Environment.getDataDirectory();
1093            File systemDir = new File(dataDir, "system");
1094            File fname = new File(systemDir, "package-usage.list");
1095            return new AtomicFile(fname);
1096        }
1097    }
1098
1099    class PackageHandler extends Handler {
1100        private boolean mBound = false;
1101        final ArrayList<HandlerParams> mPendingInstalls =
1102            new ArrayList<HandlerParams>();
1103
1104        private boolean connectToService() {
1105            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1106                    " DefaultContainerService");
1107            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1110                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1111                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                mBound = true;
1113                return true;
1114            }
1115            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116            return false;
1117        }
1118
1119        private void disconnectService() {
1120            mContainerService = null;
1121            mBound = false;
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            mContext.unbindService(mDefContainerConn);
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125        }
1126
1127        PackageHandler(Looper looper) {
1128            super(looper);
1129        }
1130
1131        public void handleMessage(Message msg) {
1132            try {
1133                doHandleMessage(msg);
1134            } finally {
1135                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136            }
1137        }
1138
1139        void doHandleMessage(Message msg) {
1140            switch (msg.what) {
1141                case INIT_COPY: {
1142                    HandlerParams params = (HandlerParams) msg.obj;
1143                    int idx = mPendingInstalls.size();
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1145                    // If a bind was already initiated we dont really
1146                    // need to do anything. The pending install
1147                    // will be processed later on.
1148                    if (!mBound) {
1149                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1150                                System.identityHashCode(mHandler));
1151                        // If this is the only one pending we might
1152                        // have to bind to the service again.
1153                        if (!connectToService()) {
1154                            Slog.e(TAG, "Failed to bind to media container service");
1155                            params.serviceError();
1156                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1157                                    System.identityHashCode(mHandler));
1158                            if (params.traceMethod != null) {
1159                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1160                                        params.traceCookie);
1161                            }
1162                            return;
1163                        } else {
1164                            // Once we bind to the service, the first
1165                            // pending request will be processed.
1166                            mPendingInstalls.add(idx, params);
1167                        }
1168                    } else {
1169                        mPendingInstalls.add(idx, params);
1170                        // Already bound to the service. Just make
1171                        // sure we trigger off processing the first request.
1172                        if (idx == 0) {
1173                            mHandler.sendEmptyMessage(MCS_BOUND);
1174                        }
1175                    }
1176                    break;
1177                }
1178                case MCS_BOUND: {
1179                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1180                    if (msg.obj != null) {
1181                        mContainerService = (IMediaContainerService) msg.obj;
1182                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1183                                System.identityHashCode(mHandler));
1184                    }
1185                    if (mContainerService == null) {
1186                        if (!mBound) {
1187                            // Something seriously wrong since we are not bound and we are not
1188                            // waiting for connection. Bail out.
1189                            Slog.e(TAG, "Cannot bind to media container service");
1190                            for (HandlerParams params : mPendingInstalls) {
1191                                // Indicate service bind error
1192                                params.serviceError();
1193                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1194                                        System.identityHashCode(params));
1195                                if (params.traceMethod != null) {
1196                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1197                                            params.traceMethod, params.traceCookie);
1198                                }
1199                                return;
1200                            }
1201                            mPendingInstalls.clear();
1202                        } else {
1203                            Slog.w(TAG, "Waiting to connect to media container service");
1204                        }
1205                    } else if (mPendingInstalls.size() > 0) {
1206                        HandlerParams params = mPendingInstalls.get(0);
1207                        if (params != null) {
1208                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1209                                    System.identityHashCode(params));
1210                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1211                            if (params.startCopy()) {
1212                                // We are done...  look for more work or to
1213                                // go idle.
1214                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1215                                        "Checking for more work or unbind...");
1216                                // Delete pending install
1217                                if (mPendingInstalls.size() > 0) {
1218                                    mPendingInstalls.remove(0);
1219                                }
1220                                if (mPendingInstalls.size() == 0) {
1221                                    if (mBound) {
1222                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1223                                                "Posting delayed MCS_UNBIND");
1224                                        removeMessages(MCS_UNBIND);
1225                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1226                                        // Unbind after a little delay, to avoid
1227                                        // continual thrashing.
1228                                        sendMessageDelayed(ubmsg, 10000);
1229                                    }
1230                                } else {
1231                                    // There are more pending requests in queue.
1232                                    // Just post MCS_BOUND message to trigger processing
1233                                    // of next pending install.
1234                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1235                                            "Posting MCS_BOUND for next work");
1236                                    mHandler.sendEmptyMessage(MCS_BOUND);
1237                                }
1238                            }
1239                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1240                        }
1241                    } else {
1242                        // Should never happen ideally.
1243                        Slog.w(TAG, "Empty queue");
1244                    }
1245                    break;
1246                }
1247                case MCS_RECONNECT: {
1248                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1249                    if (mPendingInstalls.size() > 0) {
1250                        if (mBound) {
1251                            disconnectService();
1252                        }
1253                        if (!connectToService()) {
1254                            Slog.e(TAG, "Failed to bind to media container service");
1255                            for (HandlerParams params : mPendingInstalls) {
1256                                // Indicate service bind error
1257                                params.serviceError();
1258                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259                                        System.identityHashCode(params));
1260                            }
1261                            mPendingInstalls.clear();
1262                        }
1263                    }
1264                    break;
1265                }
1266                case MCS_UNBIND: {
1267                    // If there is no actual work left, then time to unbind.
1268                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1269
1270                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1271                        if (mBound) {
1272                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1273
1274                            disconnectService();
1275                        }
1276                    } else if (mPendingInstalls.size() > 0) {
1277                        // There are more pending requests in queue.
1278                        // Just post MCS_BOUND message to trigger processing
1279                        // of next pending install.
1280                        mHandler.sendEmptyMessage(MCS_BOUND);
1281                    }
1282
1283                    break;
1284                }
1285                case MCS_GIVE_UP: {
1286                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1287                    HandlerParams params = mPendingInstalls.remove(0);
1288                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1289                            System.identityHashCode(params));
1290                    break;
1291                }
1292                case SEND_PENDING_BROADCAST: {
1293                    String packages[];
1294                    ArrayList<String> components[];
1295                    int size = 0;
1296                    int uids[];
1297                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1298                    synchronized (mPackages) {
1299                        if (mPendingBroadcasts == null) {
1300                            return;
1301                        }
1302                        size = mPendingBroadcasts.size();
1303                        if (size <= 0) {
1304                            // Nothing to be done. Just return
1305                            return;
1306                        }
1307                        packages = new String[size];
1308                        components = new ArrayList[size];
1309                        uids = new int[size];
1310                        int i = 0;  // filling out the above arrays
1311
1312                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1313                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1314                            Iterator<Map.Entry<String, ArrayList<String>>> it
1315                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1316                                            .entrySet().iterator();
1317                            while (it.hasNext() && i < size) {
1318                                Map.Entry<String, ArrayList<String>> ent = it.next();
1319                                packages[i] = ent.getKey();
1320                                components[i] = ent.getValue();
1321                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1322                                uids[i] = (ps != null)
1323                                        ? UserHandle.getUid(packageUserId, ps.appId)
1324                                        : -1;
1325                                i++;
1326                            }
1327                        }
1328                        size = i;
1329                        mPendingBroadcasts.clear();
1330                    }
1331                    // Send broadcasts
1332                    for (int i = 0; i < size; i++) {
1333                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1334                    }
1335                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336                    break;
1337                }
1338                case START_CLEANING_PACKAGE: {
1339                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1340                    final String packageName = (String)msg.obj;
1341                    final int userId = msg.arg1;
1342                    final boolean andCode = msg.arg2 != 0;
1343                    synchronized (mPackages) {
1344                        if (userId == UserHandle.USER_ALL) {
1345                            int[] users = sUserManager.getUserIds();
1346                            for (int user : users) {
1347                                mSettings.addPackageToCleanLPw(
1348                                        new PackageCleanItem(user, packageName, andCode));
1349                            }
1350                        } else {
1351                            mSettings.addPackageToCleanLPw(
1352                                    new PackageCleanItem(userId, packageName, andCode));
1353                        }
1354                    }
1355                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1356                    startCleaningPackages();
1357                } break;
1358                case POST_INSTALL: {
1359                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1360                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1361                    mRunningInstalls.delete(msg.arg1);
1362                    boolean deleteOld = false;
1363
1364                    if (data != null) {
1365                        InstallArgs args = data.args;
1366                        PackageInstalledInfo res = data.res;
1367
1368                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1369                            final String packageName = res.pkg.applicationInfo.packageName;
1370                            res.removedInfo.sendBroadcast(false, true, false);
1371                            Bundle extras = new Bundle(1);
1372                            extras.putInt(Intent.EXTRA_UID, res.uid);
1373
1374                            // Now that we successfully installed the package, grant runtime
1375                            // permissions if requested before broadcasting the install.
1376                            if ((args.installFlags
1377                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1378                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1379                                        args.installGrantPermissions);
1380                            }
1381
1382                            // Determine the set of users who are adding this
1383                            // package for the first time vs. those who are seeing
1384                            // an update.
1385                            int[] firstUsers;
1386                            int[] updateUsers = new int[0];
1387                            if (res.origUsers == null || res.origUsers.length == 0) {
1388                                firstUsers = res.newUsers;
1389                            } else {
1390                                firstUsers = new int[0];
1391                                for (int i=0; i<res.newUsers.length; i++) {
1392                                    int user = res.newUsers[i];
1393                                    boolean isNew = true;
1394                                    for (int j=0; j<res.origUsers.length; j++) {
1395                                        if (res.origUsers[j] == user) {
1396                                            isNew = false;
1397                                            break;
1398                                        }
1399                                    }
1400                                    if (isNew) {
1401                                        int[] newFirst = new int[firstUsers.length+1];
1402                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1403                                                firstUsers.length);
1404                                        newFirst[firstUsers.length] = user;
1405                                        firstUsers = newFirst;
1406                                    } else {
1407                                        int[] newUpdate = new int[updateUsers.length+1];
1408                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1409                                                updateUsers.length);
1410                                        newUpdate[updateUsers.length] = user;
1411                                        updateUsers = newUpdate;
1412                                    }
1413                                }
1414                            }
1415                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1416                                    packageName, extras, null, null, firstUsers);
1417                            final boolean update = res.removedInfo.removedPackage != null;
1418                            if (update) {
1419                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1420                            }
1421                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1422                                    packageName, extras, null, null, updateUsers);
1423                            if (update) {
1424                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1425                                        packageName, extras, null, null, updateUsers);
1426                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1427                                        null, null, packageName, null, updateUsers);
1428
1429                                // treat asec-hosted packages like removable media on upgrade
1430                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1431                                    if (DEBUG_INSTALL) {
1432                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1433                                                + " is ASEC-hosted -> AVAILABLE");
1434                                    }
1435                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1436                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1437                                    pkgList.add(packageName);
1438                                    sendResourcesChangedBroadcast(true, true,
1439                                            pkgList,uidArray, null);
1440                                }
1441                            }
1442                            if (res.removedInfo.args != null) {
1443                                // Remove the replaced package's older resources safely now
1444                                deleteOld = true;
1445                            }
1446
1447                            // If this app is a browser and it's newly-installed for some
1448                            // users, clear any default-browser state in those users
1449                            if (firstUsers.length > 0) {
1450                                // the app's nature doesn't depend on the user, so we can just
1451                                // check its browser nature in any user and generalize.
1452                                if (packageIsBrowser(packageName, firstUsers[0])) {
1453                                    synchronized (mPackages) {
1454                                        for (int userId : firstUsers) {
1455                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1456                                        }
1457                                    }
1458                                }
1459                            }
1460                            // Log current value of "unknown sources" setting
1461                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1462                                getUnknownSourcesSettings());
1463                        }
1464                        // Force a gc to clear up things
1465                        Runtime.getRuntime().gc();
1466                        // We delete after a gc for applications  on sdcard.
1467                        if (deleteOld) {
1468                            synchronized (mInstallLock) {
1469                                res.removedInfo.args.doPostDeleteLI(true);
1470                            }
1471                        }
1472                        if (args.observer != null) {
1473                            try {
1474                                Bundle extras = extrasForInstallResult(res);
1475                                args.observer.onPackageInstalled(res.name, res.returnCode,
1476                                        res.returnMsg, extras);
1477                            } catch (RemoteException e) {
1478                                Slog.i(TAG, "Observer no longer exists.");
1479                            }
1480                        }
1481                        if (args.traceMethod != null) {
1482                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1483                                    args.traceCookie);
1484                        }
1485                        return;
1486                    } else {
1487                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1488                    }
1489
1490                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1491                } break;
1492                case UPDATED_MEDIA_STATUS: {
1493                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1494                    boolean reportStatus = msg.arg1 == 1;
1495                    boolean doGc = msg.arg2 == 1;
1496                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1497                    if (doGc) {
1498                        // Force a gc to clear up stale containers.
1499                        Runtime.getRuntime().gc();
1500                    }
1501                    if (msg.obj != null) {
1502                        @SuppressWarnings("unchecked")
1503                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1504                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1505                        // Unload containers
1506                        unloadAllContainers(args);
1507                    }
1508                    if (reportStatus) {
1509                        try {
1510                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1511                            PackageHelper.getMountService().finishMediaUpdate();
1512                        } catch (RemoteException e) {
1513                            Log.e(TAG, "MountService not running?");
1514                        }
1515                    }
1516                } break;
1517                case WRITE_SETTINGS: {
1518                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1519                    synchronized (mPackages) {
1520                        removeMessages(WRITE_SETTINGS);
1521                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1522                        mSettings.writeLPr();
1523                        mDirtyUsers.clear();
1524                    }
1525                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1526                } break;
1527                case WRITE_PACKAGE_RESTRICTIONS: {
1528                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1529                    synchronized (mPackages) {
1530                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1531                        for (int userId : mDirtyUsers) {
1532                            mSettings.writePackageRestrictionsLPr(userId);
1533                        }
1534                        mDirtyUsers.clear();
1535                    }
1536                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1537                } break;
1538                case CHECK_PENDING_VERIFICATION: {
1539                    final int verificationId = msg.arg1;
1540                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1541
1542                    if ((state != null) && !state.timeoutExtended()) {
1543                        final InstallArgs args = state.getInstallArgs();
1544                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1545
1546                        Slog.i(TAG, "Verification timed out for " + originUri);
1547                        mPendingVerification.remove(verificationId);
1548
1549                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1550
1551                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1552                            Slog.i(TAG, "Continuing with installation of " + originUri);
1553                            state.setVerifierResponse(Binder.getCallingUid(),
1554                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1555                            broadcastPackageVerified(verificationId, originUri,
1556                                    PackageManager.VERIFICATION_ALLOW,
1557                                    state.getInstallArgs().getUser());
1558                            try {
1559                                ret = args.copyApk(mContainerService, true);
1560                            } catch (RemoteException e) {
1561                                Slog.e(TAG, "Could not contact the ContainerService");
1562                            }
1563                        } else {
1564                            broadcastPackageVerified(verificationId, originUri,
1565                                    PackageManager.VERIFICATION_REJECT,
1566                                    state.getInstallArgs().getUser());
1567                        }
1568
1569                        Trace.asyncTraceEnd(
1570                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1571
1572                        processPendingInstall(args, ret);
1573                        mHandler.sendEmptyMessage(MCS_UNBIND);
1574                    }
1575                    break;
1576                }
1577                case PACKAGE_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1581                    if (state == null) {
1582                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1583                        break;
1584                    }
1585
1586                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1587
1588                    state.setVerifierResponse(response.callerUid, response.code);
1589
1590                    if (state.isVerificationComplete()) {
1591                        mPendingVerification.remove(verificationId);
1592
1593                        final InstallArgs args = state.getInstallArgs();
1594                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1595
1596                        int ret;
1597                        if (state.isInstallAllowed()) {
1598                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    response.code, state.getInstallArgs().getUser());
1601                            try {
1602                                ret = args.copyApk(mContainerService, true);
1603                            } catch (RemoteException e) {
1604                                Slog.e(TAG, "Could not contact the ContainerService");
1605                            }
1606                        } else {
1607                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1608                        }
1609
1610                        Trace.asyncTraceEnd(
1611                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1612
1613                        processPendingInstall(args, ret);
1614                        mHandler.sendEmptyMessage(MCS_UNBIND);
1615                    }
1616
1617                    break;
1618                }
1619                case START_INTENT_FILTER_VERIFICATIONS: {
1620                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1621                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1622                            params.replacing, params.pkg);
1623                    break;
1624                }
1625                case INTENT_FILTER_VERIFIED: {
1626                    final int verificationId = msg.arg1;
1627
1628                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1629                            verificationId);
1630                    if (state == null) {
1631                        Slog.w(TAG, "Invalid IntentFilter verification token "
1632                                + verificationId + " received");
1633                        break;
1634                    }
1635
1636                    final int userId = state.getUserId();
1637
1638                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1639                            "Processing IntentFilter verification with token:"
1640                            + verificationId + " and userId:" + userId);
1641
1642                    final IntentFilterVerificationResponse response =
1643                            (IntentFilterVerificationResponse) msg.obj;
1644
1645                    state.setVerifierResponse(response.callerUid, response.code);
1646
1647                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1648                            "IntentFilter verification with token:" + verificationId
1649                            + " and userId:" + userId
1650                            + " is settings verifier response with response code:"
1651                            + response.code);
1652
1653                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1654                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1655                                + response.getFailedDomainsString());
1656                    }
1657
1658                    if (state.isVerificationComplete()) {
1659                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1660                    } else {
1661                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1662                                "IntentFilter verification with token:" + verificationId
1663                                + " was not said to be complete");
1664                    }
1665
1666                    break;
1667                }
1668            }
1669        }
1670    }
1671
1672    private StorageEventListener mStorageListener = new StorageEventListener() {
1673        @Override
1674        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1675            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1676                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1677                    final String volumeUuid = vol.getFsUuid();
1678
1679                    // Clean up any users or apps that were removed or recreated
1680                    // while this volume was missing
1681                    reconcileUsers(volumeUuid);
1682                    reconcileApps(volumeUuid);
1683
1684                    // Clean up any install sessions that expired or were
1685                    // cancelled while this volume was missing
1686                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1687
1688                    loadPrivatePackages(vol);
1689
1690                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1691                    unloadPrivatePackages(vol);
1692                }
1693            }
1694
1695            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1696                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1697                    updateExternalMediaStatus(true, false);
1698                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1699                    updateExternalMediaStatus(false, false);
1700                }
1701            }
1702        }
1703
1704        @Override
1705        public void onVolumeForgotten(String fsUuid) {
1706            if (TextUtils.isEmpty(fsUuid)) {
1707                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1708                return;
1709            }
1710
1711            // Remove any apps installed on the forgotten volume
1712            synchronized (mPackages) {
1713                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1714                for (PackageSetting ps : packages) {
1715                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1716                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1717                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1718                }
1719
1720                mSettings.onVolumeForgotten(fsUuid);
1721                mSettings.writeLPr();
1722            }
1723        }
1724    };
1725
1726    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1727            String[] grantedPermissions) {
1728        if (userId >= UserHandle.USER_OWNER) {
1729            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1730        } else if (userId == UserHandle.USER_ALL) {
1731            final int[] userIds;
1732            synchronized (mPackages) {
1733                userIds = UserManagerService.getInstance().getUserIds();
1734            }
1735            for (int someUserId : userIds) {
1736                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1737            }
1738        }
1739
1740        // We could have touched GID membership, so flush out packages.list
1741        synchronized (mPackages) {
1742            mSettings.writePackageListLPr();
1743        }
1744    }
1745
1746    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1747            String[] grantedPermissions) {
1748        SettingBase sb = (SettingBase) pkg.mExtras;
1749        if (sb == null) {
1750            return;
1751        }
1752
1753        PermissionsState permissionsState = sb.getPermissionsState();
1754
1755        for (String permission : pkg.requestedPermissions) {
1756            BasePermission bp = mSettings.mPermissions.get(permission);
1757            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1758                    || ArrayUtils.contains(grantedPermissions, permission))) {
1759                permissionsState.grantRuntimePermission(bp, userId);
1760            }
1761        }
1762    }
1763
1764    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1765        Bundle extras = null;
1766        switch (res.returnCode) {
1767            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1768                extras = new Bundle();
1769                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1770                        res.origPermission);
1771                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1772                        res.origPackage);
1773                break;
1774            }
1775            case PackageManager.INSTALL_SUCCEEDED: {
1776                extras = new Bundle();
1777                extras.putBoolean(Intent.EXTRA_REPLACING,
1778                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1779                break;
1780            }
1781        }
1782        return extras;
1783    }
1784
1785    void scheduleWriteSettingsLocked() {
1786        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1787            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1788        }
1789    }
1790
1791    void scheduleWritePackageRestrictionsLocked(int userId) {
1792        if (!sUserManager.exists(userId)) return;
1793        mDirtyUsers.add(userId);
1794        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1795            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1796        }
1797    }
1798
1799    public static PackageManagerService main(Context context, Installer installer,
1800            boolean factoryTest, boolean onlyCore) {
1801        PackageManagerService m = new PackageManagerService(context, installer,
1802                factoryTest, onlyCore);
1803        ServiceManager.addService("package", m);
1804        return m;
1805    }
1806
1807    static String[] splitString(String str, char sep) {
1808        int count = 1;
1809        int i = 0;
1810        while ((i=str.indexOf(sep, i)) >= 0) {
1811            count++;
1812            i++;
1813        }
1814
1815        String[] res = new String[count];
1816        i=0;
1817        count = 0;
1818        int lastI=0;
1819        while ((i=str.indexOf(sep, i)) >= 0) {
1820            res[count] = str.substring(lastI, i);
1821            count++;
1822            i++;
1823            lastI = i;
1824        }
1825        res[count] = str.substring(lastI, str.length());
1826        return res;
1827    }
1828
1829    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1830        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1831                Context.DISPLAY_SERVICE);
1832        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1833    }
1834
1835    public PackageManagerService(Context context, Installer installer,
1836            boolean factoryTest, boolean onlyCore) {
1837        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1838                SystemClock.uptimeMillis());
1839
1840        if (mSdkVersion <= 0) {
1841            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1842        }
1843
1844        mContext = context;
1845        mFactoryTest = factoryTest;
1846        mOnlyCore = onlyCore;
1847        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1848        mMetrics = new DisplayMetrics();
1849        mSettings = new Settings(mPackages);
1850        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1851                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1852        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1853                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1854        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1855                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1856        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1857                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1858        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1859                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1860        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1861                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1862
1863        // TODO: add a property to control this?
1864        long dexOptLRUThresholdInMinutes;
1865        if (mLazyDexOpt) {
1866            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1867        } else {
1868            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1869        }
1870        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1871
1872        String separateProcesses = SystemProperties.get("debug.separate_processes");
1873        if (separateProcesses != null && separateProcesses.length() > 0) {
1874            if ("*".equals(separateProcesses)) {
1875                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1876                mSeparateProcesses = null;
1877                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1878            } else {
1879                mDefParseFlags = 0;
1880                mSeparateProcesses = separateProcesses.split(",");
1881                Slog.w(TAG, "Running with debug.separate_processes: "
1882                        + separateProcesses);
1883            }
1884        } else {
1885            mDefParseFlags = 0;
1886            mSeparateProcesses = null;
1887        }
1888
1889        mInstaller = installer;
1890        mPackageDexOptimizer = new PackageDexOptimizer(this);
1891        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1892
1893        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1894                FgThread.get().getLooper());
1895
1896        getDefaultDisplayMetrics(context, mMetrics);
1897
1898        SystemConfig systemConfig = SystemConfig.getInstance();
1899        mGlobalGids = systemConfig.getGlobalGids();
1900        mSystemPermissions = systemConfig.getSystemPermissions();
1901        mAvailableFeatures = systemConfig.getAvailableFeatures();
1902
1903        synchronized (mInstallLock) {
1904        // writer
1905        synchronized (mPackages) {
1906            mHandlerThread = new ServiceThread(TAG,
1907                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1908            mHandlerThread.start();
1909            mHandler = new PackageHandler(mHandlerThread.getLooper());
1910            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1911
1912            File dataDir = Environment.getDataDirectory();
1913            mAppDataDir = new File(dataDir, "data");
1914            mAppInstallDir = new File(dataDir, "app");
1915            mAppLib32InstallDir = new File(dataDir, "app-lib");
1916            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1917            mUserAppDataDir = new File(dataDir, "user");
1918            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1919
1920            sUserManager = new UserManagerService(context, this,
1921                    mInstallLock, mPackages);
1922
1923            // Propagate permission configuration in to package manager.
1924            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1925                    = systemConfig.getPermissions();
1926            for (int i=0; i<permConfig.size(); i++) {
1927                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1928                BasePermission bp = mSettings.mPermissions.get(perm.name);
1929                if (bp == null) {
1930                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1931                    mSettings.mPermissions.put(perm.name, bp);
1932                }
1933                if (perm.gids != null) {
1934                    bp.setGids(perm.gids, perm.perUser);
1935                }
1936            }
1937
1938            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1939            for (int i=0; i<libConfig.size(); i++) {
1940                mSharedLibraries.put(libConfig.keyAt(i),
1941                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1942            }
1943
1944            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1945
1946            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1947
1948            String customResolverActivity = Resources.getSystem().getString(
1949                    R.string.config_customResolverActivity);
1950            if (TextUtils.isEmpty(customResolverActivity)) {
1951                customResolverActivity = null;
1952            } else {
1953                mCustomResolverComponentName = ComponentName.unflattenFromString(
1954                        customResolverActivity);
1955            }
1956
1957            long startTime = SystemClock.uptimeMillis();
1958
1959            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1960                    startTime);
1961
1962            // Set flag to monitor and not change apk file paths when
1963            // scanning install directories.
1964            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1965
1966            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1967
1968            /**
1969             * Add everything in the in the boot class path to the
1970             * list of process files because dexopt will have been run
1971             * if necessary during zygote startup.
1972             */
1973            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1974            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1975
1976            if (bootClassPath != null) {
1977                String[] bootClassPathElements = splitString(bootClassPath, ':');
1978                for (String element : bootClassPathElements) {
1979                    alreadyDexOpted.add(element);
1980                }
1981            } else {
1982                Slog.w(TAG, "No BOOTCLASSPATH found!");
1983            }
1984
1985            if (systemServerClassPath != null) {
1986                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1987                for (String element : systemServerClassPathElements) {
1988                    alreadyDexOpted.add(element);
1989                }
1990            } else {
1991                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1992            }
1993
1994            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1995            final String[] dexCodeInstructionSets =
1996                    getDexCodeInstructionSets(
1997                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1998
1999            /**
2000             * Ensure all external libraries have had dexopt run on them.
2001             */
2002            if (mSharedLibraries.size() > 0) {
2003                // NOTE: For now, we're compiling these system "shared libraries"
2004                // (and framework jars) into all available architectures. It's possible
2005                // to compile them only when we come across an app that uses them (there's
2006                // already logic for that in scanPackageLI) but that adds some complexity.
2007                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2008                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2009                        final String lib = libEntry.path;
2010                        if (lib == null) {
2011                            continue;
2012                        }
2013
2014                        try {
2015                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2016                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2017                                alreadyDexOpted.add(lib);
2018                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false);
2019                            }
2020                        } catch (FileNotFoundException e) {
2021                            Slog.w(TAG, "Library not found: " + lib);
2022                        } catch (IOException e) {
2023                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2024                                    + e.getMessage());
2025                        }
2026                    }
2027                }
2028            }
2029
2030            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2031
2032            // Gross hack for now: we know this file doesn't contain any
2033            // code, so don't dexopt it to avoid the resulting log spew.
2034            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2035
2036            // Gross hack for now: we know this file is only part of
2037            // the boot class path for art, so don't dexopt it to
2038            // avoid the resulting log spew.
2039            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2040
2041            /**
2042             * There are a number of commands implemented in Java, which
2043             * we currently need to do the dexopt on so that they can be
2044             * run from a non-root shell.
2045             */
2046            String[] frameworkFiles = frameworkDir.list();
2047            if (frameworkFiles != null) {
2048                // TODO: We could compile these only for the most preferred ABI. We should
2049                // first double check that the dex files for these commands are not referenced
2050                // by other system apps.
2051                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2052                    for (int i=0; i<frameworkFiles.length; i++) {
2053                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2054                        String path = libPath.getPath();
2055                        // Skip the file if we already did it.
2056                        if (alreadyDexOpted.contains(path)) {
2057                            continue;
2058                        }
2059                        // Skip the file if it is not a type we want to dexopt.
2060                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2061                            continue;
2062                        }
2063                        try {
2064                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2065                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2066                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded, false);
2067                            }
2068                        } catch (FileNotFoundException e) {
2069                            Slog.w(TAG, "Jar not found: " + path);
2070                        } catch (IOException e) {
2071                            Slog.w(TAG, "Exception reading jar: " + path, e);
2072                        }
2073                    }
2074                }
2075            }
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                /**
2214                 * Remove disable package settings for any updated system
2215                 * apps that were removed via an OTA. If they're not a
2216                 * previously-updated app, remove them completely.
2217                 * Otherwise, just revoke their system-level permissions.
2218                 */
2219                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2220                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2221                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2222
2223                    String msg;
2224                    if (deletedPkg == null) {
2225                        msg = "Updated system package " + deletedAppName
2226                                + " no longer exists; wiping its data";
2227                        removeDataDirsLI(null, deletedAppName);
2228                    } else {
2229                        msg = "Updated system app + " + deletedAppName
2230                                + " no longer present; removing system privileges for "
2231                                + deletedAppName;
2232
2233                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2234
2235                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2236                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2237                    }
2238                    logCriticalInfo(Log.WARN, msg);
2239                }
2240
2241                /**
2242                 * Make sure all system apps that we expected to appear on
2243                 * the userdata partition actually showed up. If they never
2244                 * appeared, crawl back and revive the system version.
2245                 */
2246                for (int i = 0; i < mExpectingBetter.size(); i++) {
2247                    final String packageName = mExpectingBetter.keyAt(i);
2248                    if (!mPackages.containsKey(packageName)) {
2249                        final File scanFile = mExpectingBetter.valueAt(i);
2250
2251                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2252                                + " but never showed up; reverting to system");
2253
2254                        final int reparseFlags;
2255                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2256                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2257                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2258                                    | PackageParser.PARSE_IS_PRIVILEGED;
2259                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2260                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2261                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2262                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2263                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2264                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2265                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2266                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2267                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2268                        } else {
2269                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2270                            continue;
2271                        }
2272
2273                        mSettings.enableSystemPackageLPw(packageName);
2274
2275                        try {
2276                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2277                        } catch (PackageManagerException e) {
2278                            Slog.e(TAG, "Failed to parse original system package: "
2279                                    + e.getMessage());
2280                        }
2281                    }
2282                }
2283            }
2284            mExpectingBetter.clear();
2285
2286            // Now that we know all of the shared libraries, update all clients to have
2287            // the correct library paths.
2288            updateAllSharedLibrariesLPw();
2289
2290            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2291                // NOTE: We ignore potential failures here during a system scan (like
2292                // the rest of the commands above) because there's precious little we
2293                // can do about it. A settings error is reported, though.
2294                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2295                        false /* force dexopt */, false /* defer dexopt */,
2296                        false /* boot complete */);
2297            }
2298
2299            // Now that we know all the packages we are keeping,
2300            // read and update their last usage times.
2301            mPackageUsage.readLP();
2302
2303            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2304                    SystemClock.uptimeMillis());
2305            Slog.i(TAG, "Time to scan packages: "
2306                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2307                    + " seconds");
2308
2309            // If the platform SDK has changed since the last time we booted,
2310            // we need to re-grant app permission to catch any new ones that
2311            // appear.  This is really a hack, and means that apps can in some
2312            // cases get permissions that the user didn't initially explicitly
2313            // allow...  it would be nice to have some better way to handle
2314            // this situation.
2315            int updateFlags = UPDATE_PERMISSIONS_ALL;
2316            if (ver.sdkVersion != mSdkVersion) {
2317                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2318                        + mSdkVersion + "; regranting permissions for internal storage");
2319                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2320            }
2321            updatePermissionsLPw(null, null, updateFlags);
2322            ver.sdkVersion = mSdkVersion;
2323
2324            // If this is the first boot or an update from pre-M, and it is a normal
2325            // boot, then we need to initialize the default preferred apps across
2326            // all defined users.
2327            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2328                for (UserInfo user : sUserManager.getUsers(true)) {
2329                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2330                    applyFactoryDefaultBrowserLPw(user.id);
2331                    primeDomainVerificationsLPw(user.id);
2332                }
2333            }
2334
2335            // If this is first boot after an OTA, and a normal boot, then
2336            // we need to clear code cache directories.
2337            if (mIsUpgrade && !onlyCore) {
2338                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2339                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2340                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2341                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2342                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2343                    }
2344                }
2345                ver.fingerprint = Build.FINGERPRINT;
2346            }
2347
2348            checkDefaultBrowser();
2349
2350            // clear only after permissions and other defaults have been updated
2351            mExistingSystemPackages.clear();
2352            mPromoteSystemApps = false;
2353
2354            // All the changes are done during package scanning.
2355            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2356
2357            // can downgrade to reader
2358            mSettings.writeLPr();
2359
2360            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2361                    SystemClock.uptimeMillis());
2362
2363            mRequiredVerifierPackage = getRequiredVerifierLPr();
2364            mRequiredInstallerPackage = getRequiredInstallerLPr();
2365
2366            mInstallerService = new PackageInstallerService(context, this);
2367
2368            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2369            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2370                    mIntentFilterVerifierComponent);
2371
2372        } // synchronized (mPackages)
2373        } // synchronized (mInstallLock)
2374
2375        // Now after opening every single application zip, make sure they
2376        // are all flushed.  Not really needed, but keeps things nice and
2377        // tidy.
2378        Runtime.getRuntime().gc();
2379
2380        // Expose private service for system components to use.
2381        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2382    }
2383
2384    @Override
2385    public boolean isFirstBoot() {
2386        return !mRestoredSettings;
2387    }
2388
2389    @Override
2390    public boolean isOnlyCoreApps() {
2391        return mOnlyCore;
2392    }
2393
2394    @Override
2395    public boolean isUpgrade() {
2396        return mIsUpgrade;
2397    }
2398
2399    private String getRequiredVerifierLPr() {
2400        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2401        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2402                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2403
2404        String requiredVerifier = null;
2405
2406        final int N = receivers.size();
2407        for (int i = 0; i < N; i++) {
2408            final ResolveInfo info = receivers.get(i);
2409
2410            if (info.activityInfo == null) {
2411                continue;
2412            }
2413
2414            final String packageName = info.activityInfo.packageName;
2415
2416            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2417                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2418                continue;
2419            }
2420
2421            if (requiredVerifier != null) {
2422                throw new RuntimeException("There can be only one required verifier");
2423            }
2424
2425            requiredVerifier = packageName;
2426        }
2427
2428        return requiredVerifier;
2429    }
2430
2431    private String getRequiredInstallerLPr() {
2432        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2433        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2434        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2435
2436        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2437                PACKAGE_MIME_TYPE, 0, 0);
2438
2439        String requiredInstaller = null;
2440
2441        final int N = installers.size();
2442        for (int i = 0; i < N; i++) {
2443            final ResolveInfo info = installers.get(i);
2444            final String packageName = info.activityInfo.packageName;
2445
2446            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2447                continue;
2448            }
2449
2450            if (requiredInstaller != null) {
2451                throw new RuntimeException("There must be one required installer");
2452            }
2453
2454            requiredInstaller = packageName;
2455        }
2456
2457        if (requiredInstaller == null) {
2458            throw new RuntimeException("There must be one required installer");
2459        }
2460
2461        return requiredInstaller;
2462    }
2463
2464    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2465        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2466        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2467                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2468
2469        ComponentName verifierComponentName = null;
2470
2471        int priority = -1000;
2472        final int N = receivers.size();
2473        for (int i = 0; i < N; i++) {
2474            final ResolveInfo info = receivers.get(i);
2475
2476            if (info.activityInfo == null) {
2477                continue;
2478            }
2479
2480            final String packageName = info.activityInfo.packageName;
2481
2482            final PackageSetting ps = mSettings.mPackages.get(packageName);
2483            if (ps == null) {
2484                continue;
2485            }
2486
2487            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2488                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2489                continue;
2490            }
2491
2492            // Select the IntentFilterVerifier with the highest priority
2493            if (priority < info.priority) {
2494                priority = info.priority;
2495                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2496                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2497                        + verifierComponentName + " with priority: " + info.priority);
2498            }
2499        }
2500
2501        return verifierComponentName;
2502    }
2503
2504    private void primeDomainVerificationsLPw(int userId) {
2505        if (DEBUG_DOMAIN_VERIFICATION) {
2506            Slog.d(TAG, "Priming domain verifications in user " + userId);
2507        }
2508
2509        SystemConfig systemConfig = SystemConfig.getInstance();
2510        ArraySet<String> packages = systemConfig.getLinkedApps();
2511        ArraySet<String> domains = new ArraySet<String>();
2512
2513        for (String packageName : packages) {
2514            PackageParser.Package pkg = mPackages.get(packageName);
2515            if (pkg != null) {
2516                if (!pkg.isSystemApp()) {
2517                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2518                    continue;
2519                }
2520
2521                domains.clear();
2522                for (PackageParser.Activity a : pkg.activities) {
2523                    for (ActivityIntentInfo filter : a.intents) {
2524                        if (hasValidDomains(filter)) {
2525                            domains.addAll(filter.getHostsList());
2526                        }
2527                    }
2528                }
2529
2530                if (domains.size() > 0) {
2531                    if (DEBUG_DOMAIN_VERIFICATION) {
2532                        Slog.v(TAG, "      + " + packageName);
2533                    }
2534                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2535                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2536                    // and then 'always' in the per-user state actually used for intent resolution.
2537                    final IntentFilterVerificationInfo ivi;
2538                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2539                            new ArrayList<String>(domains));
2540                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2541                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2542                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2543                } else {
2544                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2545                            + "' does not handle web links");
2546                }
2547            } else {
2548                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2549            }
2550        }
2551
2552        scheduleWritePackageRestrictionsLocked(userId);
2553        scheduleWriteSettingsLocked();
2554    }
2555
2556    private void applyFactoryDefaultBrowserLPw(int userId) {
2557        // The default browser app's package name is stored in a string resource,
2558        // with a product-specific overlay used for vendor customization.
2559        String browserPkg = mContext.getResources().getString(
2560                com.android.internal.R.string.default_browser);
2561        if (!TextUtils.isEmpty(browserPkg)) {
2562            // non-empty string => required to be a known package
2563            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2564            if (ps == null) {
2565                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2566                browserPkg = null;
2567            } else {
2568                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2569            }
2570        }
2571
2572        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2573        // default.  If there's more than one, just leave everything alone.
2574        if (browserPkg == null) {
2575            calculateDefaultBrowserLPw(userId);
2576        }
2577    }
2578
2579    private void calculateDefaultBrowserLPw(int userId) {
2580        List<String> allBrowsers = resolveAllBrowserApps(userId);
2581        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2582        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2583    }
2584
2585    private List<String> resolveAllBrowserApps(int userId) {
2586        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2587        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2588                PackageManager.MATCH_ALL, userId);
2589
2590        final int count = list.size();
2591        List<String> result = new ArrayList<String>(count);
2592        for (int i=0; i<count; i++) {
2593            ResolveInfo info = list.get(i);
2594            if (info.activityInfo == null
2595                    || !info.handleAllWebDataURI
2596                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2597                    || result.contains(info.activityInfo.packageName)) {
2598                continue;
2599            }
2600            result.add(info.activityInfo.packageName);
2601        }
2602
2603        return result;
2604    }
2605
2606    private boolean packageIsBrowser(String packageName, int userId) {
2607        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2608                PackageManager.MATCH_ALL, userId);
2609        final int N = list.size();
2610        for (int i = 0; i < N; i++) {
2611            ResolveInfo info = list.get(i);
2612            if (packageName.equals(info.activityInfo.packageName)) {
2613                return true;
2614            }
2615        }
2616        return false;
2617    }
2618
2619    private void checkDefaultBrowser() {
2620        final int myUserId = UserHandle.myUserId();
2621        final String packageName = getDefaultBrowserPackageName(myUserId);
2622        if (packageName != null) {
2623            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2624            if (info == null) {
2625                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2626                synchronized (mPackages) {
2627                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2628                }
2629            }
2630        }
2631    }
2632
2633    @Override
2634    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2635            throws RemoteException {
2636        try {
2637            return super.onTransact(code, data, reply, flags);
2638        } catch (RuntimeException e) {
2639            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2640                Slog.wtf(TAG, "Package Manager Crash", e);
2641            }
2642            throw e;
2643        }
2644    }
2645
2646    void cleanupInstallFailedPackage(PackageSetting ps) {
2647        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2648
2649        removeDataDirsLI(ps.volumeUuid, ps.name);
2650        if (ps.codePath != null) {
2651            if (ps.codePath.isDirectory()) {
2652                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2653            } else {
2654                ps.codePath.delete();
2655            }
2656        }
2657        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2658            if (ps.resourcePath.isDirectory()) {
2659                FileUtils.deleteContents(ps.resourcePath);
2660            }
2661            ps.resourcePath.delete();
2662        }
2663        mSettings.removePackageLPw(ps.name);
2664    }
2665
2666    static int[] appendInts(int[] cur, int[] add) {
2667        if (add == null) return cur;
2668        if (cur == null) return add;
2669        final int N = add.length;
2670        for (int i=0; i<N; i++) {
2671            cur = appendInt(cur, add[i]);
2672        }
2673        return cur;
2674    }
2675
2676    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2677        if (!sUserManager.exists(userId)) return null;
2678        final PackageSetting ps = (PackageSetting) p.mExtras;
2679        if (ps == null) {
2680            return null;
2681        }
2682
2683        final PermissionsState permissionsState = ps.getPermissionsState();
2684
2685        final int[] gids = permissionsState.computeGids(userId);
2686        final Set<String> permissions = permissionsState.getPermissions(userId);
2687        final PackageUserState state = ps.readUserState(userId);
2688
2689        return PackageParser.generatePackageInfo(p, gids, flags,
2690                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2691    }
2692
2693    @Override
2694    public boolean isPackageFrozen(String packageName) {
2695        synchronized (mPackages) {
2696            final PackageSetting ps = mSettings.mPackages.get(packageName);
2697            if (ps != null) {
2698                return ps.frozen;
2699            }
2700        }
2701        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2702        return true;
2703    }
2704
2705    @Override
2706    public boolean isPackageAvailable(String packageName, int userId) {
2707        if (!sUserManager.exists(userId)) return false;
2708        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2709        synchronized (mPackages) {
2710            PackageParser.Package p = mPackages.get(packageName);
2711            if (p != null) {
2712                final PackageSetting ps = (PackageSetting) p.mExtras;
2713                if (ps != null) {
2714                    final PackageUserState state = ps.readUserState(userId);
2715                    if (state != null) {
2716                        return PackageParser.isAvailable(state);
2717                    }
2718                }
2719            }
2720        }
2721        return false;
2722    }
2723
2724    @Override
2725    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2726        if (!sUserManager.exists(userId)) return null;
2727        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2728        // reader
2729        synchronized (mPackages) {
2730            PackageParser.Package p = mPackages.get(packageName);
2731            if (DEBUG_PACKAGE_INFO)
2732                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2733            if (p != null) {
2734                return generatePackageInfo(p, flags, userId);
2735            }
2736            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2737                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2738            }
2739        }
2740        return null;
2741    }
2742
2743    @Override
2744    public String[] currentToCanonicalPackageNames(String[] names) {
2745        String[] out = new String[names.length];
2746        // reader
2747        synchronized (mPackages) {
2748            for (int i=names.length-1; i>=0; i--) {
2749                PackageSetting ps = mSettings.mPackages.get(names[i]);
2750                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2751            }
2752        }
2753        return out;
2754    }
2755
2756    @Override
2757    public String[] canonicalToCurrentPackageNames(String[] names) {
2758        String[] out = new String[names.length];
2759        // reader
2760        synchronized (mPackages) {
2761            for (int i=names.length-1; i>=0; i--) {
2762                String cur = mSettings.mRenamedPackages.get(names[i]);
2763                out[i] = cur != null ? cur : names[i];
2764            }
2765        }
2766        return out;
2767    }
2768
2769    @Override
2770    public int getPackageUid(String packageName, int userId) {
2771        if (!sUserManager.exists(userId)) return -1;
2772        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2773
2774        // reader
2775        synchronized (mPackages) {
2776            PackageParser.Package p = mPackages.get(packageName);
2777            if(p != null) {
2778                return UserHandle.getUid(userId, p.applicationInfo.uid);
2779            }
2780            PackageSetting ps = mSettings.mPackages.get(packageName);
2781            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2782                return -1;
2783            }
2784            p = ps.pkg;
2785            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2786        }
2787    }
2788
2789    @Override
2790    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2791        if (!sUserManager.exists(userId)) {
2792            return null;
2793        }
2794
2795        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2796                "getPackageGids");
2797
2798        // reader
2799        synchronized (mPackages) {
2800            PackageParser.Package p = mPackages.get(packageName);
2801            if (DEBUG_PACKAGE_INFO) {
2802                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2803            }
2804            if (p != null) {
2805                PackageSetting ps = (PackageSetting) p.mExtras;
2806                return ps.getPermissionsState().computeGids(userId);
2807            }
2808        }
2809
2810        return null;
2811    }
2812
2813    static PermissionInfo generatePermissionInfo(
2814            BasePermission bp, int flags) {
2815        if (bp.perm != null) {
2816            return PackageParser.generatePermissionInfo(bp.perm, flags);
2817        }
2818        PermissionInfo pi = new PermissionInfo();
2819        pi.name = bp.name;
2820        pi.packageName = bp.sourcePackage;
2821        pi.nonLocalizedLabel = bp.name;
2822        pi.protectionLevel = bp.protectionLevel;
2823        return pi;
2824    }
2825
2826    @Override
2827    public PermissionInfo getPermissionInfo(String name, int flags) {
2828        // reader
2829        synchronized (mPackages) {
2830            final BasePermission p = mSettings.mPermissions.get(name);
2831            if (p != null) {
2832                return generatePermissionInfo(p, flags);
2833            }
2834            return null;
2835        }
2836    }
2837
2838    @Override
2839    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2840        // reader
2841        synchronized (mPackages) {
2842            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2843            for (BasePermission p : mSettings.mPermissions.values()) {
2844                if (group == null) {
2845                    if (p.perm == null || p.perm.info.group == null) {
2846                        out.add(generatePermissionInfo(p, flags));
2847                    }
2848                } else {
2849                    if (p.perm != null && group.equals(p.perm.info.group)) {
2850                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2851                    }
2852                }
2853            }
2854
2855            if (out.size() > 0) {
2856                return out;
2857            }
2858            return mPermissionGroups.containsKey(group) ? out : null;
2859        }
2860    }
2861
2862    @Override
2863    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2864        // reader
2865        synchronized (mPackages) {
2866            return PackageParser.generatePermissionGroupInfo(
2867                    mPermissionGroups.get(name), flags);
2868        }
2869    }
2870
2871    @Override
2872    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2873        // reader
2874        synchronized (mPackages) {
2875            final int N = mPermissionGroups.size();
2876            ArrayList<PermissionGroupInfo> out
2877                    = new ArrayList<PermissionGroupInfo>(N);
2878            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2879                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2880            }
2881            return out;
2882        }
2883    }
2884
2885    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2886            int userId) {
2887        if (!sUserManager.exists(userId)) return null;
2888        PackageSetting ps = mSettings.mPackages.get(packageName);
2889        if (ps != null) {
2890            if (ps.pkg == null) {
2891                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2892                        flags, userId);
2893                if (pInfo != null) {
2894                    return pInfo.applicationInfo;
2895                }
2896                return null;
2897            }
2898            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2899                    ps.readUserState(userId), userId);
2900        }
2901        return null;
2902    }
2903
2904    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2905            int userId) {
2906        if (!sUserManager.exists(userId)) return null;
2907        PackageSetting ps = mSettings.mPackages.get(packageName);
2908        if (ps != null) {
2909            PackageParser.Package pkg = ps.pkg;
2910            if (pkg == null) {
2911                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2912                    return null;
2913                }
2914                // Only data remains, so we aren't worried about code paths
2915                pkg = new PackageParser.Package(packageName);
2916                pkg.applicationInfo.packageName = packageName;
2917                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2918                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2919                pkg.applicationInfo.dataDir = Environment
2920                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2921                        .getAbsolutePath();
2922                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2923                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2924            }
2925            return generatePackageInfo(pkg, flags, userId);
2926        }
2927        return null;
2928    }
2929
2930    @Override
2931    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2932        if (!sUserManager.exists(userId)) return null;
2933        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2934        // writer
2935        synchronized (mPackages) {
2936            PackageParser.Package p = mPackages.get(packageName);
2937            if (DEBUG_PACKAGE_INFO) Log.v(
2938                    TAG, "getApplicationInfo " + packageName
2939                    + ": " + p);
2940            if (p != null) {
2941                PackageSetting ps = mSettings.mPackages.get(packageName);
2942                if (ps == null) return null;
2943                // Note: isEnabledLP() does not apply here - always return info
2944                return PackageParser.generateApplicationInfo(
2945                        p, flags, ps.readUserState(userId), userId);
2946            }
2947            if ("android".equals(packageName)||"system".equals(packageName)) {
2948                return mAndroidApplication;
2949            }
2950            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2951                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2952            }
2953        }
2954        return null;
2955    }
2956
2957    @Override
2958    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2959            final IPackageDataObserver observer) {
2960        mContext.enforceCallingOrSelfPermission(
2961                android.Manifest.permission.CLEAR_APP_CACHE, null);
2962        // Queue up an async operation since clearing cache may take a little while.
2963        mHandler.post(new Runnable() {
2964            public void run() {
2965                mHandler.removeCallbacks(this);
2966                int retCode = -1;
2967                synchronized (mInstallLock) {
2968                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2969                    if (retCode < 0) {
2970                        Slog.w(TAG, "Couldn't clear application caches");
2971                    }
2972                }
2973                if (observer != null) {
2974                    try {
2975                        observer.onRemoveCompleted(null, (retCode >= 0));
2976                    } catch (RemoteException e) {
2977                        Slog.w(TAG, "RemoveException when invoking call back");
2978                    }
2979                }
2980            }
2981        });
2982    }
2983
2984    @Override
2985    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2986            final IntentSender pi) {
2987        mContext.enforceCallingOrSelfPermission(
2988                android.Manifest.permission.CLEAR_APP_CACHE, null);
2989        // Queue up an async operation since clearing cache may take a little while.
2990        mHandler.post(new Runnable() {
2991            public void run() {
2992                mHandler.removeCallbacks(this);
2993                int retCode = -1;
2994                synchronized (mInstallLock) {
2995                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2996                    if (retCode < 0) {
2997                        Slog.w(TAG, "Couldn't clear application caches");
2998                    }
2999                }
3000                if(pi != null) {
3001                    try {
3002                        // Callback via pending intent
3003                        int code = (retCode >= 0) ? 1 : 0;
3004                        pi.sendIntent(null, code, null,
3005                                null, null);
3006                    } catch (SendIntentException e1) {
3007                        Slog.i(TAG, "Failed to send pending intent");
3008                    }
3009                }
3010            }
3011        });
3012    }
3013
3014    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3015        synchronized (mInstallLock) {
3016            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3017                throw new IOException("Failed to free enough space");
3018            }
3019        }
3020    }
3021
3022    @Override
3023    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3024        if (!sUserManager.exists(userId)) return null;
3025        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3026        synchronized (mPackages) {
3027            PackageParser.Activity a = mActivities.mActivities.get(component);
3028
3029            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3030            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3031                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3032                if (ps == null) return null;
3033                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3034                        userId);
3035            }
3036            if (mResolveComponentName.equals(component)) {
3037                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3038                        new PackageUserState(), userId);
3039            }
3040        }
3041        return null;
3042    }
3043
3044    @Override
3045    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3046            String resolvedType) {
3047        synchronized (mPackages) {
3048            if (component.equals(mResolveComponentName)) {
3049                // The resolver supports EVERYTHING!
3050                return true;
3051            }
3052            PackageParser.Activity a = mActivities.mActivities.get(component);
3053            if (a == null) {
3054                return false;
3055            }
3056            for (int i=0; i<a.intents.size(); i++) {
3057                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3058                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3059                    return true;
3060                }
3061            }
3062            return false;
3063        }
3064    }
3065
3066    @Override
3067    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3068        if (!sUserManager.exists(userId)) return null;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3070        synchronized (mPackages) {
3071            PackageParser.Activity a = mReceivers.mActivities.get(component);
3072            if (DEBUG_PACKAGE_INFO) Log.v(
3073                TAG, "getReceiverInfo " + component + ": " + a);
3074            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3075                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3076                if (ps == null) return null;
3077                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3078                        userId);
3079            }
3080        }
3081        return null;
3082    }
3083
3084    @Override
3085    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3086        if (!sUserManager.exists(userId)) return null;
3087        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3088        synchronized (mPackages) {
3089            PackageParser.Service s = mServices.mServices.get(component);
3090            if (DEBUG_PACKAGE_INFO) Log.v(
3091                TAG, "getServiceInfo " + component + ": " + s);
3092            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3093                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3094                if (ps == null) return null;
3095                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3096                        userId);
3097            }
3098        }
3099        return null;
3100    }
3101
3102    @Override
3103    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3104        if (!sUserManager.exists(userId)) return null;
3105        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3106        synchronized (mPackages) {
3107            PackageParser.Provider p = mProviders.mProviders.get(component);
3108            if (DEBUG_PACKAGE_INFO) Log.v(
3109                TAG, "getProviderInfo " + component + ": " + p);
3110            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3111                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3112                if (ps == null) return null;
3113                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3114                        userId);
3115            }
3116        }
3117        return null;
3118    }
3119
3120    @Override
3121    public String[] getSystemSharedLibraryNames() {
3122        Set<String> libSet;
3123        synchronized (mPackages) {
3124            libSet = mSharedLibraries.keySet();
3125            int size = libSet.size();
3126            if (size > 0) {
3127                String[] libs = new String[size];
3128                libSet.toArray(libs);
3129                return libs;
3130            }
3131        }
3132        return null;
3133    }
3134
3135    /**
3136     * @hide
3137     */
3138    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3139        synchronized (mPackages) {
3140            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3141            if (lib != null && lib.apk != null) {
3142                return mPackages.get(lib.apk);
3143            }
3144        }
3145        return null;
3146    }
3147
3148    @Override
3149    public FeatureInfo[] getSystemAvailableFeatures() {
3150        Collection<FeatureInfo> featSet;
3151        synchronized (mPackages) {
3152            featSet = mAvailableFeatures.values();
3153            int size = featSet.size();
3154            if (size > 0) {
3155                FeatureInfo[] features = new FeatureInfo[size+1];
3156                featSet.toArray(features);
3157                FeatureInfo fi = new FeatureInfo();
3158                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3159                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3160                features[size] = fi;
3161                return features;
3162            }
3163        }
3164        return null;
3165    }
3166
3167    @Override
3168    public boolean hasSystemFeature(String name) {
3169        synchronized (mPackages) {
3170            return mAvailableFeatures.containsKey(name);
3171        }
3172    }
3173
3174    private void checkValidCaller(int uid, int userId) {
3175        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3176            return;
3177
3178        throw new SecurityException("Caller uid=" + uid
3179                + " is not privileged to communicate with user=" + userId);
3180    }
3181
3182    @Override
3183    public int checkPermission(String permName, String pkgName, int userId) {
3184        if (!sUserManager.exists(userId)) {
3185            return PackageManager.PERMISSION_DENIED;
3186        }
3187
3188        synchronized (mPackages) {
3189            final PackageParser.Package p = mPackages.get(pkgName);
3190            if (p != null && p.mExtras != null) {
3191                final PackageSetting ps = (PackageSetting) p.mExtras;
3192                final PermissionsState permissionsState = ps.getPermissionsState();
3193                if (permissionsState.hasPermission(permName, userId)) {
3194                    return PackageManager.PERMISSION_GRANTED;
3195                }
3196                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3197                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3198                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3199                    return PackageManager.PERMISSION_GRANTED;
3200                }
3201            }
3202        }
3203
3204        return PackageManager.PERMISSION_DENIED;
3205    }
3206
3207    @Override
3208    public int checkUidPermission(String permName, int uid) {
3209        final int userId = UserHandle.getUserId(uid);
3210
3211        if (!sUserManager.exists(userId)) {
3212            return PackageManager.PERMISSION_DENIED;
3213        }
3214
3215        synchronized (mPackages) {
3216            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3217            if (obj != null) {
3218                final SettingBase ps = (SettingBase) obj;
3219                final PermissionsState permissionsState = ps.getPermissionsState();
3220                if (permissionsState.hasPermission(permName, userId)) {
3221                    return PackageManager.PERMISSION_GRANTED;
3222                }
3223                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3224                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3225                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3226                    return PackageManager.PERMISSION_GRANTED;
3227                }
3228            } else {
3229                ArraySet<String> perms = mSystemPermissions.get(uid);
3230                if (perms != null) {
3231                    if (perms.contains(permName)) {
3232                        return PackageManager.PERMISSION_GRANTED;
3233                    }
3234                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3235                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3236                        return PackageManager.PERMISSION_GRANTED;
3237                    }
3238                }
3239            }
3240        }
3241
3242        return PackageManager.PERMISSION_DENIED;
3243    }
3244
3245    @Override
3246    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3247        if (UserHandle.getCallingUserId() != userId) {
3248            mContext.enforceCallingPermission(
3249                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3250                    "isPermissionRevokedByPolicy for user " + userId);
3251        }
3252
3253        if (checkPermission(permission, packageName, userId)
3254                == PackageManager.PERMISSION_GRANTED) {
3255            return false;
3256        }
3257
3258        final long identity = Binder.clearCallingIdentity();
3259        try {
3260            final int flags = getPermissionFlags(permission, packageName, userId);
3261            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3262        } finally {
3263            Binder.restoreCallingIdentity(identity);
3264        }
3265    }
3266
3267    @Override
3268    public String getPermissionControllerPackageName() {
3269        synchronized (mPackages) {
3270            return mRequiredInstallerPackage;
3271        }
3272    }
3273
3274    /**
3275     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3276     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3277     * @param checkShell TODO(yamasani):
3278     * @param message the message to log on security exception
3279     */
3280    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3281            boolean checkShell, String message) {
3282        if (userId < 0) {
3283            throw new IllegalArgumentException("Invalid userId " + userId);
3284        }
3285        if (checkShell) {
3286            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3287        }
3288        if (userId == UserHandle.getUserId(callingUid)) return;
3289        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3290            if (requireFullPermission) {
3291                mContext.enforceCallingOrSelfPermission(
3292                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3293            } else {
3294                try {
3295                    mContext.enforceCallingOrSelfPermission(
3296                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3297                } catch (SecurityException se) {
3298                    mContext.enforceCallingOrSelfPermission(
3299                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3300                }
3301            }
3302        }
3303    }
3304
3305    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3306        if (callingUid == Process.SHELL_UID) {
3307            if (userHandle >= 0
3308                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3309                throw new SecurityException("Shell does not have permission to access user "
3310                        + userHandle);
3311            } else if (userHandle < 0) {
3312                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3313                        + Debug.getCallers(3));
3314            }
3315        }
3316    }
3317
3318    private BasePermission findPermissionTreeLP(String permName) {
3319        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3320            if (permName.startsWith(bp.name) &&
3321                    permName.length() > bp.name.length() &&
3322                    permName.charAt(bp.name.length()) == '.') {
3323                return bp;
3324            }
3325        }
3326        return null;
3327    }
3328
3329    private BasePermission checkPermissionTreeLP(String permName) {
3330        if (permName != null) {
3331            BasePermission bp = findPermissionTreeLP(permName);
3332            if (bp != null) {
3333                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3334                    return bp;
3335                }
3336                throw new SecurityException("Calling uid "
3337                        + Binder.getCallingUid()
3338                        + " is not allowed to add to permission tree "
3339                        + bp.name + " owned by uid " + bp.uid);
3340            }
3341        }
3342        throw new SecurityException("No permission tree found for " + permName);
3343    }
3344
3345    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3346        if (s1 == null) {
3347            return s2 == null;
3348        }
3349        if (s2 == null) {
3350            return false;
3351        }
3352        if (s1.getClass() != s2.getClass()) {
3353            return false;
3354        }
3355        return s1.equals(s2);
3356    }
3357
3358    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3359        if (pi1.icon != pi2.icon) return false;
3360        if (pi1.logo != pi2.logo) return false;
3361        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3362        if (!compareStrings(pi1.name, pi2.name)) return false;
3363        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3364        // We'll take care of setting this one.
3365        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3366        // These are not currently stored in settings.
3367        //if (!compareStrings(pi1.group, pi2.group)) return false;
3368        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3369        //if (pi1.labelRes != pi2.labelRes) return false;
3370        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3371        return true;
3372    }
3373
3374    int permissionInfoFootprint(PermissionInfo info) {
3375        int size = info.name.length();
3376        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3377        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3378        return size;
3379    }
3380
3381    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3382        int size = 0;
3383        for (BasePermission perm : mSettings.mPermissions.values()) {
3384            if (perm.uid == tree.uid) {
3385                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3386            }
3387        }
3388        return size;
3389    }
3390
3391    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3392        // We calculate the max size of permissions defined by this uid and throw
3393        // if that plus the size of 'info' would exceed our stated maximum.
3394        if (tree.uid != Process.SYSTEM_UID) {
3395            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3396            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3397                throw new SecurityException("Permission tree size cap exceeded");
3398            }
3399        }
3400    }
3401
3402    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3403        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3404            throw new SecurityException("Label must be specified in permission");
3405        }
3406        BasePermission tree = checkPermissionTreeLP(info.name);
3407        BasePermission bp = mSettings.mPermissions.get(info.name);
3408        boolean added = bp == null;
3409        boolean changed = true;
3410        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3411        if (added) {
3412            enforcePermissionCapLocked(info, tree);
3413            bp = new BasePermission(info.name, tree.sourcePackage,
3414                    BasePermission.TYPE_DYNAMIC);
3415        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3416            throw new SecurityException(
3417                    "Not allowed to modify non-dynamic permission "
3418                    + info.name);
3419        } else {
3420            if (bp.protectionLevel == fixedLevel
3421                    && bp.perm.owner.equals(tree.perm.owner)
3422                    && bp.uid == tree.uid
3423                    && comparePermissionInfos(bp.perm.info, info)) {
3424                changed = false;
3425            }
3426        }
3427        bp.protectionLevel = fixedLevel;
3428        info = new PermissionInfo(info);
3429        info.protectionLevel = fixedLevel;
3430        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3431        bp.perm.info.packageName = tree.perm.info.packageName;
3432        bp.uid = tree.uid;
3433        if (added) {
3434            mSettings.mPermissions.put(info.name, bp);
3435        }
3436        if (changed) {
3437            if (!async) {
3438                mSettings.writeLPr();
3439            } else {
3440                scheduleWriteSettingsLocked();
3441            }
3442        }
3443        return added;
3444    }
3445
3446    @Override
3447    public boolean addPermission(PermissionInfo info) {
3448        synchronized (mPackages) {
3449            return addPermissionLocked(info, false);
3450        }
3451    }
3452
3453    @Override
3454    public boolean addPermissionAsync(PermissionInfo info) {
3455        synchronized (mPackages) {
3456            return addPermissionLocked(info, true);
3457        }
3458    }
3459
3460    @Override
3461    public void removePermission(String name) {
3462        synchronized (mPackages) {
3463            checkPermissionTreeLP(name);
3464            BasePermission bp = mSettings.mPermissions.get(name);
3465            if (bp != null) {
3466                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3467                    throw new SecurityException(
3468                            "Not allowed to modify non-dynamic permission "
3469                            + name);
3470                }
3471                mSettings.mPermissions.remove(name);
3472                mSettings.writeLPr();
3473            }
3474        }
3475    }
3476
3477    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3478            BasePermission bp) {
3479        int index = pkg.requestedPermissions.indexOf(bp.name);
3480        if (index == -1) {
3481            throw new SecurityException("Package " + pkg.packageName
3482                    + " has not requested permission " + bp.name);
3483        }
3484        if (!bp.isRuntime() && !bp.isDevelopment()) {
3485            throw new SecurityException("Permission " + bp.name
3486                    + " is not a changeable permission type");
3487        }
3488    }
3489
3490    @Override
3491    public void grantRuntimePermission(String packageName, String name, final int userId) {
3492        if (!sUserManager.exists(userId)) {
3493            Log.e(TAG, "No such user:" + userId);
3494            return;
3495        }
3496
3497        mContext.enforceCallingOrSelfPermission(
3498                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3499                "grantRuntimePermission");
3500
3501        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3502                "grantRuntimePermission");
3503
3504        final int uid;
3505        final SettingBase sb;
3506
3507        synchronized (mPackages) {
3508            final PackageParser.Package pkg = mPackages.get(packageName);
3509            if (pkg == null) {
3510                throw new IllegalArgumentException("Unknown package: " + packageName);
3511            }
3512
3513            final BasePermission bp = mSettings.mPermissions.get(name);
3514            if (bp == null) {
3515                throw new IllegalArgumentException("Unknown permission: " + name);
3516            }
3517
3518            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3519
3520            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3521            sb = (SettingBase) pkg.mExtras;
3522            if (sb == null) {
3523                throw new IllegalArgumentException("Unknown package: " + packageName);
3524            }
3525
3526            final PermissionsState permissionsState = sb.getPermissionsState();
3527
3528            final int flags = permissionsState.getPermissionFlags(name, userId);
3529            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3530                throw new SecurityException("Cannot grant system fixed permission: "
3531                        + name + " for package: " + packageName);
3532            }
3533
3534            if (bp.isDevelopment()) {
3535                // Development permissions must be handled specially, since they are not
3536                // normal runtime permissions.  For now they apply to all users.
3537                if (permissionsState.grantInstallPermission(bp) !=
3538                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3539                    scheduleWriteSettingsLocked();
3540                }
3541                return;
3542            }
3543
3544            final int result = permissionsState.grantRuntimePermission(bp, userId);
3545            switch (result) {
3546                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3547                    return;
3548                }
3549
3550                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3551                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3552                    mHandler.post(new Runnable() {
3553                        @Override
3554                        public void run() {
3555                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3556                        }
3557                    });
3558                } break;
3559            }
3560
3561            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3562
3563            // Not critical if that is lost - app has to request again.
3564            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3565        }
3566
3567        // Only need to do this if user is initialized. Otherwise it's a new user
3568        // and there are no processes running as the user yet and there's no need
3569        // to make an expensive call to remount processes for the changed permissions.
3570        if (READ_EXTERNAL_STORAGE.equals(name)
3571                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3572            final long token = Binder.clearCallingIdentity();
3573            try {
3574                if (sUserManager.isInitialized(userId)) {
3575                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3576                            MountServiceInternal.class);
3577                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3578                }
3579            } finally {
3580                Binder.restoreCallingIdentity(token);
3581            }
3582        }
3583    }
3584
3585    @Override
3586    public void revokeRuntimePermission(String packageName, String name, int userId) {
3587        if (!sUserManager.exists(userId)) {
3588            Log.e(TAG, "No such user:" + userId);
3589            return;
3590        }
3591
3592        mContext.enforceCallingOrSelfPermission(
3593                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3594                "revokeRuntimePermission");
3595
3596        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3597                "revokeRuntimePermission");
3598
3599        final int appId;
3600
3601        synchronized (mPackages) {
3602            final PackageParser.Package pkg = mPackages.get(packageName);
3603            if (pkg == null) {
3604                throw new IllegalArgumentException("Unknown package: " + packageName);
3605            }
3606
3607            final BasePermission bp = mSettings.mPermissions.get(name);
3608            if (bp == null) {
3609                throw new IllegalArgumentException("Unknown permission: " + name);
3610            }
3611
3612            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3613
3614            SettingBase sb = (SettingBase) pkg.mExtras;
3615            if (sb == null) {
3616                throw new IllegalArgumentException("Unknown package: " + packageName);
3617            }
3618
3619            final PermissionsState permissionsState = sb.getPermissionsState();
3620
3621            final int flags = permissionsState.getPermissionFlags(name, userId);
3622            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3623                throw new SecurityException("Cannot revoke system fixed permission: "
3624                        + name + " for package: " + packageName);
3625            }
3626
3627            if (bp.isDevelopment()) {
3628                // Development permissions must be handled specially, since they are not
3629                // normal runtime permissions.  For now they apply to all users.
3630                if (permissionsState.revokeInstallPermission(bp) !=
3631                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3632                    scheduleWriteSettingsLocked();
3633                }
3634                return;
3635            }
3636
3637            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3638                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3639                return;
3640            }
3641
3642            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3643
3644            // Critical, after this call app should never have the permission.
3645            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3646
3647            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3648        }
3649
3650        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3651    }
3652
3653    @Override
3654    public void resetRuntimePermissions() {
3655        mContext.enforceCallingOrSelfPermission(
3656                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3657                "revokeRuntimePermission");
3658
3659        int callingUid = Binder.getCallingUid();
3660        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3661            mContext.enforceCallingOrSelfPermission(
3662                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3663                    "resetRuntimePermissions");
3664        }
3665
3666        synchronized (mPackages) {
3667            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3668            for (int userId : UserManagerService.getInstance().getUserIds()) {
3669                final int packageCount = mPackages.size();
3670                for (int i = 0; i < packageCount; i++) {
3671                    PackageParser.Package pkg = mPackages.valueAt(i);
3672                    if (!(pkg.mExtras instanceof PackageSetting)) {
3673                        continue;
3674                    }
3675                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3676                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3677                }
3678            }
3679        }
3680    }
3681
3682    @Override
3683    public int getPermissionFlags(String name, String packageName, int userId) {
3684        if (!sUserManager.exists(userId)) {
3685            return 0;
3686        }
3687
3688        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3689
3690        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3691                "getPermissionFlags");
3692
3693        synchronized (mPackages) {
3694            final PackageParser.Package pkg = mPackages.get(packageName);
3695            if (pkg == null) {
3696                throw new IllegalArgumentException("Unknown package: " + packageName);
3697            }
3698
3699            final BasePermission bp = mSettings.mPermissions.get(name);
3700            if (bp == null) {
3701                throw new IllegalArgumentException("Unknown permission: " + name);
3702            }
3703
3704            SettingBase sb = (SettingBase) pkg.mExtras;
3705            if (sb == null) {
3706                throw new IllegalArgumentException("Unknown package: " + packageName);
3707            }
3708
3709            PermissionsState permissionsState = sb.getPermissionsState();
3710            return permissionsState.getPermissionFlags(name, userId);
3711        }
3712    }
3713
3714    @Override
3715    public void updatePermissionFlags(String name, String packageName, int flagMask,
3716            int flagValues, int userId) {
3717        if (!sUserManager.exists(userId)) {
3718            return;
3719        }
3720
3721        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3722
3723        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3724                "updatePermissionFlags");
3725
3726        // Only the system can change these flags and nothing else.
3727        if (getCallingUid() != Process.SYSTEM_UID) {
3728            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3729            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3730            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3731            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3732        }
3733
3734        synchronized (mPackages) {
3735            final PackageParser.Package pkg = mPackages.get(packageName);
3736            if (pkg == null) {
3737                throw new IllegalArgumentException("Unknown package: " + packageName);
3738            }
3739
3740            final BasePermission bp = mSettings.mPermissions.get(name);
3741            if (bp == null) {
3742                throw new IllegalArgumentException("Unknown permission: " + name);
3743            }
3744
3745            SettingBase sb = (SettingBase) pkg.mExtras;
3746            if (sb == null) {
3747                throw new IllegalArgumentException("Unknown package: " + packageName);
3748            }
3749
3750            PermissionsState permissionsState = sb.getPermissionsState();
3751
3752            // Only the package manager can change flags for system component permissions.
3753            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3754            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3755                return;
3756            }
3757
3758            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3759
3760            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3761                // Install and runtime permissions are stored in different places,
3762                // so figure out what permission changed and persist the change.
3763                if (permissionsState.getInstallPermissionState(name) != null) {
3764                    scheduleWriteSettingsLocked();
3765                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3766                        || hadState) {
3767                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3768                }
3769            }
3770        }
3771    }
3772
3773    /**
3774     * Update the permission flags for all packages and runtime permissions of a user in order
3775     * to allow device or profile owner to remove POLICY_FIXED.
3776     */
3777    @Override
3778    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3779        if (!sUserManager.exists(userId)) {
3780            return;
3781        }
3782
3783        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3784
3785        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3786                "updatePermissionFlagsForAllApps");
3787
3788        // Only the system can change system fixed flags.
3789        if (getCallingUid() != Process.SYSTEM_UID) {
3790            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3791            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3792        }
3793
3794        synchronized (mPackages) {
3795            boolean changed = false;
3796            final int packageCount = mPackages.size();
3797            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3798                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3799                SettingBase sb = (SettingBase) pkg.mExtras;
3800                if (sb == null) {
3801                    continue;
3802                }
3803                PermissionsState permissionsState = sb.getPermissionsState();
3804                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3805                        userId, flagMask, flagValues);
3806            }
3807            if (changed) {
3808                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3809            }
3810        }
3811    }
3812
3813    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3814        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3815                != PackageManager.PERMISSION_GRANTED
3816            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3817                != PackageManager.PERMISSION_GRANTED) {
3818            throw new SecurityException(message + " requires "
3819                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3820                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3821        }
3822    }
3823
3824    @Override
3825    public boolean shouldShowRequestPermissionRationale(String permissionName,
3826            String packageName, int userId) {
3827        if (UserHandle.getCallingUserId() != userId) {
3828            mContext.enforceCallingPermission(
3829                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3830                    "canShowRequestPermissionRationale for user " + userId);
3831        }
3832
3833        final int uid = getPackageUid(packageName, userId);
3834        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3835            return false;
3836        }
3837
3838        if (checkPermission(permissionName, packageName, userId)
3839                == PackageManager.PERMISSION_GRANTED) {
3840            return false;
3841        }
3842
3843        final int flags;
3844
3845        final long identity = Binder.clearCallingIdentity();
3846        try {
3847            flags = getPermissionFlags(permissionName,
3848                    packageName, userId);
3849        } finally {
3850            Binder.restoreCallingIdentity(identity);
3851        }
3852
3853        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3854                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3855                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3856
3857        if ((flags & fixedFlags) != 0) {
3858            return false;
3859        }
3860
3861        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3862    }
3863
3864    @Override
3865    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3866        mContext.enforceCallingOrSelfPermission(
3867                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3868                "addOnPermissionsChangeListener");
3869
3870        synchronized (mPackages) {
3871            mOnPermissionChangeListeners.addListenerLocked(listener);
3872        }
3873    }
3874
3875    @Override
3876    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3877        synchronized (mPackages) {
3878            mOnPermissionChangeListeners.removeListenerLocked(listener);
3879        }
3880    }
3881
3882    @Override
3883    public boolean isProtectedBroadcast(String actionName) {
3884        synchronized (mPackages) {
3885            return mProtectedBroadcasts.contains(actionName);
3886        }
3887    }
3888
3889    @Override
3890    public int checkSignatures(String pkg1, String pkg2) {
3891        synchronized (mPackages) {
3892            final PackageParser.Package p1 = mPackages.get(pkg1);
3893            final PackageParser.Package p2 = mPackages.get(pkg2);
3894            if (p1 == null || p1.mExtras == null
3895                    || p2 == null || p2.mExtras == null) {
3896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897            }
3898            return compareSignatures(p1.mSignatures, p2.mSignatures);
3899        }
3900    }
3901
3902    @Override
3903    public int checkUidSignatures(int uid1, int uid2) {
3904        // Map to base uids.
3905        uid1 = UserHandle.getAppId(uid1);
3906        uid2 = UserHandle.getAppId(uid2);
3907        // reader
3908        synchronized (mPackages) {
3909            Signature[] s1;
3910            Signature[] s2;
3911            Object obj = mSettings.getUserIdLPr(uid1);
3912            if (obj != null) {
3913                if (obj instanceof SharedUserSetting) {
3914                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3915                } else if (obj instanceof PackageSetting) {
3916                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3917                } else {
3918                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3919                }
3920            } else {
3921                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3922            }
3923            obj = mSettings.getUserIdLPr(uid2);
3924            if (obj != null) {
3925                if (obj instanceof SharedUserSetting) {
3926                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3927                } else if (obj instanceof PackageSetting) {
3928                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3929                } else {
3930                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3931                }
3932            } else {
3933                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3934            }
3935            return compareSignatures(s1, s2);
3936        }
3937    }
3938
3939    private void killUid(int appId, int userId, String reason) {
3940        final long identity = Binder.clearCallingIdentity();
3941        try {
3942            IActivityManager am = ActivityManagerNative.getDefault();
3943            if (am != null) {
3944                try {
3945                    am.killUid(appId, userId, reason);
3946                } catch (RemoteException e) {
3947                    /* ignore - same process */
3948                }
3949            }
3950        } finally {
3951            Binder.restoreCallingIdentity(identity);
3952        }
3953    }
3954
3955    /**
3956     * Compares two sets of signatures. Returns:
3957     * <br />
3958     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3959     * <br />
3960     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3961     * <br />
3962     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3963     * <br />
3964     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3965     * <br />
3966     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3967     */
3968    static int compareSignatures(Signature[] s1, Signature[] s2) {
3969        if (s1 == null) {
3970            return s2 == null
3971                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3972                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3973        }
3974
3975        if (s2 == null) {
3976            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3977        }
3978
3979        if (s1.length != s2.length) {
3980            return PackageManager.SIGNATURE_NO_MATCH;
3981        }
3982
3983        // Since both signature sets are of size 1, we can compare without HashSets.
3984        if (s1.length == 1) {
3985            return s1[0].equals(s2[0]) ?
3986                    PackageManager.SIGNATURE_MATCH :
3987                    PackageManager.SIGNATURE_NO_MATCH;
3988        }
3989
3990        ArraySet<Signature> set1 = new ArraySet<Signature>();
3991        for (Signature sig : s1) {
3992            set1.add(sig);
3993        }
3994        ArraySet<Signature> set2 = new ArraySet<Signature>();
3995        for (Signature sig : s2) {
3996            set2.add(sig);
3997        }
3998        // Make sure s2 contains all signatures in s1.
3999        if (set1.equals(set2)) {
4000            return PackageManager.SIGNATURE_MATCH;
4001        }
4002        return PackageManager.SIGNATURE_NO_MATCH;
4003    }
4004
4005    /**
4006     * If the database version for this type of package (internal storage or
4007     * external storage) is less than the version where package signatures
4008     * were updated, return true.
4009     */
4010    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4011        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4012        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4013    }
4014
4015    /**
4016     * Used for backward compatibility to make sure any packages with
4017     * certificate chains get upgraded to the new style. {@code existingSigs}
4018     * will be in the old format (since they were stored on disk from before the
4019     * system upgrade) and {@code scannedSigs} will be in the newer format.
4020     */
4021    private int compareSignaturesCompat(PackageSignatures existingSigs,
4022            PackageParser.Package scannedPkg) {
4023        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4024            return PackageManager.SIGNATURE_NO_MATCH;
4025        }
4026
4027        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4028        for (Signature sig : existingSigs.mSignatures) {
4029            existingSet.add(sig);
4030        }
4031        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4032        for (Signature sig : scannedPkg.mSignatures) {
4033            try {
4034                Signature[] chainSignatures = sig.getChainSignatures();
4035                for (Signature chainSig : chainSignatures) {
4036                    scannedCompatSet.add(chainSig);
4037                }
4038            } catch (CertificateEncodingException e) {
4039                scannedCompatSet.add(sig);
4040            }
4041        }
4042        /*
4043         * Make sure the expanded scanned set contains all signatures in the
4044         * existing one.
4045         */
4046        if (scannedCompatSet.equals(existingSet)) {
4047            // Migrate the old signatures to the new scheme.
4048            existingSigs.assignSignatures(scannedPkg.mSignatures);
4049            // The new KeySets will be re-added later in the scanning process.
4050            synchronized (mPackages) {
4051                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4052            }
4053            return PackageManager.SIGNATURE_MATCH;
4054        }
4055        return PackageManager.SIGNATURE_NO_MATCH;
4056    }
4057
4058    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4059        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4060        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4061    }
4062
4063    private int compareSignaturesRecover(PackageSignatures existingSigs,
4064            PackageParser.Package scannedPkg) {
4065        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4066            return PackageManager.SIGNATURE_NO_MATCH;
4067        }
4068
4069        String msg = null;
4070        try {
4071            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4072                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4073                        + scannedPkg.packageName);
4074                return PackageManager.SIGNATURE_MATCH;
4075            }
4076        } catch (CertificateException e) {
4077            msg = e.getMessage();
4078        }
4079
4080        logCriticalInfo(Log.INFO,
4081                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4082        return PackageManager.SIGNATURE_NO_MATCH;
4083    }
4084
4085    @Override
4086    public String[] getPackagesForUid(int uid) {
4087        uid = UserHandle.getAppId(uid);
4088        // reader
4089        synchronized (mPackages) {
4090            Object obj = mSettings.getUserIdLPr(uid);
4091            if (obj instanceof SharedUserSetting) {
4092                final SharedUserSetting sus = (SharedUserSetting) obj;
4093                final int N = sus.packages.size();
4094                final String[] res = new String[N];
4095                final Iterator<PackageSetting> it = sus.packages.iterator();
4096                int i = 0;
4097                while (it.hasNext()) {
4098                    res[i++] = it.next().name;
4099                }
4100                return res;
4101            } else if (obj instanceof PackageSetting) {
4102                final PackageSetting ps = (PackageSetting) obj;
4103                return new String[] { ps.name };
4104            }
4105        }
4106        return null;
4107    }
4108
4109    @Override
4110    public String getNameForUid(int uid) {
4111        // reader
4112        synchronized (mPackages) {
4113            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4114            if (obj instanceof SharedUserSetting) {
4115                final SharedUserSetting sus = (SharedUserSetting) obj;
4116                return sus.name + ":" + sus.userId;
4117            } else if (obj instanceof PackageSetting) {
4118                final PackageSetting ps = (PackageSetting) obj;
4119                return ps.name;
4120            }
4121        }
4122        return null;
4123    }
4124
4125    @Override
4126    public int getUidForSharedUser(String sharedUserName) {
4127        if(sharedUserName == null) {
4128            return -1;
4129        }
4130        // reader
4131        synchronized (mPackages) {
4132            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4133            if (suid == null) {
4134                return -1;
4135            }
4136            return suid.userId;
4137        }
4138    }
4139
4140    @Override
4141    public int getFlagsForUid(int uid) {
4142        synchronized (mPackages) {
4143            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4144            if (obj instanceof SharedUserSetting) {
4145                final SharedUserSetting sus = (SharedUserSetting) obj;
4146                return sus.pkgFlags;
4147            } else if (obj instanceof PackageSetting) {
4148                final PackageSetting ps = (PackageSetting) obj;
4149                return ps.pkgFlags;
4150            }
4151        }
4152        return 0;
4153    }
4154
4155    @Override
4156    public int getPrivateFlagsForUid(int uid) {
4157        synchronized (mPackages) {
4158            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4159            if (obj instanceof SharedUserSetting) {
4160                final SharedUserSetting sus = (SharedUserSetting) obj;
4161                return sus.pkgPrivateFlags;
4162            } else if (obj instanceof PackageSetting) {
4163                final PackageSetting ps = (PackageSetting) obj;
4164                return ps.pkgPrivateFlags;
4165            }
4166        }
4167        return 0;
4168    }
4169
4170    @Override
4171    public boolean isUidPrivileged(int uid) {
4172        uid = UserHandle.getAppId(uid);
4173        // reader
4174        synchronized (mPackages) {
4175            Object obj = mSettings.getUserIdLPr(uid);
4176            if (obj instanceof SharedUserSetting) {
4177                final SharedUserSetting sus = (SharedUserSetting) obj;
4178                final Iterator<PackageSetting> it = sus.packages.iterator();
4179                while (it.hasNext()) {
4180                    if (it.next().isPrivileged()) {
4181                        return true;
4182                    }
4183                }
4184            } else if (obj instanceof PackageSetting) {
4185                final PackageSetting ps = (PackageSetting) obj;
4186                return ps.isPrivileged();
4187            }
4188        }
4189        return false;
4190    }
4191
4192    @Override
4193    public String[] getAppOpPermissionPackages(String permissionName) {
4194        synchronized (mPackages) {
4195            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4196            if (pkgs == null) {
4197                return null;
4198            }
4199            return pkgs.toArray(new String[pkgs.size()]);
4200        }
4201    }
4202
4203    @Override
4204    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4205            int flags, int userId) {
4206        if (!sUserManager.exists(userId)) return null;
4207        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4208        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4209        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4210    }
4211
4212    @Override
4213    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4214            IntentFilter filter, int match, ComponentName activity) {
4215        final int userId = UserHandle.getCallingUserId();
4216        if (DEBUG_PREFERRED) {
4217            Log.v(TAG, "setLastChosenActivity intent=" + intent
4218                + " resolvedType=" + resolvedType
4219                + " flags=" + flags
4220                + " filter=" + filter
4221                + " match=" + match
4222                + " activity=" + activity);
4223            filter.dump(new PrintStreamPrinter(System.out), "    ");
4224        }
4225        intent.setComponent(null);
4226        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4227        // Find any earlier preferred or last chosen entries and nuke them
4228        findPreferredActivity(intent, resolvedType,
4229                flags, query, 0, false, true, false, userId);
4230        // Add the new activity as the last chosen for this filter
4231        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4232                "Setting last chosen");
4233    }
4234
4235    @Override
4236    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4237        final int userId = UserHandle.getCallingUserId();
4238        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4239        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4240        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4241                false, false, false, userId);
4242    }
4243
4244    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4245            int flags, List<ResolveInfo> query, int userId) {
4246        if (query != null) {
4247            final int N = query.size();
4248            if (N == 1) {
4249                return query.get(0);
4250            } else if (N > 1) {
4251                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4252                // If there is more than one activity with the same priority,
4253                // then let the user decide between them.
4254                ResolveInfo r0 = query.get(0);
4255                ResolveInfo r1 = query.get(1);
4256                if (DEBUG_INTENT_MATCHING || debug) {
4257                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4258                            + r1.activityInfo.name + "=" + r1.priority);
4259                }
4260                // If the first activity has a higher priority, or a different
4261                // default, then it is always desireable to pick it.
4262                if (r0.priority != r1.priority
4263                        || r0.preferredOrder != r1.preferredOrder
4264                        || r0.isDefault != r1.isDefault) {
4265                    return query.get(0);
4266                }
4267                // If we have saved a preference for a preferred activity for
4268                // this Intent, use that.
4269                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4270                        flags, query, r0.priority, true, false, debug, userId);
4271                if (ri != null) {
4272                    return ri;
4273                }
4274                ri = new ResolveInfo(mResolveInfo);
4275                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4276                ri.activityInfo.applicationInfo = new ApplicationInfo(
4277                        ri.activityInfo.applicationInfo);
4278                if (userId != 0) {
4279                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4280                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4281                }
4282                // Make sure that the resolver is displayable in car mode
4283                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4284                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4285                return ri;
4286            }
4287        }
4288        return null;
4289    }
4290
4291    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4292            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4293        final int N = query.size();
4294        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4295                .get(userId);
4296        // Get the list of persistent preferred activities that handle the intent
4297        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4298        List<PersistentPreferredActivity> pprefs = ppir != null
4299                ? ppir.queryIntent(intent, resolvedType,
4300                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4301                : null;
4302        if (pprefs != null && pprefs.size() > 0) {
4303            final int M = pprefs.size();
4304            for (int i=0; i<M; i++) {
4305                final PersistentPreferredActivity ppa = pprefs.get(i);
4306                if (DEBUG_PREFERRED || debug) {
4307                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4308                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4309                            + "\n  component=" + ppa.mComponent);
4310                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4311                }
4312                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4313                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4314                if (DEBUG_PREFERRED || debug) {
4315                    Slog.v(TAG, "Found persistent preferred activity:");
4316                    if (ai != null) {
4317                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4318                    } else {
4319                        Slog.v(TAG, "  null");
4320                    }
4321                }
4322                if (ai == null) {
4323                    // This previously registered persistent preferred activity
4324                    // component is no longer known. Ignore it and do NOT remove it.
4325                    continue;
4326                }
4327                for (int j=0; j<N; j++) {
4328                    final ResolveInfo ri = query.get(j);
4329                    if (!ri.activityInfo.applicationInfo.packageName
4330                            .equals(ai.applicationInfo.packageName)) {
4331                        continue;
4332                    }
4333                    if (!ri.activityInfo.name.equals(ai.name)) {
4334                        continue;
4335                    }
4336                    //  Found a persistent preference that can handle the intent.
4337                    if (DEBUG_PREFERRED || debug) {
4338                        Slog.v(TAG, "Returning persistent preferred activity: " +
4339                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4340                    }
4341                    return ri;
4342                }
4343            }
4344        }
4345        return null;
4346    }
4347
4348    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4349            List<ResolveInfo> query, int priority, boolean always,
4350            boolean removeMatches, boolean debug, int userId) {
4351        if (!sUserManager.exists(userId)) return null;
4352        // writer
4353        synchronized (mPackages) {
4354            if (intent.getSelector() != null) {
4355                intent = intent.getSelector();
4356            }
4357            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4358
4359            // Try to find a matching persistent preferred activity.
4360            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4361                    debug, userId);
4362
4363            // If a persistent preferred activity matched, use it.
4364            if (pri != null) {
4365                return pri;
4366            }
4367
4368            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4369            // Get the list of preferred activities that handle the intent
4370            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4371            List<PreferredActivity> prefs = pir != null
4372                    ? pir.queryIntent(intent, resolvedType,
4373                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4374                    : null;
4375            if (prefs != null && prefs.size() > 0) {
4376                boolean changed = false;
4377                try {
4378                    // First figure out how good the original match set is.
4379                    // We will only allow preferred activities that came
4380                    // from the same match quality.
4381                    int match = 0;
4382
4383                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4384
4385                    final int N = query.size();
4386                    for (int j=0; j<N; j++) {
4387                        final ResolveInfo ri = query.get(j);
4388                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4389                                + ": 0x" + Integer.toHexString(match));
4390                        if (ri.match > match) {
4391                            match = ri.match;
4392                        }
4393                    }
4394
4395                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4396                            + Integer.toHexString(match));
4397
4398                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4399                    final int M = prefs.size();
4400                    for (int i=0; i<M; i++) {
4401                        final PreferredActivity pa = prefs.get(i);
4402                        if (DEBUG_PREFERRED || debug) {
4403                            Slog.v(TAG, "Checking PreferredActivity ds="
4404                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4405                                    + "\n  component=" + pa.mPref.mComponent);
4406                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4407                        }
4408                        if (pa.mPref.mMatch != match) {
4409                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4410                                    + Integer.toHexString(pa.mPref.mMatch));
4411                            continue;
4412                        }
4413                        // If it's not an "always" type preferred activity and that's what we're
4414                        // looking for, skip it.
4415                        if (always && !pa.mPref.mAlways) {
4416                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4417                            continue;
4418                        }
4419                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4420                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4421                        if (DEBUG_PREFERRED || debug) {
4422                            Slog.v(TAG, "Found preferred activity:");
4423                            if (ai != null) {
4424                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4425                            } else {
4426                                Slog.v(TAG, "  null");
4427                            }
4428                        }
4429                        if (ai == null) {
4430                            // This previously registered preferred activity
4431                            // component is no longer known.  Most likely an update
4432                            // to the app was installed and in the new version this
4433                            // component no longer exists.  Clean it up by removing
4434                            // it from the preferred activities list, and skip it.
4435                            Slog.w(TAG, "Removing dangling preferred activity: "
4436                                    + pa.mPref.mComponent);
4437                            pir.removeFilter(pa);
4438                            changed = true;
4439                            continue;
4440                        }
4441                        for (int j=0; j<N; j++) {
4442                            final ResolveInfo ri = query.get(j);
4443                            if (!ri.activityInfo.applicationInfo.packageName
4444                                    .equals(ai.applicationInfo.packageName)) {
4445                                continue;
4446                            }
4447                            if (!ri.activityInfo.name.equals(ai.name)) {
4448                                continue;
4449                            }
4450
4451                            if (removeMatches) {
4452                                pir.removeFilter(pa);
4453                                changed = true;
4454                                if (DEBUG_PREFERRED) {
4455                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4456                                }
4457                                break;
4458                            }
4459
4460                            // Okay we found a previously set preferred or last chosen app.
4461                            // If the result set is different from when this
4462                            // was created, we need to clear it and re-ask the
4463                            // user their preference, if we're looking for an "always" type entry.
4464                            if (always && !pa.mPref.sameSet(query)) {
4465                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4466                                        + intent + " type " + resolvedType);
4467                                if (DEBUG_PREFERRED) {
4468                                    Slog.v(TAG, "Removing preferred activity since set changed "
4469                                            + pa.mPref.mComponent);
4470                                }
4471                                pir.removeFilter(pa);
4472                                // Re-add the filter as a "last chosen" entry (!always)
4473                                PreferredActivity lastChosen = new PreferredActivity(
4474                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4475                                pir.addFilter(lastChosen);
4476                                changed = true;
4477                                return null;
4478                            }
4479
4480                            // Yay! Either the set matched or we're looking for the last chosen
4481                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4482                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4483                            return ri;
4484                        }
4485                    }
4486                } finally {
4487                    if (changed) {
4488                        if (DEBUG_PREFERRED) {
4489                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4490                        }
4491                        scheduleWritePackageRestrictionsLocked(userId);
4492                    }
4493                }
4494            }
4495        }
4496        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4497        return null;
4498    }
4499
4500    /*
4501     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4502     */
4503    @Override
4504    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4505            int targetUserId) {
4506        mContext.enforceCallingOrSelfPermission(
4507                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4508        List<CrossProfileIntentFilter> matches =
4509                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4510        if (matches != null) {
4511            int size = matches.size();
4512            for (int i = 0; i < size; i++) {
4513                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4514            }
4515        }
4516        if (hasWebURI(intent)) {
4517            // cross-profile app linking works only towards the parent.
4518            final UserInfo parent = getProfileParent(sourceUserId);
4519            synchronized(mPackages) {
4520                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4521                        intent, resolvedType, 0, sourceUserId, parent.id);
4522                return xpDomainInfo != null;
4523            }
4524        }
4525        return false;
4526    }
4527
4528    private UserInfo getProfileParent(int userId) {
4529        final long identity = Binder.clearCallingIdentity();
4530        try {
4531            return sUserManager.getProfileParent(userId);
4532        } finally {
4533            Binder.restoreCallingIdentity(identity);
4534        }
4535    }
4536
4537    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4538            String resolvedType, int userId) {
4539        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4540        if (resolver != null) {
4541            return resolver.queryIntent(intent, resolvedType, false, userId);
4542        }
4543        return null;
4544    }
4545
4546    @Override
4547    public List<ResolveInfo> queryIntentActivities(Intent intent,
4548            String resolvedType, int flags, int userId) {
4549        if (!sUserManager.exists(userId)) return Collections.emptyList();
4550        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4551        ComponentName comp = intent.getComponent();
4552        if (comp == null) {
4553            if (intent.getSelector() != null) {
4554                intent = intent.getSelector();
4555                comp = intent.getComponent();
4556            }
4557        }
4558
4559        if (comp != null) {
4560            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4561            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4562            if (ai != null) {
4563                final ResolveInfo ri = new ResolveInfo();
4564                ri.activityInfo = ai;
4565                list.add(ri);
4566            }
4567            return list;
4568        }
4569
4570        // reader
4571        synchronized (mPackages) {
4572            final String pkgName = intent.getPackage();
4573            if (pkgName == null) {
4574                List<CrossProfileIntentFilter> matchingFilters =
4575                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4576                // Check for results that need to skip the current profile.
4577                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4578                        resolvedType, flags, userId);
4579                if (xpResolveInfo != null) {
4580                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4581                    result.add(xpResolveInfo);
4582                    return filterIfNotSystemUser(result, userId);
4583                }
4584
4585                // Check for results in the current profile.
4586                List<ResolveInfo> result = mActivities.queryIntent(
4587                        intent, resolvedType, flags, userId);
4588
4589                // Check for cross profile results.
4590                xpResolveInfo = queryCrossProfileIntents(
4591                        matchingFilters, intent, resolvedType, flags, userId);
4592                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4593                    result.add(xpResolveInfo);
4594                    Collections.sort(result, mResolvePrioritySorter);
4595                }
4596                result = filterIfNotSystemUser(result, userId);
4597                if (hasWebURI(intent)) {
4598                    CrossProfileDomainInfo xpDomainInfo = null;
4599                    final UserInfo parent = getProfileParent(userId);
4600                    if (parent != null) {
4601                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4602                                flags, userId, parent.id);
4603                    }
4604                    if (xpDomainInfo != null) {
4605                        if (xpResolveInfo != null) {
4606                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4607                            // in the result.
4608                            result.remove(xpResolveInfo);
4609                        }
4610                        if (result.size() == 0) {
4611                            result.add(xpDomainInfo.resolveInfo);
4612                            return result;
4613                        }
4614                    } else if (result.size() <= 1) {
4615                        return result;
4616                    }
4617                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4618                            xpDomainInfo, userId);
4619                    Collections.sort(result, mResolvePrioritySorter);
4620                }
4621                return result;
4622            }
4623            final PackageParser.Package pkg = mPackages.get(pkgName);
4624            if (pkg != null) {
4625                return filterIfNotSystemUser(
4626                        mActivities.queryIntentForPackage(
4627                                intent, resolvedType, flags, pkg.activities, userId),
4628                        userId);
4629            }
4630            return new ArrayList<ResolveInfo>();
4631        }
4632    }
4633
4634    private static class CrossProfileDomainInfo {
4635        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4636        ResolveInfo resolveInfo;
4637        /* Best domain verification status of the activities found in the other profile */
4638        int bestDomainVerificationStatus;
4639    }
4640
4641    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4642            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4643        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4644                sourceUserId)) {
4645            return null;
4646        }
4647        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4648                resolvedType, flags, parentUserId);
4649
4650        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4651            return null;
4652        }
4653        CrossProfileDomainInfo result = null;
4654        int size = resultTargetUser.size();
4655        for (int i = 0; i < size; i++) {
4656            ResolveInfo riTargetUser = resultTargetUser.get(i);
4657            // Intent filter verification is only for filters that specify a host. So don't return
4658            // those that handle all web uris.
4659            if (riTargetUser.handleAllWebDataURI) {
4660                continue;
4661            }
4662            String packageName = riTargetUser.activityInfo.packageName;
4663            PackageSetting ps = mSettings.mPackages.get(packageName);
4664            if (ps == null) {
4665                continue;
4666            }
4667            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4668            int status = (int)(verificationState >> 32);
4669            if (result == null) {
4670                result = new CrossProfileDomainInfo();
4671                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4672                        sourceUserId, parentUserId);
4673                result.bestDomainVerificationStatus = status;
4674            } else {
4675                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4676                        result.bestDomainVerificationStatus);
4677            }
4678        }
4679        // Don't consider matches with status NEVER across profiles.
4680        if (result != null && result.bestDomainVerificationStatus
4681                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4682            return null;
4683        }
4684        return result;
4685    }
4686
4687    /**
4688     * Verification statuses are ordered from the worse to the best, except for
4689     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4690     */
4691    private int bestDomainVerificationStatus(int status1, int status2) {
4692        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4693            return status2;
4694        }
4695        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4696            return status1;
4697        }
4698        return (int) MathUtils.max(status1, status2);
4699    }
4700
4701    private boolean isUserEnabled(int userId) {
4702        long callingId = Binder.clearCallingIdentity();
4703        try {
4704            UserInfo userInfo = sUserManager.getUserInfo(userId);
4705            return userInfo != null && userInfo.isEnabled();
4706        } finally {
4707            Binder.restoreCallingIdentity(callingId);
4708        }
4709    }
4710
4711    /**
4712     * Filter out activities with systemUserOnly flag set, when current user is not System.
4713     *
4714     * @return filtered list
4715     */
4716    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4717        if (userId == UserHandle.USER_SYSTEM) {
4718            return resolveInfos;
4719        }
4720        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4721            ResolveInfo info = resolveInfos.get(i);
4722            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4723                resolveInfos.remove(i);
4724            }
4725        }
4726        return resolveInfos;
4727    }
4728
4729    private static boolean hasWebURI(Intent intent) {
4730        if (intent.getData() == null) {
4731            return false;
4732        }
4733        final String scheme = intent.getScheme();
4734        if (TextUtils.isEmpty(scheme)) {
4735            return false;
4736        }
4737        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4738    }
4739
4740    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4741            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4742            int userId) {
4743        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4744
4745        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4746            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4747                    candidates.size());
4748        }
4749
4750        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4751        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4752        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4753        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4754        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4755        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4756
4757        synchronized (mPackages) {
4758            final int count = candidates.size();
4759            // First, try to use linked apps. Partition the candidates into four lists:
4760            // one for the final results, one for the "do not use ever", one for "undefined status"
4761            // and finally one for "browser app type".
4762            for (int n=0; n<count; n++) {
4763                ResolveInfo info = candidates.get(n);
4764                String packageName = info.activityInfo.packageName;
4765                PackageSetting ps = mSettings.mPackages.get(packageName);
4766                if (ps != null) {
4767                    // Add to the special match all list (Browser use case)
4768                    if (info.handleAllWebDataURI) {
4769                        matchAllList.add(info);
4770                        continue;
4771                    }
4772                    // Try to get the status from User settings first
4773                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4774                    int status = (int)(packedStatus >> 32);
4775                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4776                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4777                        if (DEBUG_DOMAIN_VERIFICATION) {
4778                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4779                                    + " : linkgen=" + linkGeneration);
4780                        }
4781                        // Use link-enabled generation as preferredOrder, i.e.
4782                        // prefer newly-enabled over earlier-enabled.
4783                        info.preferredOrder = linkGeneration;
4784                        alwaysList.add(info);
4785                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4786                        if (DEBUG_DOMAIN_VERIFICATION) {
4787                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4788                        }
4789                        neverList.add(info);
4790                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4791                        if (DEBUG_DOMAIN_VERIFICATION) {
4792                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4793                        }
4794                        alwaysAskList.add(info);
4795                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4796                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4797                        if (DEBUG_DOMAIN_VERIFICATION) {
4798                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4799                        }
4800                        undefinedList.add(info);
4801                    }
4802                }
4803            }
4804
4805            // We'll want to include browser possibilities in a few cases
4806            boolean includeBrowser = false;
4807
4808            // First try to add the "always" resolution(s) for the current user, if any
4809            if (alwaysList.size() > 0) {
4810                result.addAll(alwaysList);
4811            // if there is an "always" for the parent user, add it.
4812            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4813                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4814                result.add(xpDomainInfo.resolveInfo);
4815            } else {
4816                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4817                result.addAll(undefinedList);
4818                if (xpDomainInfo != null && (
4819                        xpDomainInfo.bestDomainVerificationStatus
4820                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4821                        || xpDomainInfo.bestDomainVerificationStatus
4822                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4823                    result.add(xpDomainInfo.resolveInfo);
4824                }
4825                includeBrowser = true;
4826            }
4827
4828            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4829            // If there were 'always' entries their preferred order has been set, so we also
4830            // back that off to make the alternatives equivalent
4831            if (alwaysAskList.size() > 0) {
4832                for (ResolveInfo i : result) {
4833                    i.preferredOrder = 0;
4834                }
4835                result.addAll(alwaysAskList);
4836                includeBrowser = true;
4837            }
4838
4839            if (includeBrowser) {
4840                // Also add browsers (all of them or only the default one)
4841                if (DEBUG_DOMAIN_VERIFICATION) {
4842                    Slog.v(TAG, "   ...including browsers in candidate set");
4843                }
4844                if ((matchFlags & MATCH_ALL) != 0) {
4845                    result.addAll(matchAllList);
4846                } else {
4847                    // Browser/generic handling case.  If there's a default browser, go straight
4848                    // to that (but only if there is no other higher-priority match).
4849                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4850                    int maxMatchPrio = 0;
4851                    ResolveInfo defaultBrowserMatch = null;
4852                    final int numCandidates = matchAllList.size();
4853                    for (int n = 0; n < numCandidates; n++) {
4854                        ResolveInfo info = matchAllList.get(n);
4855                        // track the highest overall match priority...
4856                        if (info.priority > maxMatchPrio) {
4857                            maxMatchPrio = info.priority;
4858                        }
4859                        // ...and the highest-priority default browser match
4860                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4861                            if (defaultBrowserMatch == null
4862                                    || (defaultBrowserMatch.priority < info.priority)) {
4863                                if (debug) {
4864                                    Slog.v(TAG, "Considering default browser match " + info);
4865                                }
4866                                defaultBrowserMatch = info;
4867                            }
4868                        }
4869                    }
4870                    if (defaultBrowserMatch != null
4871                            && defaultBrowserMatch.priority >= maxMatchPrio
4872                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4873                    {
4874                        if (debug) {
4875                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4876                        }
4877                        result.add(defaultBrowserMatch);
4878                    } else {
4879                        result.addAll(matchAllList);
4880                    }
4881                }
4882
4883                // If there is nothing selected, add all candidates and remove the ones that the user
4884                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4885                if (result.size() == 0) {
4886                    result.addAll(candidates);
4887                    result.removeAll(neverList);
4888                }
4889            }
4890        }
4891        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4892            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4893                    result.size());
4894            for (ResolveInfo info : result) {
4895                Slog.v(TAG, "  + " + info.activityInfo);
4896            }
4897        }
4898        return result;
4899    }
4900
4901    // Returns a packed value as a long:
4902    //
4903    // high 'int'-sized word: link status: undefined/ask/never/always.
4904    // low 'int'-sized word: relative priority among 'always' results.
4905    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4906        long result = ps.getDomainVerificationStatusForUser(userId);
4907        // if none available, get the master status
4908        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4909            if (ps.getIntentFilterVerificationInfo() != null) {
4910                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4911            }
4912        }
4913        return result;
4914    }
4915
4916    private ResolveInfo querySkipCurrentProfileIntents(
4917            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4918            int flags, int sourceUserId) {
4919        if (matchingFilters != null) {
4920            int size = matchingFilters.size();
4921            for (int i = 0; i < size; i ++) {
4922                CrossProfileIntentFilter filter = matchingFilters.get(i);
4923                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4924                    // Checking if there are activities in the target user that can handle the
4925                    // intent.
4926                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4927                            resolvedType, flags, sourceUserId);
4928                    if (resolveInfo != null) {
4929                        return resolveInfo;
4930                    }
4931                }
4932            }
4933        }
4934        return null;
4935    }
4936
4937    // Return matching ResolveInfo if any for skip current profile intent filters.
4938    private ResolveInfo queryCrossProfileIntents(
4939            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4940            int flags, int sourceUserId) {
4941        if (matchingFilters != null) {
4942            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4943            // match the same intent. For performance reasons, it is better not to
4944            // run queryIntent twice for the same userId
4945            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4946            int size = matchingFilters.size();
4947            for (int i = 0; i < size; i++) {
4948                CrossProfileIntentFilter filter = matchingFilters.get(i);
4949                int targetUserId = filter.getTargetUserId();
4950                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4951                        && !alreadyTriedUserIds.get(targetUserId)) {
4952                    // Checking if there are activities in the target user that can handle the
4953                    // intent.
4954                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4955                            resolvedType, flags, sourceUserId);
4956                    if (resolveInfo != null) return resolveInfo;
4957                    alreadyTriedUserIds.put(targetUserId, true);
4958                }
4959            }
4960        }
4961        return null;
4962    }
4963
4964    /**
4965     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
4966     * will forward the intent to the filter's target user.
4967     * Otherwise, returns null.
4968     */
4969    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
4970            String resolvedType, int flags, int sourceUserId) {
4971        int targetUserId = filter.getTargetUserId();
4972        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4973                resolvedType, flags, targetUserId);
4974        if (resultTargetUser != null && !resultTargetUser.isEmpty()
4975                && isUserEnabled(targetUserId)) {
4976            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
4977        }
4978        return null;
4979    }
4980
4981    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
4982            int sourceUserId, int targetUserId) {
4983        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4984        long ident = Binder.clearCallingIdentity();
4985        boolean targetIsProfile;
4986        try {
4987            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
4988        } finally {
4989            Binder.restoreCallingIdentity(ident);
4990        }
4991        String className;
4992        if (targetIsProfile) {
4993            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4994        } else {
4995            className = FORWARD_INTENT_TO_PARENT;
4996        }
4997        ComponentName forwardingActivityComponentName = new ComponentName(
4998                mAndroidApplication.packageName, className);
4999        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5000                sourceUserId);
5001        if (!targetIsProfile) {
5002            forwardingActivityInfo.showUserIcon = targetUserId;
5003            forwardingResolveInfo.noResourceId = true;
5004        }
5005        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5006        forwardingResolveInfo.priority = 0;
5007        forwardingResolveInfo.preferredOrder = 0;
5008        forwardingResolveInfo.match = 0;
5009        forwardingResolveInfo.isDefault = true;
5010        forwardingResolveInfo.filter = filter;
5011        forwardingResolveInfo.targetUserId = targetUserId;
5012        return forwardingResolveInfo;
5013    }
5014
5015    @Override
5016    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5017            Intent[] specifics, String[] specificTypes, Intent intent,
5018            String resolvedType, int flags, int userId) {
5019        if (!sUserManager.exists(userId)) return Collections.emptyList();
5020        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5021                false, "query intent activity options");
5022        final String resultsAction = intent.getAction();
5023
5024        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5025                | PackageManager.GET_RESOLVED_FILTER, userId);
5026
5027        if (DEBUG_INTENT_MATCHING) {
5028            Log.v(TAG, "Query " + intent + ": " + results);
5029        }
5030
5031        int specificsPos = 0;
5032        int N;
5033
5034        // todo: note that the algorithm used here is O(N^2).  This
5035        // isn't a problem in our current environment, but if we start running
5036        // into situations where we have more than 5 or 10 matches then this
5037        // should probably be changed to something smarter...
5038
5039        // First we go through and resolve each of the specific items
5040        // that were supplied, taking care of removing any corresponding
5041        // duplicate items in the generic resolve list.
5042        if (specifics != null) {
5043            for (int i=0; i<specifics.length; i++) {
5044                final Intent sintent = specifics[i];
5045                if (sintent == null) {
5046                    continue;
5047                }
5048
5049                if (DEBUG_INTENT_MATCHING) {
5050                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5051                }
5052
5053                String action = sintent.getAction();
5054                if (resultsAction != null && resultsAction.equals(action)) {
5055                    // If this action was explicitly requested, then don't
5056                    // remove things that have it.
5057                    action = null;
5058                }
5059
5060                ResolveInfo ri = null;
5061                ActivityInfo ai = null;
5062
5063                ComponentName comp = sintent.getComponent();
5064                if (comp == null) {
5065                    ri = resolveIntent(
5066                        sintent,
5067                        specificTypes != null ? specificTypes[i] : null,
5068                            flags, userId);
5069                    if (ri == null) {
5070                        continue;
5071                    }
5072                    if (ri == mResolveInfo) {
5073                        // ACK!  Must do something better with this.
5074                    }
5075                    ai = ri.activityInfo;
5076                    comp = new ComponentName(ai.applicationInfo.packageName,
5077                            ai.name);
5078                } else {
5079                    ai = getActivityInfo(comp, flags, userId);
5080                    if (ai == null) {
5081                        continue;
5082                    }
5083                }
5084
5085                // Look for any generic query activities that are duplicates
5086                // of this specific one, and remove them from the results.
5087                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5088                N = results.size();
5089                int j;
5090                for (j=specificsPos; j<N; j++) {
5091                    ResolveInfo sri = results.get(j);
5092                    if ((sri.activityInfo.name.equals(comp.getClassName())
5093                            && sri.activityInfo.applicationInfo.packageName.equals(
5094                                    comp.getPackageName()))
5095                        || (action != null && sri.filter.matchAction(action))) {
5096                        results.remove(j);
5097                        if (DEBUG_INTENT_MATCHING) Log.v(
5098                            TAG, "Removing duplicate item from " + j
5099                            + " due to specific " + specificsPos);
5100                        if (ri == null) {
5101                            ri = sri;
5102                        }
5103                        j--;
5104                        N--;
5105                    }
5106                }
5107
5108                // Add this specific item to its proper place.
5109                if (ri == null) {
5110                    ri = new ResolveInfo();
5111                    ri.activityInfo = ai;
5112                }
5113                results.add(specificsPos, ri);
5114                ri.specificIndex = i;
5115                specificsPos++;
5116            }
5117        }
5118
5119        // Now we go through the remaining generic results and remove any
5120        // duplicate actions that are found here.
5121        N = results.size();
5122        for (int i=specificsPos; i<N-1; i++) {
5123            final ResolveInfo rii = results.get(i);
5124            if (rii.filter == null) {
5125                continue;
5126            }
5127
5128            // Iterate over all of the actions of this result's intent
5129            // filter...  typically this should be just one.
5130            final Iterator<String> it = rii.filter.actionsIterator();
5131            if (it == null) {
5132                continue;
5133            }
5134            while (it.hasNext()) {
5135                final String action = it.next();
5136                if (resultsAction != null && resultsAction.equals(action)) {
5137                    // If this action was explicitly requested, then don't
5138                    // remove things that have it.
5139                    continue;
5140                }
5141                for (int j=i+1; j<N; j++) {
5142                    final ResolveInfo rij = results.get(j);
5143                    if (rij.filter != null && rij.filter.hasAction(action)) {
5144                        results.remove(j);
5145                        if (DEBUG_INTENT_MATCHING) Log.v(
5146                            TAG, "Removing duplicate item from " + j
5147                            + " due to action " + action + " at " + i);
5148                        j--;
5149                        N--;
5150                    }
5151                }
5152            }
5153
5154            // If the caller didn't request filter information, drop it now
5155            // so we don't have to marshall/unmarshall it.
5156            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5157                rii.filter = null;
5158            }
5159        }
5160
5161        // Filter out the caller activity if so requested.
5162        if (caller != null) {
5163            N = results.size();
5164            for (int i=0; i<N; i++) {
5165                ActivityInfo ainfo = results.get(i).activityInfo;
5166                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5167                        && caller.getClassName().equals(ainfo.name)) {
5168                    results.remove(i);
5169                    break;
5170                }
5171            }
5172        }
5173
5174        // If the caller didn't request filter information,
5175        // drop them now so we don't have to
5176        // marshall/unmarshall it.
5177        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5178            N = results.size();
5179            for (int i=0; i<N; i++) {
5180                results.get(i).filter = null;
5181            }
5182        }
5183
5184        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5185        return results;
5186    }
5187
5188    @Override
5189    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5190            int userId) {
5191        if (!sUserManager.exists(userId)) return Collections.emptyList();
5192        ComponentName comp = intent.getComponent();
5193        if (comp == null) {
5194            if (intent.getSelector() != null) {
5195                intent = intent.getSelector();
5196                comp = intent.getComponent();
5197            }
5198        }
5199        if (comp != null) {
5200            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5201            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5202            if (ai != null) {
5203                ResolveInfo ri = new ResolveInfo();
5204                ri.activityInfo = ai;
5205                list.add(ri);
5206            }
5207            return list;
5208        }
5209
5210        // reader
5211        synchronized (mPackages) {
5212            String pkgName = intent.getPackage();
5213            if (pkgName == null) {
5214                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5215            }
5216            final PackageParser.Package pkg = mPackages.get(pkgName);
5217            if (pkg != null) {
5218                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5219                        userId);
5220            }
5221            return null;
5222        }
5223    }
5224
5225    @Override
5226    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5227        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5228        if (!sUserManager.exists(userId)) return null;
5229        if (query != null) {
5230            if (query.size() >= 1) {
5231                // If there is more than one service with the same priority,
5232                // just arbitrarily pick the first one.
5233                return query.get(0);
5234            }
5235        }
5236        return null;
5237    }
5238
5239    @Override
5240    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5241            int userId) {
5242        if (!sUserManager.exists(userId)) return Collections.emptyList();
5243        ComponentName comp = intent.getComponent();
5244        if (comp == null) {
5245            if (intent.getSelector() != null) {
5246                intent = intent.getSelector();
5247                comp = intent.getComponent();
5248            }
5249        }
5250        if (comp != null) {
5251            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5252            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5253            if (si != null) {
5254                final ResolveInfo ri = new ResolveInfo();
5255                ri.serviceInfo = si;
5256                list.add(ri);
5257            }
5258            return list;
5259        }
5260
5261        // reader
5262        synchronized (mPackages) {
5263            String pkgName = intent.getPackage();
5264            if (pkgName == null) {
5265                return mServices.queryIntent(intent, resolvedType, flags, userId);
5266            }
5267            final PackageParser.Package pkg = mPackages.get(pkgName);
5268            if (pkg != null) {
5269                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5270                        userId);
5271            }
5272            return null;
5273        }
5274    }
5275
5276    @Override
5277    public List<ResolveInfo> queryIntentContentProviders(
5278            Intent intent, String resolvedType, int flags, int userId) {
5279        if (!sUserManager.exists(userId)) return Collections.emptyList();
5280        ComponentName comp = intent.getComponent();
5281        if (comp == null) {
5282            if (intent.getSelector() != null) {
5283                intent = intent.getSelector();
5284                comp = intent.getComponent();
5285            }
5286        }
5287        if (comp != null) {
5288            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5289            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5290            if (pi != null) {
5291                final ResolveInfo ri = new ResolveInfo();
5292                ri.providerInfo = pi;
5293                list.add(ri);
5294            }
5295            return list;
5296        }
5297
5298        // reader
5299        synchronized (mPackages) {
5300            String pkgName = intent.getPackage();
5301            if (pkgName == null) {
5302                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5303            }
5304            final PackageParser.Package pkg = mPackages.get(pkgName);
5305            if (pkg != null) {
5306                return mProviders.queryIntentForPackage(
5307                        intent, resolvedType, flags, pkg.providers, userId);
5308            }
5309            return null;
5310        }
5311    }
5312
5313    @Override
5314    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5315        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5316
5317        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5318
5319        // writer
5320        synchronized (mPackages) {
5321            ArrayList<PackageInfo> list;
5322            if (listUninstalled) {
5323                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5324                for (PackageSetting ps : mSettings.mPackages.values()) {
5325                    PackageInfo pi;
5326                    if (ps.pkg != null) {
5327                        pi = generatePackageInfo(ps.pkg, flags, userId);
5328                    } else {
5329                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5330                    }
5331                    if (pi != null) {
5332                        list.add(pi);
5333                    }
5334                }
5335            } else {
5336                list = new ArrayList<PackageInfo>(mPackages.size());
5337                for (PackageParser.Package p : mPackages.values()) {
5338                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5339                    if (pi != null) {
5340                        list.add(pi);
5341                    }
5342                }
5343            }
5344
5345            return new ParceledListSlice<PackageInfo>(list);
5346        }
5347    }
5348
5349    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5350            String[] permissions, boolean[] tmp, int flags, int userId) {
5351        int numMatch = 0;
5352        final PermissionsState permissionsState = ps.getPermissionsState();
5353        for (int i=0; i<permissions.length; i++) {
5354            final String permission = permissions[i];
5355            if (permissionsState.hasPermission(permission, userId)) {
5356                tmp[i] = true;
5357                numMatch++;
5358            } else {
5359                tmp[i] = false;
5360            }
5361        }
5362        if (numMatch == 0) {
5363            return;
5364        }
5365        PackageInfo pi;
5366        if (ps.pkg != null) {
5367            pi = generatePackageInfo(ps.pkg, flags, userId);
5368        } else {
5369            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5370        }
5371        // The above might return null in cases of uninstalled apps or install-state
5372        // skew across users/profiles.
5373        if (pi != null) {
5374            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5375                if (numMatch == permissions.length) {
5376                    pi.requestedPermissions = permissions;
5377                } else {
5378                    pi.requestedPermissions = new String[numMatch];
5379                    numMatch = 0;
5380                    for (int i=0; i<permissions.length; i++) {
5381                        if (tmp[i]) {
5382                            pi.requestedPermissions[numMatch] = permissions[i];
5383                            numMatch++;
5384                        }
5385                    }
5386                }
5387            }
5388            list.add(pi);
5389        }
5390    }
5391
5392    @Override
5393    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5394            String[] permissions, int flags, int userId) {
5395        if (!sUserManager.exists(userId)) return null;
5396        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5397
5398        // writer
5399        synchronized (mPackages) {
5400            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5401            boolean[] tmpBools = new boolean[permissions.length];
5402            if (listUninstalled) {
5403                for (PackageSetting ps : mSettings.mPackages.values()) {
5404                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5405                }
5406            } else {
5407                for (PackageParser.Package pkg : mPackages.values()) {
5408                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5409                    if (ps != null) {
5410                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5411                                userId);
5412                    }
5413                }
5414            }
5415
5416            return new ParceledListSlice<PackageInfo>(list);
5417        }
5418    }
5419
5420    @Override
5421    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5422        if (!sUserManager.exists(userId)) return null;
5423        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5424
5425        // writer
5426        synchronized (mPackages) {
5427            ArrayList<ApplicationInfo> list;
5428            if (listUninstalled) {
5429                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5430                for (PackageSetting ps : mSettings.mPackages.values()) {
5431                    ApplicationInfo ai;
5432                    if (ps.pkg != null) {
5433                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5434                                ps.readUserState(userId), userId);
5435                    } else {
5436                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5437                    }
5438                    if (ai != null) {
5439                        list.add(ai);
5440                    }
5441                }
5442            } else {
5443                list = new ArrayList<ApplicationInfo>(mPackages.size());
5444                for (PackageParser.Package p : mPackages.values()) {
5445                    if (p.mExtras != null) {
5446                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5447                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5448                        if (ai != null) {
5449                            list.add(ai);
5450                        }
5451                    }
5452                }
5453            }
5454
5455            return new ParceledListSlice<ApplicationInfo>(list);
5456        }
5457    }
5458
5459    public List<ApplicationInfo> getPersistentApplications(int flags) {
5460        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5461
5462        // reader
5463        synchronized (mPackages) {
5464            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5465            final int userId = UserHandle.getCallingUserId();
5466            while (i.hasNext()) {
5467                final PackageParser.Package p = i.next();
5468                if (p.applicationInfo != null
5469                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5470                        && (!mSafeMode || isSystemApp(p))) {
5471                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5472                    if (ps != null) {
5473                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5474                                ps.readUserState(userId), userId);
5475                        if (ai != null) {
5476                            finalList.add(ai);
5477                        }
5478                    }
5479                }
5480            }
5481        }
5482
5483        return finalList;
5484    }
5485
5486    @Override
5487    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5488        if (!sUserManager.exists(userId)) return null;
5489        // reader
5490        synchronized (mPackages) {
5491            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5492            PackageSetting ps = provider != null
5493                    ? mSettings.mPackages.get(provider.owner.packageName)
5494                    : null;
5495            return ps != null
5496                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5497                    && (!mSafeMode || (provider.info.applicationInfo.flags
5498                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5499                    ? PackageParser.generateProviderInfo(provider, flags,
5500                            ps.readUserState(userId), userId)
5501                    : null;
5502        }
5503    }
5504
5505    /**
5506     * @deprecated
5507     */
5508    @Deprecated
5509    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5510        // reader
5511        synchronized (mPackages) {
5512            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5513                    .entrySet().iterator();
5514            final int userId = UserHandle.getCallingUserId();
5515            while (i.hasNext()) {
5516                Map.Entry<String, PackageParser.Provider> entry = i.next();
5517                PackageParser.Provider p = entry.getValue();
5518                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5519
5520                if (ps != null && p.syncable
5521                        && (!mSafeMode || (p.info.applicationInfo.flags
5522                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5523                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5524                            ps.readUserState(userId), userId);
5525                    if (info != null) {
5526                        outNames.add(entry.getKey());
5527                        outInfo.add(info);
5528                    }
5529                }
5530            }
5531        }
5532    }
5533
5534    @Override
5535    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5536            int uid, int flags) {
5537        ArrayList<ProviderInfo> finalList = null;
5538        // reader
5539        synchronized (mPackages) {
5540            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5541            final int userId = processName != null ?
5542                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5543            while (i.hasNext()) {
5544                final PackageParser.Provider p = i.next();
5545                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5546                if (ps != null && p.info.authority != null
5547                        && (processName == null
5548                                || (p.info.processName.equals(processName)
5549                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5550                        && mSettings.isEnabledLPr(p.info, flags, userId)
5551                        && (!mSafeMode
5552                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5553                    if (finalList == null) {
5554                        finalList = new ArrayList<ProviderInfo>(3);
5555                    }
5556                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5557                            ps.readUserState(userId), userId);
5558                    if (info != null) {
5559                        finalList.add(info);
5560                    }
5561                }
5562            }
5563        }
5564
5565        if (finalList != null) {
5566            Collections.sort(finalList, mProviderInitOrderSorter);
5567            return new ParceledListSlice<ProviderInfo>(finalList);
5568        }
5569
5570        return null;
5571    }
5572
5573    @Override
5574    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5575            int flags) {
5576        // reader
5577        synchronized (mPackages) {
5578            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5579            return PackageParser.generateInstrumentationInfo(i, flags);
5580        }
5581    }
5582
5583    @Override
5584    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5585            int flags) {
5586        ArrayList<InstrumentationInfo> finalList =
5587            new ArrayList<InstrumentationInfo>();
5588
5589        // reader
5590        synchronized (mPackages) {
5591            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5592            while (i.hasNext()) {
5593                final PackageParser.Instrumentation p = i.next();
5594                if (targetPackage == null
5595                        || targetPackage.equals(p.info.targetPackage)) {
5596                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5597                            flags);
5598                    if (ii != null) {
5599                        finalList.add(ii);
5600                    }
5601                }
5602            }
5603        }
5604
5605        return finalList;
5606    }
5607
5608    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5609        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5610        if (overlays == null) {
5611            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5612            return;
5613        }
5614        for (PackageParser.Package opkg : overlays.values()) {
5615            // Not much to do if idmap fails: we already logged the error
5616            // and we certainly don't want to abort installation of pkg simply
5617            // because an overlay didn't fit properly. For these reasons,
5618            // ignore the return value of createIdmapForPackagePairLI.
5619            createIdmapForPackagePairLI(pkg, opkg);
5620        }
5621    }
5622
5623    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5624            PackageParser.Package opkg) {
5625        if (!opkg.mTrustedOverlay) {
5626            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5627                    opkg.baseCodePath + ": overlay not trusted");
5628            return false;
5629        }
5630        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5631        if (overlaySet == null) {
5632            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5633                    opkg.baseCodePath + " but target package has no known overlays");
5634            return false;
5635        }
5636        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5637        // TODO: generate idmap for split APKs
5638        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5639            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5640                    + opkg.baseCodePath);
5641            return false;
5642        }
5643        PackageParser.Package[] overlayArray =
5644            overlaySet.values().toArray(new PackageParser.Package[0]);
5645        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5646            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5647                return p1.mOverlayPriority - p2.mOverlayPriority;
5648            }
5649        };
5650        Arrays.sort(overlayArray, cmp);
5651
5652        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5653        int i = 0;
5654        for (PackageParser.Package p : overlayArray) {
5655            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5656        }
5657        return true;
5658    }
5659
5660    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5661        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5662        try {
5663            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5664        } finally {
5665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5666        }
5667    }
5668
5669    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5670        final File[] files = dir.listFiles();
5671        if (ArrayUtils.isEmpty(files)) {
5672            Log.d(TAG, "No files in app dir " + dir);
5673            return;
5674        }
5675
5676        if (DEBUG_PACKAGE_SCANNING) {
5677            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5678                    + " flags=0x" + Integer.toHexString(parseFlags));
5679        }
5680
5681        for (File file : files) {
5682            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5683                    && !PackageInstallerService.isStageName(file.getName());
5684            if (!isPackage) {
5685                // Ignore entries which are not packages
5686                continue;
5687            }
5688            try {
5689                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5690                        scanFlags, currentTime, null);
5691            } catch (PackageManagerException e) {
5692                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5693
5694                // Delete invalid userdata apps
5695                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5696                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5697                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5698                    if (file.isDirectory()) {
5699                        mInstaller.rmPackageDir(file.getAbsolutePath());
5700                    } else {
5701                        file.delete();
5702                    }
5703                }
5704            }
5705        }
5706    }
5707
5708    private static File getSettingsProblemFile() {
5709        File dataDir = Environment.getDataDirectory();
5710        File systemDir = new File(dataDir, "system");
5711        File fname = new File(systemDir, "uiderrors.txt");
5712        return fname;
5713    }
5714
5715    static void reportSettingsProblem(int priority, String msg) {
5716        logCriticalInfo(priority, msg);
5717    }
5718
5719    static void logCriticalInfo(int priority, String msg) {
5720        Slog.println(priority, TAG, msg);
5721        EventLogTags.writePmCriticalInfo(msg);
5722        try {
5723            File fname = getSettingsProblemFile();
5724            FileOutputStream out = new FileOutputStream(fname, true);
5725            PrintWriter pw = new FastPrintWriter(out);
5726            SimpleDateFormat formatter = new SimpleDateFormat();
5727            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5728            pw.println(dateString + ": " + msg);
5729            pw.close();
5730            FileUtils.setPermissions(
5731                    fname.toString(),
5732                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5733                    -1, -1);
5734        } catch (java.io.IOException e) {
5735        }
5736    }
5737
5738    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5739            PackageParser.Package pkg, File srcFile, int parseFlags)
5740            throws PackageManagerException {
5741        if (ps != null
5742                && ps.codePath.equals(srcFile)
5743                && ps.timeStamp == srcFile.lastModified()
5744                && !isCompatSignatureUpdateNeeded(pkg)
5745                && !isRecoverSignatureUpdateNeeded(pkg)) {
5746            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5747            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5748            ArraySet<PublicKey> signingKs;
5749            synchronized (mPackages) {
5750                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5751            }
5752            if (ps.signatures.mSignatures != null
5753                    && ps.signatures.mSignatures.length != 0
5754                    && signingKs != null) {
5755                // Optimization: reuse the existing cached certificates
5756                // if the package appears to be unchanged.
5757                pkg.mSignatures = ps.signatures.mSignatures;
5758                pkg.mSigningKeys = signingKs;
5759                return;
5760            }
5761
5762            Slog.w(TAG, "PackageSetting for " + ps.name
5763                    + " is missing signatures.  Collecting certs again to recover them.");
5764        } else {
5765            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5766        }
5767
5768        try {
5769            pp.collectCertificates(pkg, parseFlags);
5770            pp.collectManifestDigest(pkg);
5771        } catch (PackageParserException e) {
5772            throw PackageManagerException.from(e);
5773        }
5774    }
5775
5776    /**
5777     *  Traces a package scan.
5778     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5779     */
5780    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5781            long currentTime, UserHandle user) throws PackageManagerException {
5782        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5783        try {
5784            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5785        } finally {
5786            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5787        }
5788    }
5789
5790    /**
5791     *  Scans a package and returns the newly parsed package.
5792     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5793     */
5794    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5795            long currentTime, UserHandle user) throws PackageManagerException {
5796        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5797        parseFlags |= mDefParseFlags;
5798        PackageParser pp = new PackageParser();
5799        pp.setSeparateProcesses(mSeparateProcesses);
5800        pp.setOnlyCoreApps(mOnlyCore);
5801        pp.setDisplayMetrics(mMetrics);
5802
5803        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5804            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5805        }
5806
5807        final PackageParser.Package pkg;
5808        try {
5809            pkg = pp.parsePackage(scanFile, parseFlags);
5810        } catch (PackageParserException e) {
5811            throw PackageManagerException.from(e);
5812        }
5813
5814        PackageSetting ps = null;
5815        PackageSetting updatedPkg;
5816        // reader
5817        synchronized (mPackages) {
5818            // Look to see if we already know about this package.
5819            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5820            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5821                // This package has been renamed to its original name.  Let's
5822                // use that.
5823                ps = mSettings.peekPackageLPr(oldName);
5824            }
5825            // If there was no original package, see one for the real package name.
5826            if (ps == null) {
5827                ps = mSettings.peekPackageLPr(pkg.packageName);
5828            }
5829            // Check to see if this package could be hiding/updating a system
5830            // package.  Must look for it either under the original or real
5831            // package name depending on our state.
5832            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5833            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5834        }
5835        boolean updatedPkgBetter = false;
5836        // First check if this is a system package that may involve an update
5837        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5838            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5839            // it needs to drop FLAG_PRIVILEGED.
5840            if (locationIsPrivileged(scanFile)) {
5841                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5842            } else {
5843                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5844            }
5845
5846            if (ps != null && !ps.codePath.equals(scanFile)) {
5847                // The path has changed from what was last scanned...  check the
5848                // version of the new path against what we have stored to determine
5849                // what to do.
5850                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5851                if (pkg.mVersionCode <= ps.versionCode) {
5852                    // The system package has been updated and the code path does not match
5853                    // Ignore entry. Skip it.
5854                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5855                            + " ignored: updated version " + ps.versionCode
5856                            + " better than this " + pkg.mVersionCode);
5857                    if (!updatedPkg.codePath.equals(scanFile)) {
5858                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5859                                + ps.name + " changing from " + updatedPkg.codePathString
5860                                + " to " + scanFile);
5861                        updatedPkg.codePath = scanFile;
5862                        updatedPkg.codePathString = scanFile.toString();
5863                        updatedPkg.resourcePath = scanFile;
5864                        updatedPkg.resourcePathString = scanFile.toString();
5865                    }
5866                    updatedPkg.pkg = pkg;
5867                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5868                            "Package " + ps.name + " at " + scanFile
5869                                    + " ignored: updated version " + ps.versionCode
5870                                    + " better than this " + pkg.mVersionCode);
5871                } else {
5872                    // The current app on the system partition is better than
5873                    // what we have updated to on the data partition; switch
5874                    // back to the system partition version.
5875                    // At this point, its safely assumed that package installation for
5876                    // apps in system partition will go through. If not there won't be a working
5877                    // version of the app
5878                    // writer
5879                    synchronized (mPackages) {
5880                        // Just remove the loaded entries from package lists.
5881                        mPackages.remove(ps.name);
5882                    }
5883
5884                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5885                            + " reverting from " + ps.codePathString
5886                            + ": new version " + pkg.mVersionCode
5887                            + " better than installed " + ps.versionCode);
5888
5889                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5890                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5891                    synchronized (mInstallLock) {
5892                        args.cleanUpResourcesLI();
5893                    }
5894                    synchronized (mPackages) {
5895                        mSettings.enableSystemPackageLPw(ps.name);
5896                    }
5897                    updatedPkgBetter = true;
5898                }
5899            }
5900        }
5901
5902        if (updatedPkg != null) {
5903            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5904            // initially
5905            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5906
5907            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5908            // flag set initially
5909            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5910                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5911            }
5912        }
5913
5914        // Verify certificates against what was last scanned
5915        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5916
5917        /*
5918         * A new system app appeared, but we already had a non-system one of the
5919         * same name installed earlier.
5920         */
5921        boolean shouldHideSystemApp = false;
5922        if (updatedPkg == null && ps != null
5923                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5924            /*
5925             * Check to make sure the signatures match first. If they don't,
5926             * wipe the installed application and its data.
5927             */
5928            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5929                    != PackageManager.SIGNATURE_MATCH) {
5930                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5931                        + " signatures don't match existing userdata copy; removing");
5932                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5933                ps = null;
5934            } else {
5935                /*
5936                 * If the newly-added system app is an older version than the
5937                 * already installed version, hide it. It will be scanned later
5938                 * and re-added like an update.
5939                 */
5940                if (pkg.mVersionCode <= ps.versionCode) {
5941                    shouldHideSystemApp = true;
5942                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5943                            + " but new version " + pkg.mVersionCode + " better than installed "
5944                            + ps.versionCode + "; hiding system");
5945                } else {
5946                    /*
5947                     * The newly found system app is a newer version that the
5948                     * one previously installed. Simply remove the
5949                     * already-installed application and replace it with our own
5950                     * while keeping the application data.
5951                     */
5952                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5953                            + " reverting from " + ps.codePathString + ": new version "
5954                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5955                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5956                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5957                    synchronized (mInstallLock) {
5958                        args.cleanUpResourcesLI();
5959                    }
5960                }
5961            }
5962        }
5963
5964        // The apk is forward locked (not public) if its code and resources
5965        // are kept in different files. (except for app in either system or
5966        // vendor path).
5967        // TODO grab this value from PackageSettings
5968        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5969            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5970                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5971            }
5972        }
5973
5974        // TODO: extend to support forward-locked splits
5975        String resourcePath = null;
5976        String baseResourcePath = null;
5977        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5978            if (ps != null && ps.resourcePathString != null) {
5979                resourcePath = ps.resourcePathString;
5980                baseResourcePath = ps.resourcePathString;
5981            } else {
5982                // Should not happen at all. Just log an error.
5983                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5984            }
5985        } else {
5986            resourcePath = pkg.codePath;
5987            baseResourcePath = pkg.baseCodePath;
5988        }
5989
5990        // Set application objects path explicitly.
5991        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5992        pkg.applicationInfo.setCodePath(pkg.codePath);
5993        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5994        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5995        pkg.applicationInfo.setResourcePath(resourcePath);
5996        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5997        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5998
5999        // Note that we invoke the following method only if we are about to unpack an application
6000        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6001                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6002
6003        /*
6004         * If the system app should be overridden by a previously installed
6005         * data, hide the system app now and let the /data/app scan pick it up
6006         * again.
6007         */
6008        if (shouldHideSystemApp) {
6009            synchronized (mPackages) {
6010                mSettings.disableSystemPackageLPw(pkg.packageName);
6011            }
6012        }
6013
6014        return scannedPkg;
6015    }
6016
6017    private static String fixProcessName(String defProcessName,
6018            String processName, int uid) {
6019        if (processName == null) {
6020            return defProcessName;
6021        }
6022        return processName;
6023    }
6024
6025    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6026            throws PackageManagerException {
6027        if (pkgSetting.signatures.mSignatures != null) {
6028            // Already existing package. Make sure signatures match
6029            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6030                    == PackageManager.SIGNATURE_MATCH;
6031            if (!match) {
6032                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6033                        == PackageManager.SIGNATURE_MATCH;
6034            }
6035            if (!match) {
6036                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6037                        == PackageManager.SIGNATURE_MATCH;
6038            }
6039            if (!match) {
6040                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6041                        + pkg.packageName + " signatures do not match the "
6042                        + "previously installed version; ignoring!");
6043            }
6044        }
6045
6046        // Check for shared user signatures
6047        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6048            // Already existing package. Make sure signatures match
6049            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6050                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6051            if (!match) {
6052                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6053                        == PackageManager.SIGNATURE_MATCH;
6054            }
6055            if (!match) {
6056                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6057                        == PackageManager.SIGNATURE_MATCH;
6058            }
6059            if (!match) {
6060                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6061                        "Package " + pkg.packageName
6062                        + " has no signatures that match those in shared user "
6063                        + pkgSetting.sharedUser.name + "; ignoring!");
6064            }
6065        }
6066    }
6067
6068    /**
6069     * Enforces that only the system UID or root's UID can call a method exposed
6070     * via Binder.
6071     *
6072     * @param message used as message if SecurityException is thrown
6073     * @throws SecurityException if the caller is not system or root
6074     */
6075    private static final void enforceSystemOrRoot(String message) {
6076        final int uid = Binder.getCallingUid();
6077        if (uid != Process.SYSTEM_UID && uid != 0) {
6078            throw new SecurityException(message);
6079        }
6080    }
6081
6082    @Override
6083    public void performBootDexOpt() {
6084        enforceSystemOrRoot("Only the system can request dexopt be performed");
6085
6086        // Before everything else, see whether we need to fstrim.
6087        try {
6088            IMountService ms = PackageHelper.getMountService();
6089            if (ms != null) {
6090                final boolean isUpgrade = isUpgrade();
6091                boolean doTrim = isUpgrade;
6092                if (doTrim) {
6093                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6094                } else {
6095                    final long interval = android.provider.Settings.Global.getLong(
6096                            mContext.getContentResolver(),
6097                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6098                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6099                    if (interval > 0) {
6100                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6101                        if (timeSinceLast > interval) {
6102                            doTrim = true;
6103                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6104                                    + "; running immediately");
6105                        }
6106                    }
6107                }
6108                if (doTrim) {
6109                    if (!isFirstBoot()) {
6110                        try {
6111                            ActivityManagerNative.getDefault().showBootMessage(
6112                                    mContext.getResources().getString(
6113                                            R.string.android_upgrading_fstrim), true);
6114                        } catch (RemoteException e) {
6115                        }
6116                    }
6117                    ms.runMaintenance();
6118                }
6119            } else {
6120                Slog.e(TAG, "Mount service unavailable!");
6121            }
6122        } catch (RemoteException e) {
6123            // Can't happen; MountService is local
6124        }
6125
6126        final ArraySet<PackageParser.Package> pkgs;
6127        synchronized (mPackages) {
6128            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6129        }
6130
6131        if (pkgs != null) {
6132            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6133            // in case the device runs out of space.
6134            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6135            // Give priority to core apps.
6136            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6137                PackageParser.Package pkg = it.next();
6138                if (pkg.coreApp) {
6139                    if (DEBUG_DEXOPT) {
6140                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6141                    }
6142                    sortedPkgs.add(pkg);
6143                    it.remove();
6144                }
6145            }
6146            // Give priority to system apps that listen for pre boot complete.
6147            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6148            ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6149            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6150                PackageParser.Package pkg = it.next();
6151                if (pkgNames.contains(pkg.packageName)) {
6152                    if (DEBUG_DEXOPT) {
6153                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6154                    }
6155                    sortedPkgs.add(pkg);
6156                    it.remove();
6157                }
6158            }
6159            // Give priority to system apps.
6160            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6161                PackageParser.Package pkg = it.next();
6162                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6163                    if (DEBUG_DEXOPT) {
6164                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6165                    }
6166                    sortedPkgs.add(pkg);
6167                    it.remove();
6168                }
6169            }
6170            // Give priority to updated system apps.
6171            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6172                PackageParser.Package pkg = it.next();
6173                if (pkg.isUpdatedSystemApp()) {
6174                    if (DEBUG_DEXOPT) {
6175                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6176                    }
6177                    sortedPkgs.add(pkg);
6178                    it.remove();
6179                }
6180            }
6181            // Give priority to apps that listen for boot complete.
6182            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6183            pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6184            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6185                PackageParser.Package pkg = it.next();
6186                if (pkgNames.contains(pkg.packageName)) {
6187                    if (DEBUG_DEXOPT) {
6188                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6189                    }
6190                    sortedPkgs.add(pkg);
6191                    it.remove();
6192                }
6193            }
6194            // Filter out packages that aren't recently used.
6195            filterRecentlyUsedApps(pkgs);
6196            // Add all remaining apps.
6197            for (PackageParser.Package pkg : pkgs) {
6198                if (DEBUG_DEXOPT) {
6199                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6200                }
6201                sortedPkgs.add(pkg);
6202            }
6203
6204            // If we want to be lazy, filter everything that wasn't recently used.
6205            if (mLazyDexOpt) {
6206                filterRecentlyUsedApps(sortedPkgs);
6207            }
6208
6209            int i = 0;
6210            int total = sortedPkgs.size();
6211            File dataDir = Environment.getDataDirectory();
6212            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6213            if (lowThreshold == 0) {
6214                throw new IllegalStateException("Invalid low memory threshold");
6215            }
6216            for (PackageParser.Package pkg : sortedPkgs) {
6217                long usableSpace = dataDir.getUsableSpace();
6218                if (usableSpace < lowThreshold) {
6219                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6220                    break;
6221                }
6222                performBootDexOpt(pkg, ++i, total);
6223            }
6224        }
6225    }
6226
6227    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6228        // Filter out packages that aren't recently used.
6229        //
6230        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6231        // should do a full dexopt.
6232        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6233            int total = pkgs.size();
6234            int skipped = 0;
6235            long now = System.currentTimeMillis();
6236            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6237                PackageParser.Package pkg = i.next();
6238                long then = pkg.mLastPackageUsageTimeInMills;
6239                if (then + mDexOptLRUThresholdInMills < now) {
6240                    if (DEBUG_DEXOPT) {
6241                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6242                              ((then == 0) ? "never" : new Date(then)));
6243                    }
6244                    i.remove();
6245                    skipped++;
6246                }
6247            }
6248            if (DEBUG_DEXOPT) {
6249                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6250            }
6251        }
6252    }
6253
6254    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6255        List<ResolveInfo> ris = null;
6256        try {
6257            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6258                    intent, null, 0, userId);
6259        } catch (RemoteException e) {
6260        }
6261        ArraySet<String> pkgNames = new ArraySet<String>();
6262        if (ris != null) {
6263            for (ResolveInfo ri : ris) {
6264                pkgNames.add(ri.activityInfo.packageName);
6265            }
6266        }
6267        return pkgNames;
6268    }
6269
6270    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6271        if (DEBUG_DEXOPT) {
6272            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6273        }
6274        if (!isFirstBoot()) {
6275            try {
6276                ActivityManagerNative.getDefault().showBootMessage(
6277                        mContext.getResources().getString(R.string.android_upgrading_apk,
6278                                curr, total), true);
6279            } catch (RemoteException e) {
6280            }
6281        }
6282        PackageParser.Package p = pkg;
6283        synchronized (mInstallLock) {
6284            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6285                    false /* force dex */, false /* defer */, true /* include dependencies */,
6286                    false /* boot complete */);
6287        }
6288    }
6289
6290    @Override
6291    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6292        return performDexOptTraced(packageName, instructionSet, false);
6293    }
6294
6295    public boolean performDexOpt(
6296            String packageName, String instructionSet, boolean backgroundDexopt) {
6297        return performDexOptTraced(packageName, instructionSet, backgroundDexopt);
6298    }
6299
6300    private boolean performDexOptTraced(
6301            String packageName, String instructionSet, boolean backgroundDexopt) {
6302        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6303        try {
6304            return performDexOptInternal(packageName, instructionSet, backgroundDexopt);
6305        } finally {
6306            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6307        }
6308    }
6309
6310    private boolean performDexOptInternal(
6311            String packageName, String instructionSet, boolean backgroundDexopt) {
6312        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6313        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6314        if (!dexopt && !updateUsage) {
6315            // We aren't going to dexopt or update usage, so bail early.
6316            return false;
6317        }
6318        PackageParser.Package p;
6319        final String targetInstructionSet;
6320        synchronized (mPackages) {
6321            p = mPackages.get(packageName);
6322            if (p == null) {
6323                return false;
6324            }
6325            if (updateUsage) {
6326                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6327            }
6328            mPackageUsage.write(false);
6329            if (!dexopt) {
6330                // We aren't going to dexopt, so bail early.
6331                return false;
6332            }
6333
6334            targetInstructionSet = instructionSet != null ? instructionSet :
6335                    getPrimaryInstructionSet(p.applicationInfo);
6336            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6337                return false;
6338            }
6339        }
6340        long callingId = Binder.clearCallingIdentity();
6341        try {
6342            synchronized (mInstallLock) {
6343                final String[] instructionSets = new String[] { targetInstructionSet };
6344                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6345                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6346                        true /* boot complete */);
6347                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6348            }
6349        } finally {
6350            Binder.restoreCallingIdentity(callingId);
6351        }
6352    }
6353
6354    public ArraySet<String> getPackagesThatNeedDexOpt() {
6355        ArraySet<String> pkgs = null;
6356        synchronized (mPackages) {
6357            for (PackageParser.Package p : mPackages.values()) {
6358                if (DEBUG_DEXOPT) {
6359                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6360                }
6361                if (!p.mDexOptPerformed.isEmpty()) {
6362                    continue;
6363                }
6364                if (pkgs == null) {
6365                    pkgs = new ArraySet<String>();
6366                }
6367                pkgs.add(p.packageName);
6368            }
6369        }
6370        return pkgs;
6371    }
6372
6373    public void shutdown() {
6374        mPackageUsage.write(true);
6375    }
6376
6377    @Override
6378    public void forceDexOpt(String packageName) {
6379        enforceSystemOrRoot("forceDexOpt");
6380
6381        PackageParser.Package pkg;
6382        synchronized (mPackages) {
6383            pkg = mPackages.get(packageName);
6384            if (pkg == null) {
6385                throw new IllegalArgumentException("Missing package: " + packageName);
6386            }
6387        }
6388
6389        synchronized (mInstallLock) {
6390            final String[] instructionSets = new String[] {
6391                    getPrimaryInstructionSet(pkg.applicationInfo) };
6392
6393            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6394
6395            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6396                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6397                    true /* boot complete */);
6398
6399            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6400            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6401                throw new IllegalStateException("Failed to dexopt: " + res);
6402            }
6403        }
6404    }
6405
6406    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6407        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6408            Slog.w(TAG, "Unable to update from " + oldPkg.name
6409                    + " to " + newPkg.packageName
6410                    + ": old package not in system partition");
6411            return false;
6412        } else if (mPackages.get(oldPkg.name) != null) {
6413            Slog.w(TAG, "Unable to update from " + oldPkg.name
6414                    + " to " + newPkg.packageName
6415                    + ": old package still exists");
6416            return false;
6417        }
6418        return true;
6419    }
6420
6421    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6422        int[] users = sUserManager.getUserIds();
6423        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6424        if (res < 0) {
6425            return res;
6426        }
6427        for (int user : users) {
6428            if (user != 0) {
6429                res = mInstaller.createUserData(volumeUuid, packageName,
6430                        UserHandle.getUid(user, uid), user, seinfo);
6431                if (res < 0) {
6432                    return res;
6433                }
6434            }
6435        }
6436        return res;
6437    }
6438
6439    private int removeDataDirsLI(String volumeUuid, String packageName) {
6440        int[] users = sUserManager.getUserIds();
6441        int res = 0;
6442        for (int user : users) {
6443            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6444            if (resInner < 0) {
6445                res = resInner;
6446            }
6447        }
6448
6449        return res;
6450    }
6451
6452    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6453        int[] users = sUserManager.getUserIds();
6454        int res = 0;
6455        for (int user : users) {
6456            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6457            if (resInner < 0) {
6458                res = resInner;
6459            }
6460        }
6461        return res;
6462    }
6463
6464    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6465            PackageParser.Package changingLib) {
6466        if (file.path != null) {
6467            usesLibraryFiles.add(file.path);
6468            return;
6469        }
6470        PackageParser.Package p = mPackages.get(file.apk);
6471        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6472            // If we are doing this while in the middle of updating a library apk,
6473            // then we need to make sure to use that new apk for determining the
6474            // dependencies here.  (We haven't yet finished committing the new apk
6475            // to the package manager state.)
6476            if (p == null || p.packageName.equals(changingLib.packageName)) {
6477                p = changingLib;
6478            }
6479        }
6480        if (p != null) {
6481            usesLibraryFiles.addAll(p.getAllCodePaths());
6482        }
6483    }
6484
6485    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6486            PackageParser.Package changingLib) throws PackageManagerException {
6487        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6488            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6489            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6490            for (int i=0; i<N; i++) {
6491                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6492                if (file == null) {
6493                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6494                            "Package " + pkg.packageName + " requires unavailable shared library "
6495                            + pkg.usesLibraries.get(i) + "; failing!");
6496                }
6497                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6498            }
6499            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6500            for (int i=0; i<N; i++) {
6501                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6502                if (file == null) {
6503                    Slog.w(TAG, "Package " + pkg.packageName
6504                            + " desires unavailable shared library "
6505                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6506                } else {
6507                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6508                }
6509            }
6510            N = usesLibraryFiles.size();
6511            if (N > 0) {
6512                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6513            } else {
6514                pkg.usesLibraryFiles = null;
6515            }
6516        }
6517    }
6518
6519    private static boolean hasString(List<String> list, List<String> which) {
6520        if (list == null) {
6521            return false;
6522        }
6523        for (int i=list.size()-1; i>=0; i--) {
6524            for (int j=which.size()-1; j>=0; j--) {
6525                if (which.get(j).equals(list.get(i))) {
6526                    return true;
6527                }
6528            }
6529        }
6530        return false;
6531    }
6532
6533    private void updateAllSharedLibrariesLPw() {
6534        for (PackageParser.Package pkg : mPackages.values()) {
6535            try {
6536                updateSharedLibrariesLPw(pkg, null);
6537            } catch (PackageManagerException e) {
6538                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6539            }
6540        }
6541    }
6542
6543    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6544            PackageParser.Package changingPkg) {
6545        ArrayList<PackageParser.Package> res = null;
6546        for (PackageParser.Package pkg : mPackages.values()) {
6547            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6548                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6549                if (res == null) {
6550                    res = new ArrayList<PackageParser.Package>();
6551                }
6552                res.add(pkg);
6553                try {
6554                    updateSharedLibrariesLPw(pkg, changingPkg);
6555                } catch (PackageManagerException e) {
6556                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6557                }
6558            }
6559        }
6560        return res;
6561    }
6562
6563    /**
6564     * Derive the value of the {@code cpuAbiOverride} based on the provided
6565     * value and an optional stored value from the package settings.
6566     */
6567    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6568        String cpuAbiOverride = null;
6569
6570        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6571            cpuAbiOverride = null;
6572        } else if (abiOverride != null) {
6573            cpuAbiOverride = abiOverride;
6574        } else if (settings != null) {
6575            cpuAbiOverride = settings.cpuAbiOverrideString;
6576        }
6577
6578        return cpuAbiOverride;
6579    }
6580
6581    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6582            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6583        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6584        try {
6585            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6586        } finally {
6587            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6588        }
6589    }
6590
6591    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6592            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6593        boolean success = false;
6594        try {
6595            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6596                    currentTime, user);
6597            success = true;
6598            return res;
6599        } finally {
6600            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6601                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6602            }
6603        }
6604    }
6605
6606    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6607            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6608        final File scanFile = new File(pkg.codePath);
6609        if (pkg.applicationInfo.getCodePath() == null ||
6610                pkg.applicationInfo.getResourcePath() == null) {
6611            // Bail out. The resource and code paths haven't been set.
6612            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6613                    "Code and resource paths haven't been set correctly");
6614        }
6615
6616        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6617            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6618        } else {
6619            // Only allow system apps to be flagged as core apps.
6620            pkg.coreApp = false;
6621        }
6622
6623        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6624            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6625        }
6626
6627        if (mCustomResolverComponentName != null &&
6628                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6629            setUpCustomResolverActivity(pkg);
6630        }
6631
6632        if (pkg.packageName.equals("android")) {
6633            synchronized (mPackages) {
6634                if (mAndroidApplication != null) {
6635                    Slog.w(TAG, "*************************************************");
6636                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6637                    Slog.w(TAG, " file=" + scanFile);
6638                    Slog.w(TAG, "*************************************************");
6639                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6640                            "Core android package being redefined.  Skipping.");
6641                }
6642
6643                // Set up information for our fall-back user intent resolution activity.
6644                mPlatformPackage = pkg;
6645                pkg.mVersionCode = mSdkVersion;
6646                mAndroidApplication = pkg.applicationInfo;
6647
6648                if (!mResolverReplaced) {
6649                    mResolveActivity.applicationInfo = mAndroidApplication;
6650                    mResolveActivity.name = ResolverActivity.class.getName();
6651                    mResolveActivity.packageName = mAndroidApplication.packageName;
6652                    mResolveActivity.processName = "system:ui";
6653                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6654                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6655                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6656                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6657                    mResolveActivity.exported = true;
6658                    mResolveActivity.enabled = true;
6659                    mResolveInfo.activityInfo = mResolveActivity;
6660                    mResolveInfo.priority = 0;
6661                    mResolveInfo.preferredOrder = 0;
6662                    mResolveInfo.match = 0;
6663                    mResolveComponentName = new ComponentName(
6664                            mAndroidApplication.packageName, mResolveActivity.name);
6665                }
6666            }
6667        }
6668
6669        if (DEBUG_PACKAGE_SCANNING) {
6670            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6671                Log.d(TAG, "Scanning package " + pkg.packageName);
6672        }
6673
6674        if (mPackages.containsKey(pkg.packageName)
6675                || mSharedLibraries.containsKey(pkg.packageName)) {
6676            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6677                    "Application package " + pkg.packageName
6678                    + " already installed.  Skipping duplicate.");
6679        }
6680
6681        // If we're only installing presumed-existing packages, require that the
6682        // scanned APK is both already known and at the path previously established
6683        // for it.  Previously unknown packages we pick up normally, but if we have an
6684        // a priori expectation about this package's install presence, enforce it.
6685        // With a singular exception for new system packages. When an OTA contains
6686        // a new system package, we allow the codepath to change from a system location
6687        // to the user-installed location. If we don't allow this change, any newer,
6688        // user-installed version of the application will be ignored.
6689        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6690            if (mExpectingBetter.containsKey(pkg.packageName)) {
6691                logCriticalInfo(Log.WARN,
6692                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6693            } else {
6694                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6695                if (known != null) {
6696                    if (DEBUG_PACKAGE_SCANNING) {
6697                        Log.d(TAG, "Examining " + pkg.codePath
6698                                + " and requiring known paths " + known.codePathString
6699                                + " & " + known.resourcePathString);
6700                    }
6701                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6702                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6703                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6704                                "Application package " + pkg.packageName
6705                                + " found at " + pkg.applicationInfo.getCodePath()
6706                                + " but expected at " + known.codePathString + "; ignoring.");
6707                    }
6708                }
6709            }
6710        }
6711
6712        // Initialize package source and resource directories
6713        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6714        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6715
6716        SharedUserSetting suid = null;
6717        PackageSetting pkgSetting = null;
6718
6719        if (!isSystemApp(pkg)) {
6720            // Only system apps can use these features.
6721            pkg.mOriginalPackages = null;
6722            pkg.mRealPackage = null;
6723            pkg.mAdoptPermissions = null;
6724        }
6725
6726        // writer
6727        synchronized (mPackages) {
6728            if (pkg.mSharedUserId != null) {
6729                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6730                if (suid == null) {
6731                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6732                            "Creating application package " + pkg.packageName
6733                            + " for shared user failed");
6734                }
6735                if (DEBUG_PACKAGE_SCANNING) {
6736                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6737                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6738                                + "): packages=" + suid.packages);
6739                }
6740            }
6741
6742            // Check if we are renaming from an original package name.
6743            PackageSetting origPackage = null;
6744            String realName = null;
6745            if (pkg.mOriginalPackages != null) {
6746                // This package may need to be renamed to a previously
6747                // installed name.  Let's check on that...
6748                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6749                if (pkg.mOriginalPackages.contains(renamed)) {
6750                    // This package had originally been installed as the
6751                    // original name, and we have already taken care of
6752                    // transitioning to the new one.  Just update the new
6753                    // one to continue using the old name.
6754                    realName = pkg.mRealPackage;
6755                    if (!pkg.packageName.equals(renamed)) {
6756                        // Callers into this function may have already taken
6757                        // care of renaming the package; only do it here if
6758                        // it is not already done.
6759                        pkg.setPackageName(renamed);
6760                    }
6761
6762                } else {
6763                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6764                        if ((origPackage = mSettings.peekPackageLPr(
6765                                pkg.mOriginalPackages.get(i))) != null) {
6766                            // We do have the package already installed under its
6767                            // original name...  should we use it?
6768                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6769                                // New package is not compatible with original.
6770                                origPackage = null;
6771                                continue;
6772                            } else if (origPackage.sharedUser != null) {
6773                                // Make sure uid is compatible between packages.
6774                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6775                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6776                                            + " to " + pkg.packageName + ": old uid "
6777                                            + origPackage.sharedUser.name
6778                                            + " differs from " + pkg.mSharedUserId);
6779                                    origPackage = null;
6780                                    continue;
6781                                }
6782                            } else {
6783                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6784                                        + pkg.packageName + " to old name " + origPackage.name);
6785                            }
6786                            break;
6787                        }
6788                    }
6789                }
6790            }
6791
6792            if (mTransferedPackages.contains(pkg.packageName)) {
6793                Slog.w(TAG, "Package " + pkg.packageName
6794                        + " was transferred to another, but its .apk remains");
6795            }
6796
6797            // Just create the setting, don't add it yet. For already existing packages
6798            // the PkgSetting exists already and doesn't have to be created.
6799            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6800                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6801                    pkg.applicationInfo.primaryCpuAbi,
6802                    pkg.applicationInfo.secondaryCpuAbi,
6803                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6804                    user, false);
6805            if (pkgSetting == null) {
6806                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6807                        "Creating application package " + pkg.packageName + " failed");
6808            }
6809
6810            if (pkgSetting.origPackage != null) {
6811                // If we are first transitioning from an original package,
6812                // fix up the new package's name now.  We need to do this after
6813                // looking up the package under its new name, so getPackageLP
6814                // can take care of fiddling things correctly.
6815                pkg.setPackageName(origPackage.name);
6816
6817                // File a report about this.
6818                String msg = "New package " + pkgSetting.realName
6819                        + " renamed to replace old package " + pkgSetting.name;
6820                reportSettingsProblem(Log.WARN, msg);
6821
6822                // Make a note of it.
6823                mTransferedPackages.add(origPackage.name);
6824
6825                // No longer need to retain this.
6826                pkgSetting.origPackage = null;
6827            }
6828
6829            if (realName != null) {
6830                // Make a note of it.
6831                mTransferedPackages.add(pkg.packageName);
6832            }
6833
6834            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6835                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6836            }
6837
6838            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6839                // Check all shared libraries and map to their actual file path.
6840                // We only do this here for apps not on a system dir, because those
6841                // are the only ones that can fail an install due to this.  We
6842                // will take care of the system apps by updating all of their
6843                // library paths after the scan is done.
6844                updateSharedLibrariesLPw(pkg, null);
6845            }
6846
6847            if (mFoundPolicyFile) {
6848                SELinuxMMAC.assignSeinfoValue(pkg);
6849            }
6850
6851            pkg.applicationInfo.uid = pkgSetting.appId;
6852            pkg.mExtras = pkgSetting;
6853            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6854                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6855                    // We just determined the app is signed correctly, so bring
6856                    // over the latest parsed certs.
6857                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6858                } else {
6859                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6860                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6861                                "Package " + pkg.packageName + " upgrade keys do not match the "
6862                                + "previously installed version");
6863                    } else {
6864                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6865                        String msg = "System package " + pkg.packageName
6866                            + " signature changed; retaining data.";
6867                        reportSettingsProblem(Log.WARN, msg);
6868                    }
6869                }
6870            } else {
6871                try {
6872                    verifySignaturesLP(pkgSetting, pkg);
6873                    // We just determined the app is signed correctly, so bring
6874                    // over the latest parsed certs.
6875                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6876                } catch (PackageManagerException e) {
6877                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6878                        throw e;
6879                    }
6880                    // The signature has changed, but this package is in the system
6881                    // image...  let's recover!
6882                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6883                    // However...  if this package is part of a shared user, but it
6884                    // doesn't match the signature of the shared user, let's fail.
6885                    // What this means is that you can't change the signatures
6886                    // associated with an overall shared user, which doesn't seem all
6887                    // that unreasonable.
6888                    if (pkgSetting.sharedUser != null) {
6889                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6890                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6891                            throw new PackageManagerException(
6892                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6893                                            "Signature mismatch for shared user : "
6894                                            + pkgSetting.sharedUser);
6895                        }
6896                    }
6897                    // File a report about this.
6898                    String msg = "System package " + pkg.packageName
6899                        + " signature changed; retaining data.";
6900                    reportSettingsProblem(Log.WARN, msg);
6901                }
6902            }
6903            // Verify that this new package doesn't have any content providers
6904            // that conflict with existing packages.  Only do this if the
6905            // package isn't already installed, since we don't want to break
6906            // things that are installed.
6907            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6908                final int N = pkg.providers.size();
6909                int i;
6910                for (i=0; i<N; i++) {
6911                    PackageParser.Provider p = pkg.providers.get(i);
6912                    if (p.info.authority != null) {
6913                        String names[] = p.info.authority.split(";");
6914                        for (int j = 0; j < names.length; j++) {
6915                            if (mProvidersByAuthority.containsKey(names[j])) {
6916                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6917                                final String otherPackageName =
6918                                        ((other != null && other.getComponentName() != null) ?
6919                                                other.getComponentName().getPackageName() : "?");
6920                                throw new PackageManagerException(
6921                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6922                                                "Can't install because provider name " + names[j]
6923                                                + " (in package " + pkg.applicationInfo.packageName
6924                                                + ") is already used by " + otherPackageName);
6925                            }
6926                        }
6927                    }
6928                }
6929            }
6930
6931            if (pkg.mAdoptPermissions != null) {
6932                // This package wants to adopt ownership of permissions from
6933                // another package.
6934                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6935                    final String origName = pkg.mAdoptPermissions.get(i);
6936                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6937                    if (orig != null) {
6938                        if (verifyPackageUpdateLPr(orig, pkg)) {
6939                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6940                                    + pkg.packageName);
6941                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6942                        }
6943                    }
6944                }
6945            }
6946        }
6947
6948        final String pkgName = pkg.packageName;
6949
6950        final long scanFileTime = scanFile.lastModified();
6951        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6952        pkg.applicationInfo.processName = fixProcessName(
6953                pkg.applicationInfo.packageName,
6954                pkg.applicationInfo.processName,
6955                pkg.applicationInfo.uid);
6956
6957        File dataPath;
6958        if (mPlatformPackage == pkg) {
6959            // The system package is special.
6960            dataPath = new File(Environment.getDataDirectory(), "system");
6961
6962            pkg.applicationInfo.dataDir = dataPath.getPath();
6963
6964        } else {
6965            // This is a normal package, need to make its data directory.
6966            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6967                    UserHandle.USER_OWNER, pkg.packageName);
6968
6969            boolean uidError = false;
6970            if (dataPath.exists()) {
6971                int currentUid = 0;
6972                try {
6973                    StructStat stat = Os.stat(dataPath.getPath());
6974                    currentUid = stat.st_uid;
6975                } catch (ErrnoException e) {
6976                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6977                }
6978
6979                // If we have mismatched owners for the data path, we have a problem.
6980                if (currentUid != pkg.applicationInfo.uid) {
6981                    boolean recovered = false;
6982                    if (currentUid == 0) {
6983                        // The directory somehow became owned by root.  Wow.
6984                        // This is probably because the system was stopped while
6985                        // installd was in the middle of messing with its libs
6986                        // directory.  Ask installd to fix that.
6987                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6988                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6989                        if (ret >= 0) {
6990                            recovered = true;
6991                            String msg = "Package " + pkg.packageName
6992                                    + " unexpectedly changed to uid 0; recovered to " +
6993                                    + pkg.applicationInfo.uid;
6994                            reportSettingsProblem(Log.WARN, msg);
6995                        }
6996                    }
6997                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6998                            || (scanFlags&SCAN_BOOTING) != 0)) {
6999                        // If this is a system app, we can at least delete its
7000                        // current data so the application will still work.
7001                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7002                        if (ret >= 0) {
7003                            // TODO: Kill the processes first
7004                            // Old data gone!
7005                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7006                                    ? "System package " : "Third party package ";
7007                            String msg = prefix + pkg.packageName
7008                                    + " has changed from uid: "
7009                                    + currentUid + " to "
7010                                    + pkg.applicationInfo.uid + "; old data erased";
7011                            reportSettingsProblem(Log.WARN, msg);
7012                            recovered = true;
7013
7014                            // And now re-install the app.
7015                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7016                                    pkg.applicationInfo.seinfo);
7017                            if (ret == -1) {
7018                                // Ack should not happen!
7019                                msg = prefix + pkg.packageName
7020                                        + " could not have data directory re-created after delete.";
7021                                reportSettingsProblem(Log.WARN, msg);
7022                                throw new PackageManagerException(
7023                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
7024                            }
7025                        }
7026                        if (!recovered) {
7027                            mHasSystemUidErrors = true;
7028                        }
7029                    } else if (!recovered) {
7030                        // If we allow this install to proceed, we will be broken.
7031                        // Abort, abort!
7032                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7033                                "scanPackageLI");
7034                    }
7035                    if (!recovered) {
7036                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7037                            + pkg.applicationInfo.uid + "/fs_"
7038                            + currentUid;
7039                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7040                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7041                        String msg = "Package " + pkg.packageName
7042                                + " has mismatched uid: "
7043                                + currentUid + " on disk, "
7044                                + pkg.applicationInfo.uid + " in settings";
7045                        // writer
7046                        synchronized (mPackages) {
7047                            mSettings.mReadMessages.append(msg);
7048                            mSettings.mReadMessages.append('\n');
7049                            uidError = true;
7050                            if (!pkgSetting.uidError) {
7051                                reportSettingsProblem(Log.ERROR, msg);
7052                            }
7053                        }
7054                    }
7055                }
7056                pkg.applicationInfo.dataDir = dataPath.getPath();
7057                if (mShouldRestoreconData) {
7058                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7059                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7060                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7061                }
7062            } else {
7063                if (DEBUG_PACKAGE_SCANNING) {
7064                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7065                        Log.v(TAG, "Want this data dir: " + dataPath);
7066                }
7067                //invoke installer to do the actual installation
7068                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7069                        pkg.applicationInfo.seinfo);
7070                if (ret < 0) {
7071                    // Error from installer
7072                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7073                            "Unable to create data dirs [errorCode=" + ret + "]");
7074                }
7075
7076                if (dataPath.exists()) {
7077                    pkg.applicationInfo.dataDir = dataPath.getPath();
7078                } else {
7079                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
7080                    pkg.applicationInfo.dataDir = null;
7081                }
7082            }
7083
7084            pkgSetting.uidError = uidError;
7085        }
7086
7087        final String path = scanFile.getPath();
7088        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7089
7090        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7091            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7092
7093            // Some system apps still use directory structure for native libraries
7094            // in which case we might end up not detecting abi solely based on apk
7095            // structure. Try to detect abi based on directory structure.
7096            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7097                    pkg.applicationInfo.primaryCpuAbi == null) {
7098                setBundledAppAbisAndRoots(pkg, pkgSetting);
7099                setNativeLibraryPaths(pkg);
7100            }
7101
7102        } else {
7103            if ((scanFlags & SCAN_MOVE) != 0) {
7104                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7105                // but we already have this packages package info in the PackageSetting. We just
7106                // use that and derive the native library path based on the new codepath.
7107                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7108                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7109            }
7110
7111            // Set native library paths again. For moves, the path will be updated based on the
7112            // ABIs we've determined above. For non-moves, the path will be updated based on the
7113            // ABIs we determined during compilation, but the path will depend on the final
7114            // package path (after the rename away from the stage path).
7115            setNativeLibraryPaths(pkg);
7116        }
7117
7118        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7119        final int[] userIds = sUserManager.getUserIds();
7120        synchronized (mInstallLock) {
7121            // Make sure all user data directories are ready to roll; we're okay
7122            // if they already exist
7123            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7124                for (int userId : userIds) {
7125                    if (userId != 0) {
7126                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7127                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7128                                pkg.applicationInfo.seinfo);
7129                    }
7130                }
7131            }
7132
7133            // Create a native library symlink only if we have native libraries
7134            // and if the native libraries are 32 bit libraries. We do not provide
7135            // this symlink for 64 bit libraries.
7136            if (pkg.applicationInfo.primaryCpuAbi != null &&
7137                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7138                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7139                try {
7140                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7141                    for (int userId : userIds) {
7142                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7143                                nativeLibPath, userId) < 0) {
7144                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7145                                    "Failed linking native library dir (user=" + userId + ")");
7146                        }
7147                    }
7148                } finally {
7149                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7150                }
7151            }
7152        }
7153
7154        // This is a special case for the "system" package, where the ABI is
7155        // dictated by the zygote configuration (and init.rc). We should keep track
7156        // of this ABI so that we can deal with "normal" applications that run under
7157        // the same UID correctly.
7158        if (mPlatformPackage == pkg) {
7159            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7160                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7161        }
7162
7163        // If there's a mismatch between the abi-override in the package setting
7164        // and the abiOverride specified for the install. Warn about this because we
7165        // would've already compiled the app without taking the package setting into
7166        // account.
7167        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7168            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7169                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7170                        " for package: " + pkg.packageName);
7171            }
7172        }
7173
7174        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7175        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7176        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7177
7178        // Copy the derived override back to the parsed package, so that we can
7179        // update the package settings accordingly.
7180        pkg.cpuAbiOverride = cpuAbiOverride;
7181
7182        if (DEBUG_ABI_SELECTION) {
7183            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7184                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7185                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7186        }
7187
7188        // Push the derived path down into PackageSettings so we know what to
7189        // clean up at uninstall time.
7190        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7191
7192        if (DEBUG_ABI_SELECTION) {
7193            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7194                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7195                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7196        }
7197
7198        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7199            // We don't do this here during boot because we can do it all
7200            // at once after scanning all existing packages.
7201            //
7202            // We also do this *before* we perform dexopt on this package, so that
7203            // we can avoid redundant dexopts, and also to make sure we've got the
7204            // code and package path correct.
7205            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7206                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7207        }
7208
7209        if ((scanFlags & SCAN_NO_DEX) == 0) {
7210            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7211
7212            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7213                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7214                    (scanFlags & SCAN_BOOTING) == 0);
7215
7216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7217            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7218                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7219            }
7220        }
7221        if (mFactoryTest && pkg.requestedPermissions.contains(
7222                android.Manifest.permission.FACTORY_TEST)) {
7223            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7224        }
7225
7226        ArrayList<PackageParser.Package> clientLibPkgs = null;
7227
7228        // writer
7229        synchronized (mPackages) {
7230            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7231                // Only system apps can add new shared libraries.
7232                if (pkg.libraryNames != null) {
7233                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7234                        String name = pkg.libraryNames.get(i);
7235                        boolean allowed = false;
7236                        if (pkg.isUpdatedSystemApp()) {
7237                            // New library entries can only be added through the
7238                            // system image.  This is important to get rid of a lot
7239                            // of nasty edge cases: for example if we allowed a non-
7240                            // system update of the app to add a library, then uninstalling
7241                            // the update would make the library go away, and assumptions
7242                            // we made such as through app install filtering would now
7243                            // have allowed apps on the device which aren't compatible
7244                            // with it.  Better to just have the restriction here, be
7245                            // conservative, and create many fewer cases that can negatively
7246                            // impact the user experience.
7247                            final PackageSetting sysPs = mSettings
7248                                    .getDisabledSystemPkgLPr(pkg.packageName);
7249                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7250                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7251                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7252                                        allowed = true;
7253                                        allowed = true;
7254                                        break;
7255                                    }
7256                                }
7257                            }
7258                        } else {
7259                            allowed = true;
7260                        }
7261                        if (allowed) {
7262                            if (!mSharedLibraries.containsKey(name)) {
7263                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7264                            } else if (!name.equals(pkg.packageName)) {
7265                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7266                                        + name + " already exists; skipping");
7267                            }
7268                        } else {
7269                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7270                                    + name + " that is not declared on system image; skipping");
7271                        }
7272                    }
7273                    if ((scanFlags&SCAN_BOOTING) == 0) {
7274                        // If we are not booting, we need to update any applications
7275                        // that are clients of our shared library.  If we are booting,
7276                        // this will all be done once the scan is complete.
7277                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7278                    }
7279                }
7280            }
7281        }
7282
7283        // We also need to dexopt any apps that are dependent on this library.  Note that
7284        // if these fail, we should abort the install since installing the library will
7285        // result in some apps being broken.
7286        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7287        try {
7288            if (clientLibPkgs != null) {
7289                if ((scanFlags & SCAN_NO_DEX) == 0) {
7290                    for (int i = 0; i < clientLibPkgs.size(); i++) {
7291                        PackageParser.Package clientPkg = clientLibPkgs.get(i);
7292                        int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7293                                null /* instruction sets */, forceDex,
7294                                (scanFlags & SCAN_DEFER_DEX) != 0, false,
7295                                (scanFlags & SCAN_BOOTING) == 0);
7296                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7297                            throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7298                                    "scanPackageLI failed to dexopt clientLibPkgs");
7299                        }
7300                    }
7301                }
7302            }
7303        } finally {
7304            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7305        }
7306
7307        // Request the ActivityManager to kill the process(only for existing packages)
7308        // so that we do not end up in a confused state while the user is still using the older
7309        // version of the application while the new one gets installed.
7310        if ((scanFlags & SCAN_REPLACING) != 0) {
7311            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7312
7313            killApplication(pkg.applicationInfo.packageName,
7314                        pkg.applicationInfo.uid, "replace pkg");
7315
7316            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7317        }
7318
7319        // Also need to kill any apps that are dependent on the library.
7320        if (clientLibPkgs != null) {
7321            for (int i=0; i<clientLibPkgs.size(); i++) {
7322                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7323                killApplication(clientPkg.applicationInfo.packageName,
7324                        clientPkg.applicationInfo.uid, "update lib");
7325            }
7326        }
7327
7328        // Make sure we're not adding any bogus keyset info
7329        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7330        ksms.assertScannedPackageValid(pkg);
7331
7332        // writer
7333        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7334
7335        boolean createIdmapFailed = false;
7336        synchronized (mPackages) {
7337            // We don't expect installation to fail beyond this point
7338
7339            // Add the new setting to mSettings
7340            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7341            // Add the new setting to mPackages
7342            mPackages.put(pkg.applicationInfo.packageName, pkg);
7343            // Make sure we don't accidentally delete its data.
7344            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7345            while (iter.hasNext()) {
7346                PackageCleanItem item = iter.next();
7347                if (pkgName.equals(item.packageName)) {
7348                    iter.remove();
7349                }
7350            }
7351
7352            // Take care of first install / last update times.
7353            if (currentTime != 0) {
7354                if (pkgSetting.firstInstallTime == 0) {
7355                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7356                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7357                    pkgSetting.lastUpdateTime = currentTime;
7358                }
7359            } else if (pkgSetting.firstInstallTime == 0) {
7360                // We need *something*.  Take time time stamp of the file.
7361                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7362            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7363                if (scanFileTime != pkgSetting.timeStamp) {
7364                    // A package on the system image has changed; consider this
7365                    // to be an update.
7366                    pkgSetting.lastUpdateTime = scanFileTime;
7367                }
7368            }
7369
7370            // Add the package's KeySets to the global KeySetManagerService
7371            ksms.addScannedPackageLPw(pkg);
7372
7373            int N = pkg.providers.size();
7374            StringBuilder r = null;
7375            int i;
7376            for (i=0; i<N; i++) {
7377                PackageParser.Provider p = pkg.providers.get(i);
7378                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7379                        p.info.processName, pkg.applicationInfo.uid);
7380                mProviders.addProvider(p);
7381                p.syncable = p.info.isSyncable;
7382                if (p.info.authority != null) {
7383                    String names[] = p.info.authority.split(";");
7384                    p.info.authority = null;
7385                    for (int j = 0; j < names.length; j++) {
7386                        if (j == 1 && p.syncable) {
7387                            // We only want the first authority for a provider to possibly be
7388                            // syncable, so if we already added this provider using a different
7389                            // authority clear the syncable flag. We copy the provider before
7390                            // changing it because the mProviders object contains a reference
7391                            // to a provider that we don't want to change.
7392                            // Only do this for the second authority since the resulting provider
7393                            // object can be the same for all future authorities for this provider.
7394                            p = new PackageParser.Provider(p);
7395                            p.syncable = false;
7396                        }
7397                        if (!mProvidersByAuthority.containsKey(names[j])) {
7398                            mProvidersByAuthority.put(names[j], p);
7399                            if (p.info.authority == null) {
7400                                p.info.authority = names[j];
7401                            } else {
7402                                p.info.authority = p.info.authority + ";" + names[j];
7403                            }
7404                            if (DEBUG_PACKAGE_SCANNING) {
7405                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7406                                    Log.d(TAG, "Registered content provider: " + names[j]
7407                                            + ", className = " + p.info.name + ", isSyncable = "
7408                                            + p.info.isSyncable);
7409                            }
7410                        } else {
7411                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7412                            Slog.w(TAG, "Skipping provider name " + names[j] +
7413                                    " (in package " + pkg.applicationInfo.packageName +
7414                                    "): name already used by "
7415                                    + ((other != null && other.getComponentName() != null)
7416                                            ? other.getComponentName().getPackageName() : "?"));
7417                        }
7418                    }
7419                }
7420                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7421                    if (r == null) {
7422                        r = new StringBuilder(256);
7423                    } else {
7424                        r.append(' ');
7425                    }
7426                    r.append(p.info.name);
7427                }
7428            }
7429            if (r != null) {
7430                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7431            }
7432
7433            N = pkg.services.size();
7434            r = null;
7435            for (i=0; i<N; i++) {
7436                PackageParser.Service s = pkg.services.get(i);
7437                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7438                        s.info.processName, pkg.applicationInfo.uid);
7439                mServices.addService(s);
7440                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7441                    if (r == null) {
7442                        r = new StringBuilder(256);
7443                    } else {
7444                        r.append(' ');
7445                    }
7446                    r.append(s.info.name);
7447                }
7448            }
7449            if (r != null) {
7450                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7451            }
7452
7453            N = pkg.receivers.size();
7454            r = null;
7455            for (i=0; i<N; i++) {
7456                PackageParser.Activity a = pkg.receivers.get(i);
7457                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7458                        a.info.processName, pkg.applicationInfo.uid);
7459                mReceivers.addActivity(a, "receiver");
7460                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7461                    if (r == null) {
7462                        r = new StringBuilder(256);
7463                    } else {
7464                        r.append(' ');
7465                    }
7466                    r.append(a.info.name);
7467                }
7468            }
7469            if (r != null) {
7470                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7471            }
7472
7473            N = pkg.activities.size();
7474            r = null;
7475            for (i=0; i<N; i++) {
7476                PackageParser.Activity a = pkg.activities.get(i);
7477                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7478                        a.info.processName, pkg.applicationInfo.uid);
7479                mActivities.addActivity(a, "activity");
7480                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7481                    if (r == null) {
7482                        r = new StringBuilder(256);
7483                    } else {
7484                        r.append(' ');
7485                    }
7486                    r.append(a.info.name);
7487                }
7488            }
7489            if (r != null) {
7490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7491            }
7492
7493            N = pkg.permissionGroups.size();
7494            r = null;
7495            for (i=0; i<N; i++) {
7496                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7497                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7498                if (cur == null) {
7499                    mPermissionGroups.put(pg.info.name, pg);
7500                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7501                        if (r == null) {
7502                            r = new StringBuilder(256);
7503                        } else {
7504                            r.append(' ');
7505                        }
7506                        r.append(pg.info.name);
7507                    }
7508                } else {
7509                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7510                            + pg.info.packageName + " ignored: original from "
7511                            + cur.info.packageName);
7512                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7513                        if (r == null) {
7514                            r = new StringBuilder(256);
7515                        } else {
7516                            r.append(' ');
7517                        }
7518                        r.append("DUP:");
7519                        r.append(pg.info.name);
7520                    }
7521                }
7522            }
7523            if (r != null) {
7524                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7525            }
7526
7527            N = pkg.permissions.size();
7528            r = null;
7529            for (i=0; i<N; i++) {
7530                PackageParser.Permission p = pkg.permissions.get(i);
7531
7532                // Assume by default that we did not install this permission into the system.
7533                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7534
7535                // Now that permission groups have a special meaning, we ignore permission
7536                // groups for legacy apps to prevent unexpected behavior. In particular,
7537                // permissions for one app being granted to someone just becuase they happen
7538                // to be in a group defined by another app (before this had no implications).
7539                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7540                    p.group = mPermissionGroups.get(p.info.group);
7541                    // Warn for a permission in an unknown group.
7542                    if (p.info.group != null && p.group == null) {
7543                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7544                                + p.info.packageName + " in an unknown group " + p.info.group);
7545                    }
7546                }
7547
7548                ArrayMap<String, BasePermission> permissionMap =
7549                        p.tree ? mSettings.mPermissionTrees
7550                                : mSettings.mPermissions;
7551                BasePermission bp = permissionMap.get(p.info.name);
7552
7553                // Allow system apps to redefine non-system permissions
7554                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7555                    final boolean currentOwnerIsSystem = (bp.perm != null
7556                            && isSystemApp(bp.perm.owner));
7557                    if (isSystemApp(p.owner)) {
7558                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7559                            // It's a built-in permission and no owner, take ownership now
7560                            bp.packageSetting = pkgSetting;
7561                            bp.perm = p;
7562                            bp.uid = pkg.applicationInfo.uid;
7563                            bp.sourcePackage = p.info.packageName;
7564                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7565                        } else if (!currentOwnerIsSystem) {
7566                            String msg = "New decl " + p.owner + " of permission  "
7567                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7568                            reportSettingsProblem(Log.WARN, msg);
7569                            bp = null;
7570                        }
7571                    }
7572                }
7573
7574                if (bp == null) {
7575                    bp = new BasePermission(p.info.name, p.info.packageName,
7576                            BasePermission.TYPE_NORMAL);
7577                    permissionMap.put(p.info.name, bp);
7578                }
7579
7580                if (bp.perm == null) {
7581                    if (bp.sourcePackage == null
7582                            || bp.sourcePackage.equals(p.info.packageName)) {
7583                        BasePermission tree = findPermissionTreeLP(p.info.name);
7584                        if (tree == null
7585                                || tree.sourcePackage.equals(p.info.packageName)) {
7586                            bp.packageSetting = pkgSetting;
7587                            bp.perm = p;
7588                            bp.uid = pkg.applicationInfo.uid;
7589                            bp.sourcePackage = p.info.packageName;
7590                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7591                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7592                                if (r == null) {
7593                                    r = new StringBuilder(256);
7594                                } else {
7595                                    r.append(' ');
7596                                }
7597                                r.append(p.info.name);
7598                            }
7599                        } else {
7600                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7601                                    + p.info.packageName + " ignored: base tree "
7602                                    + tree.name + " is from package "
7603                                    + tree.sourcePackage);
7604                        }
7605                    } else {
7606                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7607                                + p.info.packageName + " ignored: original from "
7608                                + bp.sourcePackage);
7609                    }
7610                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7611                    if (r == null) {
7612                        r = new StringBuilder(256);
7613                    } else {
7614                        r.append(' ');
7615                    }
7616                    r.append("DUP:");
7617                    r.append(p.info.name);
7618                }
7619                if (bp.perm == p) {
7620                    bp.protectionLevel = p.info.protectionLevel;
7621                }
7622            }
7623
7624            if (r != null) {
7625                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7626            }
7627
7628            N = pkg.instrumentation.size();
7629            r = null;
7630            for (i=0; i<N; i++) {
7631                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7632                a.info.packageName = pkg.applicationInfo.packageName;
7633                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7634                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7635                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7636                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7637                a.info.dataDir = pkg.applicationInfo.dataDir;
7638
7639                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7640                // need other information about the application, like the ABI and what not ?
7641                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7642                mInstrumentation.put(a.getComponentName(), a);
7643                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7644                    if (r == null) {
7645                        r = new StringBuilder(256);
7646                    } else {
7647                        r.append(' ');
7648                    }
7649                    r.append(a.info.name);
7650                }
7651            }
7652            if (r != null) {
7653                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7654            }
7655
7656            if (pkg.protectedBroadcasts != null) {
7657                N = pkg.protectedBroadcasts.size();
7658                for (i=0; i<N; i++) {
7659                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7660                }
7661            }
7662
7663            pkgSetting.setTimeStamp(scanFileTime);
7664
7665            // Create idmap files for pairs of (packages, overlay packages).
7666            // Note: "android", ie framework-res.apk, is handled by native layers.
7667            if (pkg.mOverlayTarget != null) {
7668                // This is an overlay package.
7669                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7670                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7671                        mOverlays.put(pkg.mOverlayTarget,
7672                                new ArrayMap<String, PackageParser.Package>());
7673                    }
7674                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7675                    map.put(pkg.packageName, pkg);
7676                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7677                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7678                        createIdmapFailed = true;
7679                    }
7680                }
7681            } else if (mOverlays.containsKey(pkg.packageName) &&
7682                    !pkg.packageName.equals("android")) {
7683                // This is a regular package, with one or more known overlay packages.
7684                createIdmapsForPackageLI(pkg);
7685            }
7686        }
7687
7688        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7689
7690        if (createIdmapFailed) {
7691            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7692                    "scanPackageLI failed to createIdmap");
7693        }
7694        return pkg;
7695    }
7696
7697    /**
7698     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7699     * is derived purely on the basis of the contents of {@code scanFile} and
7700     * {@code cpuAbiOverride}.
7701     *
7702     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7703     */
7704    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7705                                 String cpuAbiOverride, boolean extractLibs)
7706            throws PackageManagerException {
7707        // TODO: We can probably be smarter about this stuff. For installed apps,
7708        // we can calculate this information at install time once and for all. For
7709        // system apps, we can probably assume that this information doesn't change
7710        // after the first boot scan. As things stand, we do lots of unnecessary work.
7711
7712        // Give ourselves some initial paths; we'll come back for another
7713        // pass once we've determined ABI below.
7714        setNativeLibraryPaths(pkg);
7715
7716        // We would never need to extract libs for forward-locked and external packages,
7717        // since the container service will do it for us. We shouldn't attempt to
7718        // extract libs from system app when it was not updated.
7719        if (pkg.isForwardLocked() || isExternal(pkg) ||
7720            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7721            extractLibs = false;
7722        }
7723
7724        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7725        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7726
7727        NativeLibraryHelper.Handle handle = null;
7728        try {
7729            handle = NativeLibraryHelper.Handle.create(pkg);
7730            // TODO(multiArch): This can be null for apps that didn't go through the
7731            // usual installation process. We can calculate it again, like we
7732            // do during install time.
7733            //
7734            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7735            // unnecessary.
7736            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7737
7738            // Null out the abis so that they can be recalculated.
7739            pkg.applicationInfo.primaryCpuAbi = null;
7740            pkg.applicationInfo.secondaryCpuAbi = null;
7741            if (isMultiArch(pkg.applicationInfo)) {
7742                // Warn if we've set an abiOverride for multi-lib packages..
7743                // By definition, we need to copy both 32 and 64 bit libraries for
7744                // such packages.
7745                if (pkg.cpuAbiOverride != null
7746                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7747                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7748                }
7749
7750                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7751                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7752                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7753                    if (extractLibs) {
7754                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7755                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7756                                useIsaSpecificSubdirs);
7757                    } else {
7758                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7759                    }
7760                }
7761
7762                maybeThrowExceptionForMultiArchCopy(
7763                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7764
7765                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7766                    if (extractLibs) {
7767                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7768                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7769                                useIsaSpecificSubdirs);
7770                    } else {
7771                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7772                    }
7773                }
7774
7775                maybeThrowExceptionForMultiArchCopy(
7776                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7777
7778                if (abi64 >= 0) {
7779                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7780                }
7781
7782                if (abi32 >= 0) {
7783                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7784                    if (abi64 >= 0) {
7785                        pkg.applicationInfo.secondaryCpuAbi = abi;
7786                    } else {
7787                        pkg.applicationInfo.primaryCpuAbi = abi;
7788                    }
7789                }
7790            } else {
7791                String[] abiList = (cpuAbiOverride != null) ?
7792                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7793
7794                // Enable gross and lame hacks for apps that are built with old
7795                // SDK tools. We must scan their APKs for renderscript bitcode and
7796                // not launch them if it's present. Don't bother checking on devices
7797                // that don't have 64 bit support.
7798                boolean needsRenderScriptOverride = false;
7799                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7800                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7801                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7802                    needsRenderScriptOverride = true;
7803                }
7804
7805                final int copyRet;
7806                if (extractLibs) {
7807                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7808                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7809                } else {
7810                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7811                }
7812
7813                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7814                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7815                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7816                }
7817
7818                if (copyRet >= 0) {
7819                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7820                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7821                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7822                } else if (needsRenderScriptOverride) {
7823                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7824                }
7825            }
7826        } catch (IOException ioe) {
7827            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7828        } finally {
7829            IoUtils.closeQuietly(handle);
7830        }
7831
7832        // Now that we've calculated the ABIs and determined if it's an internal app,
7833        // we will go ahead and populate the nativeLibraryPath.
7834        setNativeLibraryPaths(pkg);
7835    }
7836
7837    /**
7838     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7839     * i.e, so that all packages can be run inside a single process if required.
7840     *
7841     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7842     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7843     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7844     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7845     * updating a package that belongs to a shared user.
7846     *
7847     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7848     * adds unnecessary complexity.
7849     */
7850    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7851            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7852            boolean bootComplete) {
7853        String requiredInstructionSet = null;
7854        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7855            requiredInstructionSet = VMRuntime.getInstructionSet(
7856                     scannedPackage.applicationInfo.primaryCpuAbi);
7857        }
7858
7859        PackageSetting requirer = null;
7860        for (PackageSetting ps : packagesForUser) {
7861            // If packagesForUser contains scannedPackage, we skip it. This will happen
7862            // when scannedPackage is an update of an existing package. Without this check,
7863            // we will never be able to change the ABI of any package belonging to a shared
7864            // user, even if it's compatible with other packages.
7865            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7866                if (ps.primaryCpuAbiString == null) {
7867                    continue;
7868                }
7869
7870                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7871                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7872                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7873                    // this but there's not much we can do.
7874                    String errorMessage = "Instruction set mismatch, "
7875                            + ((requirer == null) ? "[caller]" : requirer)
7876                            + " requires " + requiredInstructionSet + " whereas " + ps
7877                            + " requires " + instructionSet;
7878                    Slog.w(TAG, errorMessage);
7879                }
7880
7881                if (requiredInstructionSet == null) {
7882                    requiredInstructionSet = instructionSet;
7883                    requirer = ps;
7884                }
7885            }
7886        }
7887
7888        if (requiredInstructionSet != null) {
7889            String adjustedAbi;
7890            if (requirer != null) {
7891                // requirer != null implies that either scannedPackage was null or that scannedPackage
7892                // did not require an ABI, in which case we have to adjust scannedPackage to match
7893                // the ABI of the set (which is the same as requirer's ABI)
7894                adjustedAbi = requirer.primaryCpuAbiString;
7895                if (scannedPackage != null) {
7896                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7897                }
7898            } else {
7899                // requirer == null implies that we're updating all ABIs in the set to
7900                // match scannedPackage.
7901                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7902            }
7903
7904            for (PackageSetting ps : packagesForUser) {
7905                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7906                    if (ps.primaryCpuAbiString != null) {
7907                        continue;
7908                    }
7909
7910                    ps.primaryCpuAbiString = adjustedAbi;
7911                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7912                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7913                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7914
7915                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7916
7917                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7918                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7919                                bootComplete);
7920
7921                        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7922                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7923                            ps.primaryCpuAbiString = null;
7924                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7925                            return;
7926                        } else {
7927                            mInstaller.rmdex(ps.codePathString,
7928                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7929                        }
7930                    }
7931                }
7932            }
7933        }
7934    }
7935
7936    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7937        synchronized (mPackages) {
7938            mResolverReplaced = true;
7939            // Set up information for custom user intent resolution activity.
7940            mResolveActivity.applicationInfo = pkg.applicationInfo;
7941            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7942            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7943            mResolveActivity.processName = pkg.applicationInfo.packageName;
7944            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7945            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7946                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7947            mResolveActivity.theme = 0;
7948            mResolveActivity.exported = true;
7949            mResolveActivity.enabled = true;
7950            mResolveInfo.activityInfo = mResolveActivity;
7951            mResolveInfo.priority = 0;
7952            mResolveInfo.preferredOrder = 0;
7953            mResolveInfo.match = 0;
7954            mResolveComponentName = mCustomResolverComponentName;
7955            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7956                    mResolveComponentName);
7957        }
7958    }
7959
7960    private static String calculateBundledApkRoot(final String codePathString) {
7961        final File codePath = new File(codePathString);
7962        final File codeRoot;
7963        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7964            codeRoot = Environment.getRootDirectory();
7965        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7966            codeRoot = Environment.getOemDirectory();
7967        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7968            codeRoot = Environment.getVendorDirectory();
7969        } else {
7970            // Unrecognized code path; take its top real segment as the apk root:
7971            // e.g. /something/app/blah.apk => /something
7972            try {
7973                File f = codePath.getCanonicalFile();
7974                File parent = f.getParentFile();    // non-null because codePath is a file
7975                File tmp;
7976                while ((tmp = parent.getParentFile()) != null) {
7977                    f = parent;
7978                    parent = tmp;
7979                }
7980                codeRoot = f;
7981                Slog.w(TAG, "Unrecognized code path "
7982                        + codePath + " - using " + codeRoot);
7983            } catch (IOException e) {
7984                // Can't canonicalize the code path -- shenanigans?
7985                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7986                return Environment.getRootDirectory().getPath();
7987            }
7988        }
7989        return codeRoot.getPath();
7990    }
7991
7992    /**
7993     * Derive and set the location of native libraries for the given package,
7994     * which varies depending on where and how the package was installed.
7995     */
7996    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7997        final ApplicationInfo info = pkg.applicationInfo;
7998        final String codePath = pkg.codePath;
7999        final File codeFile = new File(codePath);
8000        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8001        final boolean asecApp = info.isForwardLocked() || isExternal(info);
8002
8003        info.nativeLibraryRootDir = null;
8004        info.nativeLibraryRootRequiresIsa = false;
8005        info.nativeLibraryDir = null;
8006        info.secondaryNativeLibraryDir = null;
8007
8008        if (isApkFile(codeFile)) {
8009            // Monolithic install
8010            if (bundledApp) {
8011                // If "/system/lib64/apkname" exists, assume that is the per-package
8012                // native library directory to use; otherwise use "/system/lib/apkname".
8013                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8014                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8015                        getPrimaryInstructionSet(info));
8016
8017                // This is a bundled system app so choose the path based on the ABI.
8018                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8019                // is just the default path.
8020                final String apkName = deriveCodePathName(codePath);
8021                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8022                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8023                        apkName).getAbsolutePath();
8024
8025                if (info.secondaryCpuAbi != null) {
8026                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8027                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8028                            secondaryLibDir, apkName).getAbsolutePath();
8029                }
8030            } else if (asecApp) {
8031                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8032                        .getAbsolutePath();
8033            } else {
8034                final String apkName = deriveCodePathName(codePath);
8035                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8036                        .getAbsolutePath();
8037            }
8038
8039            info.nativeLibraryRootRequiresIsa = false;
8040            info.nativeLibraryDir = info.nativeLibraryRootDir;
8041        } else {
8042            // Cluster install
8043            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8044            info.nativeLibraryRootRequiresIsa = true;
8045
8046            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8047                    getPrimaryInstructionSet(info)).getAbsolutePath();
8048
8049            if (info.secondaryCpuAbi != null) {
8050                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8051                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8052            }
8053        }
8054    }
8055
8056    /**
8057     * Calculate the abis and roots for a bundled app. These can uniquely
8058     * be determined from the contents of the system partition, i.e whether
8059     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8060     * of this information, and instead assume that the system was built
8061     * sensibly.
8062     */
8063    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8064                                           PackageSetting pkgSetting) {
8065        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8066
8067        // If "/system/lib64/apkname" exists, assume that is the per-package
8068        // native library directory to use; otherwise use "/system/lib/apkname".
8069        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8070        setBundledAppAbi(pkg, apkRoot, apkName);
8071        // pkgSetting might be null during rescan following uninstall of updates
8072        // to a bundled app, so accommodate that possibility.  The settings in
8073        // that case will be established later from the parsed package.
8074        //
8075        // If the settings aren't null, sync them up with what we've just derived.
8076        // note that apkRoot isn't stored in the package settings.
8077        if (pkgSetting != null) {
8078            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8079            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8080        }
8081    }
8082
8083    /**
8084     * Deduces the ABI of a bundled app and sets the relevant fields on the
8085     * parsed pkg object.
8086     *
8087     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8088     *        under which system libraries are installed.
8089     * @param apkName the name of the installed package.
8090     */
8091    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8092        final File codeFile = new File(pkg.codePath);
8093
8094        final boolean has64BitLibs;
8095        final boolean has32BitLibs;
8096        if (isApkFile(codeFile)) {
8097            // Monolithic install
8098            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8099            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8100        } else {
8101            // Cluster install
8102            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8103            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8104                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8105                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8106                has64BitLibs = (new File(rootDir, isa)).exists();
8107            } else {
8108                has64BitLibs = false;
8109            }
8110            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8111                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8112                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8113                has32BitLibs = (new File(rootDir, isa)).exists();
8114            } else {
8115                has32BitLibs = false;
8116            }
8117        }
8118
8119        if (has64BitLibs && !has32BitLibs) {
8120            // The package has 64 bit libs, but not 32 bit libs. Its primary
8121            // ABI should be 64 bit. We can safely assume here that the bundled
8122            // native libraries correspond to the most preferred ABI in the list.
8123
8124            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8125            pkg.applicationInfo.secondaryCpuAbi = null;
8126        } else if (has32BitLibs && !has64BitLibs) {
8127            // The package has 32 bit libs but not 64 bit libs. Its primary
8128            // ABI should be 32 bit.
8129
8130            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8131            pkg.applicationInfo.secondaryCpuAbi = null;
8132        } else if (has32BitLibs && has64BitLibs) {
8133            // The application has both 64 and 32 bit bundled libraries. We check
8134            // here that the app declares multiArch support, and warn if it doesn't.
8135            //
8136            // We will be lenient here and record both ABIs. The primary will be the
8137            // ABI that's higher on the list, i.e, a device that's configured to prefer
8138            // 64 bit apps will see a 64 bit primary ABI,
8139
8140            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8141                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8142            }
8143
8144            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8145                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8146                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8147            } else {
8148                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8149                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8150            }
8151        } else {
8152            pkg.applicationInfo.primaryCpuAbi = null;
8153            pkg.applicationInfo.secondaryCpuAbi = null;
8154        }
8155    }
8156
8157    private void killApplication(String pkgName, int appId, String reason) {
8158        // Request the ActivityManager to kill the process(only for existing packages)
8159        // so that we do not end up in a confused state while the user is still using the older
8160        // version of the application while the new one gets installed.
8161        IActivityManager am = ActivityManagerNative.getDefault();
8162        if (am != null) {
8163            try {
8164                am.killApplicationWithAppId(pkgName, appId, reason);
8165            } catch (RemoteException e) {
8166            }
8167        }
8168    }
8169
8170    void removePackageLI(PackageSetting ps, boolean chatty) {
8171        if (DEBUG_INSTALL) {
8172            if (chatty)
8173                Log.d(TAG, "Removing package " + ps.name);
8174        }
8175
8176        // writer
8177        synchronized (mPackages) {
8178            mPackages.remove(ps.name);
8179            final PackageParser.Package pkg = ps.pkg;
8180            if (pkg != null) {
8181                cleanPackageDataStructuresLILPw(pkg, chatty);
8182            }
8183        }
8184    }
8185
8186    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8187        if (DEBUG_INSTALL) {
8188            if (chatty)
8189                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8190        }
8191
8192        // writer
8193        synchronized (mPackages) {
8194            mPackages.remove(pkg.applicationInfo.packageName);
8195            cleanPackageDataStructuresLILPw(pkg, chatty);
8196        }
8197    }
8198
8199    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8200        int N = pkg.providers.size();
8201        StringBuilder r = null;
8202        int i;
8203        for (i=0; i<N; i++) {
8204            PackageParser.Provider p = pkg.providers.get(i);
8205            mProviders.removeProvider(p);
8206            if (p.info.authority == null) {
8207
8208                /* There was another ContentProvider with this authority when
8209                 * this app was installed so this authority is null,
8210                 * Ignore it as we don't have to unregister the provider.
8211                 */
8212                continue;
8213            }
8214            String names[] = p.info.authority.split(";");
8215            for (int j = 0; j < names.length; j++) {
8216                if (mProvidersByAuthority.get(names[j]) == p) {
8217                    mProvidersByAuthority.remove(names[j]);
8218                    if (DEBUG_REMOVE) {
8219                        if (chatty)
8220                            Log.d(TAG, "Unregistered content provider: " + names[j]
8221                                    + ", className = " + p.info.name + ", isSyncable = "
8222                                    + p.info.isSyncable);
8223                    }
8224                }
8225            }
8226            if (DEBUG_REMOVE && chatty) {
8227                if (r == null) {
8228                    r = new StringBuilder(256);
8229                } else {
8230                    r.append(' ');
8231                }
8232                r.append(p.info.name);
8233            }
8234        }
8235        if (r != null) {
8236            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8237        }
8238
8239        N = pkg.services.size();
8240        r = null;
8241        for (i=0; i<N; i++) {
8242            PackageParser.Service s = pkg.services.get(i);
8243            mServices.removeService(s);
8244            if (chatty) {
8245                if (r == null) {
8246                    r = new StringBuilder(256);
8247                } else {
8248                    r.append(' ');
8249                }
8250                r.append(s.info.name);
8251            }
8252        }
8253        if (r != null) {
8254            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8255        }
8256
8257        N = pkg.receivers.size();
8258        r = null;
8259        for (i=0; i<N; i++) {
8260            PackageParser.Activity a = pkg.receivers.get(i);
8261            mReceivers.removeActivity(a, "receiver");
8262            if (DEBUG_REMOVE && chatty) {
8263                if (r == null) {
8264                    r = new StringBuilder(256);
8265                } else {
8266                    r.append(' ');
8267                }
8268                r.append(a.info.name);
8269            }
8270        }
8271        if (r != null) {
8272            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8273        }
8274
8275        N = pkg.activities.size();
8276        r = null;
8277        for (i=0; i<N; i++) {
8278            PackageParser.Activity a = pkg.activities.get(i);
8279            mActivities.removeActivity(a, "activity");
8280            if (DEBUG_REMOVE && chatty) {
8281                if (r == null) {
8282                    r = new StringBuilder(256);
8283                } else {
8284                    r.append(' ');
8285                }
8286                r.append(a.info.name);
8287            }
8288        }
8289        if (r != null) {
8290            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8291        }
8292
8293        N = pkg.permissions.size();
8294        r = null;
8295        for (i=0; i<N; i++) {
8296            PackageParser.Permission p = pkg.permissions.get(i);
8297            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8298            if (bp == null) {
8299                bp = mSettings.mPermissionTrees.get(p.info.name);
8300            }
8301            if (bp != null && bp.perm == p) {
8302                bp.perm = null;
8303                if (DEBUG_REMOVE && chatty) {
8304                    if (r == null) {
8305                        r = new StringBuilder(256);
8306                    } else {
8307                        r.append(' ');
8308                    }
8309                    r.append(p.info.name);
8310                }
8311            }
8312            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8313                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8314                if (appOpPerms != null) {
8315                    appOpPerms.remove(pkg.packageName);
8316                }
8317            }
8318        }
8319        if (r != null) {
8320            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8321        }
8322
8323        N = pkg.requestedPermissions.size();
8324        r = null;
8325        for (i=0; i<N; i++) {
8326            String perm = pkg.requestedPermissions.get(i);
8327            BasePermission bp = mSettings.mPermissions.get(perm);
8328            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8329                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8330                if (appOpPerms != null) {
8331                    appOpPerms.remove(pkg.packageName);
8332                    if (appOpPerms.isEmpty()) {
8333                        mAppOpPermissionPackages.remove(perm);
8334                    }
8335                }
8336            }
8337        }
8338        if (r != null) {
8339            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8340        }
8341
8342        N = pkg.instrumentation.size();
8343        r = null;
8344        for (i=0; i<N; i++) {
8345            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8346            mInstrumentation.remove(a.getComponentName());
8347            if (DEBUG_REMOVE && chatty) {
8348                if (r == null) {
8349                    r = new StringBuilder(256);
8350                } else {
8351                    r.append(' ');
8352                }
8353                r.append(a.info.name);
8354            }
8355        }
8356        if (r != null) {
8357            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8358        }
8359
8360        r = null;
8361        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8362            // Only system apps can hold shared libraries.
8363            if (pkg.libraryNames != null) {
8364                for (i=0; i<pkg.libraryNames.size(); i++) {
8365                    String name = pkg.libraryNames.get(i);
8366                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8367                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8368                        mSharedLibraries.remove(name);
8369                        if (DEBUG_REMOVE && chatty) {
8370                            if (r == null) {
8371                                r = new StringBuilder(256);
8372                            } else {
8373                                r.append(' ');
8374                            }
8375                            r.append(name);
8376                        }
8377                    }
8378                }
8379            }
8380        }
8381        if (r != null) {
8382            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8383        }
8384    }
8385
8386    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8387        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8388            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8389                return true;
8390            }
8391        }
8392        return false;
8393    }
8394
8395    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8396    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8397    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8398
8399    private void updatePermissionsLPw(String changingPkg,
8400            PackageParser.Package pkgInfo, int flags) {
8401        // Make sure there are no dangling permission trees.
8402        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8403        while (it.hasNext()) {
8404            final BasePermission bp = it.next();
8405            if (bp.packageSetting == null) {
8406                // We may not yet have parsed the package, so just see if
8407                // we still know about its settings.
8408                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8409            }
8410            if (bp.packageSetting == null) {
8411                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8412                        + " from package " + bp.sourcePackage);
8413                it.remove();
8414            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8415                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8416                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8417                            + " from package " + bp.sourcePackage);
8418                    flags |= UPDATE_PERMISSIONS_ALL;
8419                    it.remove();
8420                }
8421            }
8422        }
8423
8424        // Make sure all dynamic permissions have been assigned to a package,
8425        // and make sure there are no dangling permissions.
8426        it = mSettings.mPermissions.values().iterator();
8427        while (it.hasNext()) {
8428            final BasePermission bp = it.next();
8429            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8430                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8431                        + bp.name + " pkg=" + bp.sourcePackage
8432                        + " info=" + bp.pendingInfo);
8433                if (bp.packageSetting == null && bp.pendingInfo != null) {
8434                    final BasePermission tree = findPermissionTreeLP(bp.name);
8435                    if (tree != null && tree.perm != null) {
8436                        bp.packageSetting = tree.packageSetting;
8437                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8438                                new PermissionInfo(bp.pendingInfo));
8439                        bp.perm.info.packageName = tree.perm.info.packageName;
8440                        bp.perm.info.name = bp.name;
8441                        bp.uid = tree.uid;
8442                    }
8443                }
8444            }
8445            if (bp.packageSetting == null) {
8446                // We may not yet have parsed the package, so just see if
8447                // we still know about its settings.
8448                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8449            }
8450            if (bp.packageSetting == null) {
8451                Slog.w(TAG, "Removing dangling permission: " + bp.name
8452                        + " from package " + bp.sourcePackage);
8453                it.remove();
8454            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8455                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8456                    Slog.i(TAG, "Removing old permission: " + bp.name
8457                            + " from package " + bp.sourcePackage);
8458                    flags |= UPDATE_PERMISSIONS_ALL;
8459                    it.remove();
8460                }
8461            }
8462        }
8463
8464        // Now update the permissions for all packages, in particular
8465        // replace the granted permissions of the system packages.
8466        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8467            for (PackageParser.Package pkg : mPackages.values()) {
8468                if (pkg != pkgInfo) {
8469                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8470                            changingPkg);
8471                }
8472            }
8473        }
8474
8475        if (pkgInfo != null) {
8476            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8477        }
8478    }
8479
8480    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8481            String packageOfInterest) {
8482        // IMPORTANT: There are two types of permissions: install and runtime.
8483        // Install time permissions are granted when the app is installed to
8484        // all device users and users added in the future. Runtime permissions
8485        // are granted at runtime explicitly to specific users. Normal and signature
8486        // protected permissions are install time permissions. Dangerous permissions
8487        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8488        // otherwise they are runtime permissions. This function does not manage
8489        // runtime permissions except for the case an app targeting Lollipop MR1
8490        // being upgraded to target a newer SDK, in which case dangerous permissions
8491        // are transformed from install time to runtime ones.
8492
8493        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8494        if (ps == null) {
8495            return;
8496        }
8497
8498        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8499
8500        PermissionsState permissionsState = ps.getPermissionsState();
8501        PermissionsState origPermissions = permissionsState;
8502
8503        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8504
8505        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8506
8507        boolean changedInstallPermission = false;
8508
8509        if (replace) {
8510            ps.installPermissionsFixed = false;
8511            if (!ps.isSharedUser()) {
8512                origPermissions = new PermissionsState(permissionsState);
8513                permissionsState.reset();
8514            }
8515        }
8516
8517        permissionsState.setGlobalGids(mGlobalGids);
8518
8519        final int N = pkg.requestedPermissions.size();
8520        for (int i=0; i<N; i++) {
8521            final String name = pkg.requestedPermissions.get(i);
8522            final BasePermission bp = mSettings.mPermissions.get(name);
8523
8524            if (DEBUG_INSTALL) {
8525                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8526            }
8527
8528            if (bp == null || bp.packageSetting == null) {
8529                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8530                    Slog.w(TAG, "Unknown permission " + name
8531                            + " in package " + pkg.packageName);
8532                }
8533                continue;
8534            }
8535
8536            final String perm = bp.name;
8537            boolean allowedSig = false;
8538            int grant = GRANT_DENIED;
8539
8540            // Keep track of app op permissions.
8541            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8542                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8543                if (pkgs == null) {
8544                    pkgs = new ArraySet<>();
8545                    mAppOpPermissionPackages.put(bp.name, pkgs);
8546                }
8547                pkgs.add(pkg.packageName);
8548            }
8549
8550            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8551            switch (level) {
8552                case PermissionInfo.PROTECTION_NORMAL: {
8553                    // For all apps normal permissions are install time ones.
8554                    grant = GRANT_INSTALL;
8555                } break;
8556
8557                case PermissionInfo.PROTECTION_DANGEROUS: {
8558                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8559                        // For legacy apps dangerous permissions are install time ones.
8560                        grant = GRANT_INSTALL_LEGACY;
8561                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8562                        // For legacy apps that became modern, install becomes runtime.
8563                        grant = GRANT_UPGRADE;
8564                    } else if (mPromoteSystemApps
8565                            && isSystemApp(ps)
8566                            && mExistingSystemPackages.contains(ps.name)) {
8567                        // For legacy system apps, install becomes runtime.
8568                        // We cannot check hasInstallPermission() for system apps since those
8569                        // permissions were granted implicitly and not persisted pre-M.
8570                        grant = GRANT_UPGRADE;
8571                    } else {
8572                        // For modern apps keep runtime permissions unchanged.
8573                        grant = GRANT_RUNTIME;
8574                    }
8575                } break;
8576
8577                case PermissionInfo.PROTECTION_SIGNATURE: {
8578                    // For all apps signature permissions are install time ones.
8579                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8580                    if (allowedSig) {
8581                        grant = GRANT_INSTALL;
8582                    }
8583                } break;
8584            }
8585
8586            if (DEBUG_INSTALL) {
8587                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8588            }
8589
8590            if (grant != GRANT_DENIED) {
8591                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8592                    // If this is an existing, non-system package, then
8593                    // we can't add any new permissions to it.
8594                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8595                        // Except...  if this is a permission that was added
8596                        // to the platform (note: need to only do this when
8597                        // updating the platform).
8598                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8599                            grant = GRANT_DENIED;
8600                        }
8601                    }
8602                }
8603
8604                switch (grant) {
8605                    case GRANT_INSTALL: {
8606                        // Revoke this as runtime permission to handle the case of
8607                        // a runtime permission being downgraded to an install one.
8608                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8609                            if (origPermissions.getRuntimePermissionState(
8610                                    bp.name, userId) != null) {
8611                                // Revoke the runtime permission and clear the flags.
8612                                origPermissions.revokeRuntimePermission(bp, userId);
8613                                origPermissions.updatePermissionFlags(bp, userId,
8614                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8615                                // If we revoked a permission permission, we have to write.
8616                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8617                                        changedRuntimePermissionUserIds, userId);
8618                            }
8619                        }
8620                        // Grant an install permission.
8621                        if (permissionsState.grantInstallPermission(bp) !=
8622                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8623                            changedInstallPermission = true;
8624                        }
8625                    } break;
8626
8627                    case GRANT_INSTALL_LEGACY: {
8628                        // Grant an install permission.
8629                        if (permissionsState.grantInstallPermission(bp) !=
8630                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8631                            changedInstallPermission = true;
8632                        }
8633                    } break;
8634
8635                    case GRANT_RUNTIME: {
8636                        // Grant previously granted runtime permissions.
8637                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8638                            PermissionState permissionState = origPermissions
8639                                    .getRuntimePermissionState(bp.name, userId);
8640                            final int flags = permissionState != null
8641                                    ? permissionState.getFlags() : 0;
8642                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8643                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8644                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8645                                    // If we cannot put the permission as it was, we have to write.
8646                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8647                                            changedRuntimePermissionUserIds, userId);
8648                                }
8649                            }
8650                            // Propagate the permission flags.
8651                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8652                        }
8653                    } break;
8654
8655                    case GRANT_UPGRADE: {
8656                        // Grant runtime permissions for a previously held install permission.
8657                        PermissionState permissionState = origPermissions
8658                                .getInstallPermissionState(bp.name);
8659                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8660
8661                        if (origPermissions.revokeInstallPermission(bp)
8662                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8663                            // We will be transferring the permission flags, so clear them.
8664                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8665                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8666                            changedInstallPermission = true;
8667                        }
8668
8669                        // If the permission is not to be promoted to runtime we ignore it and
8670                        // also its other flags as they are not applicable to install permissions.
8671                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8672                            for (int userId : currentUserIds) {
8673                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8674                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8675                                    // Transfer the permission flags.
8676                                    permissionsState.updatePermissionFlags(bp, userId,
8677                                            flags, flags);
8678                                    // If we granted the permission, we have to write.
8679                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8680                                            changedRuntimePermissionUserIds, userId);
8681                                }
8682                            }
8683                        }
8684                    } break;
8685
8686                    default: {
8687                        if (packageOfInterest == null
8688                                || packageOfInterest.equals(pkg.packageName)) {
8689                            Slog.w(TAG, "Not granting permission " + perm
8690                                    + " to package " + pkg.packageName
8691                                    + " because it was previously installed without");
8692                        }
8693                    } break;
8694                }
8695            } else {
8696                if (permissionsState.revokeInstallPermission(bp) !=
8697                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8698                    // Also drop the permission flags.
8699                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8700                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8701                    changedInstallPermission = true;
8702                    Slog.i(TAG, "Un-granting permission " + perm
8703                            + " from package " + pkg.packageName
8704                            + " (protectionLevel=" + bp.protectionLevel
8705                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8706                            + ")");
8707                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8708                    // Don't print warning for app op permissions, since it is fine for them
8709                    // not to be granted, there is a UI for the user to decide.
8710                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8711                        Slog.w(TAG, "Not granting permission " + perm
8712                                + " to package " + pkg.packageName
8713                                + " (protectionLevel=" + bp.protectionLevel
8714                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8715                                + ")");
8716                    }
8717                }
8718            }
8719        }
8720
8721        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8722                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8723            // This is the first that we have heard about this package, so the
8724            // permissions we have now selected are fixed until explicitly
8725            // changed.
8726            ps.installPermissionsFixed = true;
8727        }
8728
8729        // Persist the runtime permissions state for users with changes.
8730        for (int userId : changedRuntimePermissionUserIds) {
8731            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8732        }
8733
8734        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8735    }
8736
8737    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8738        boolean allowed = false;
8739        final int NP = PackageParser.NEW_PERMISSIONS.length;
8740        for (int ip=0; ip<NP; ip++) {
8741            final PackageParser.NewPermissionInfo npi
8742                    = PackageParser.NEW_PERMISSIONS[ip];
8743            if (npi.name.equals(perm)
8744                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8745                allowed = true;
8746                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8747                        + pkg.packageName);
8748                break;
8749            }
8750        }
8751        return allowed;
8752    }
8753
8754    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8755            BasePermission bp, PermissionsState origPermissions) {
8756        boolean allowed;
8757        allowed = (compareSignatures(
8758                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8759                        == PackageManager.SIGNATURE_MATCH)
8760                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8761                        == PackageManager.SIGNATURE_MATCH);
8762        if (!allowed && (bp.protectionLevel
8763                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8764            if (isSystemApp(pkg)) {
8765                // For updated system applications, a system permission
8766                // is granted only if it had been defined by the original application.
8767                if (pkg.isUpdatedSystemApp()) {
8768                    final PackageSetting sysPs = mSettings
8769                            .getDisabledSystemPkgLPr(pkg.packageName);
8770                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8771                        // If the original was granted this permission, we take
8772                        // that grant decision as read and propagate it to the
8773                        // update.
8774                        if (sysPs.isPrivileged()) {
8775                            allowed = true;
8776                        }
8777                    } else {
8778                        // The system apk may have been updated with an older
8779                        // version of the one on the data partition, but which
8780                        // granted a new system permission that it didn't have
8781                        // before.  In this case we do want to allow the app to
8782                        // now get the new permission if the ancestral apk is
8783                        // privileged to get it.
8784                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8785                            for (int j=0;
8786                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8787                                if (perm.equals(
8788                                        sysPs.pkg.requestedPermissions.get(j))) {
8789                                    allowed = true;
8790                                    break;
8791                                }
8792                            }
8793                        }
8794                    }
8795                } else {
8796                    allowed = isPrivilegedApp(pkg);
8797                }
8798            }
8799        }
8800        if (!allowed) {
8801            if (!allowed && (bp.protectionLevel
8802                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8803                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8804                // If this was a previously normal/dangerous permission that got moved
8805                // to a system permission as part of the runtime permission redesign, then
8806                // we still want to blindly grant it to old apps.
8807                allowed = true;
8808            }
8809            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8810                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8811                // If this permission is to be granted to the system installer and
8812                // this app is an installer, then it gets the permission.
8813                allowed = true;
8814            }
8815            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8816                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8817                // If this permission is to be granted to the system verifier and
8818                // this app is a verifier, then it gets the permission.
8819                allowed = true;
8820            }
8821            if (!allowed && (bp.protectionLevel
8822                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8823                    && isSystemApp(pkg)) {
8824                // Any pre-installed system app is allowed to get this permission.
8825                allowed = true;
8826            }
8827            if (!allowed && (bp.protectionLevel
8828                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8829                // For development permissions, a development permission
8830                // is granted only if it was already granted.
8831                allowed = origPermissions.hasInstallPermission(perm);
8832            }
8833        }
8834        return allowed;
8835    }
8836
8837    final class ActivityIntentResolver
8838            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8839        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8840                boolean defaultOnly, int userId) {
8841            if (!sUserManager.exists(userId)) return null;
8842            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8843            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8844        }
8845
8846        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8847                int userId) {
8848            if (!sUserManager.exists(userId)) return null;
8849            mFlags = flags;
8850            return super.queryIntent(intent, resolvedType,
8851                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8852        }
8853
8854        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8855                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8856            if (!sUserManager.exists(userId)) return null;
8857            if (packageActivities == null) {
8858                return null;
8859            }
8860            mFlags = flags;
8861            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8862            final int N = packageActivities.size();
8863            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8864                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8865
8866            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8867            for (int i = 0; i < N; ++i) {
8868                intentFilters = packageActivities.get(i).intents;
8869                if (intentFilters != null && intentFilters.size() > 0) {
8870                    PackageParser.ActivityIntentInfo[] array =
8871                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8872                    intentFilters.toArray(array);
8873                    listCut.add(array);
8874                }
8875            }
8876            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8877        }
8878
8879        public final void addActivity(PackageParser.Activity a, String type) {
8880            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8881            mActivities.put(a.getComponentName(), a);
8882            if (DEBUG_SHOW_INFO)
8883                Log.v(
8884                TAG, "  " + type + " " +
8885                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8886            if (DEBUG_SHOW_INFO)
8887                Log.v(TAG, "    Class=" + a.info.name);
8888            final int NI = a.intents.size();
8889            for (int j=0; j<NI; j++) {
8890                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8891                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8892                    intent.setPriority(0);
8893                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8894                            + a.className + " with priority > 0, forcing to 0");
8895                }
8896                if (DEBUG_SHOW_INFO) {
8897                    Log.v(TAG, "    IntentFilter:");
8898                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8899                }
8900                if (!intent.debugCheck()) {
8901                    Log.w(TAG, "==> For Activity " + a.info.name);
8902                }
8903                addFilter(intent);
8904            }
8905        }
8906
8907        public final void removeActivity(PackageParser.Activity a, String type) {
8908            mActivities.remove(a.getComponentName());
8909            if (DEBUG_SHOW_INFO) {
8910                Log.v(TAG, "  " + type + " "
8911                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8912                                : a.info.name) + ":");
8913                Log.v(TAG, "    Class=" + a.info.name);
8914            }
8915            final int NI = a.intents.size();
8916            for (int j=0; j<NI; j++) {
8917                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8918                if (DEBUG_SHOW_INFO) {
8919                    Log.v(TAG, "    IntentFilter:");
8920                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8921                }
8922                removeFilter(intent);
8923            }
8924        }
8925
8926        @Override
8927        protected boolean allowFilterResult(
8928                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8929            ActivityInfo filterAi = filter.activity.info;
8930            for (int i=dest.size()-1; i>=0; i--) {
8931                ActivityInfo destAi = dest.get(i).activityInfo;
8932                if (destAi.name == filterAi.name
8933                        && destAi.packageName == filterAi.packageName) {
8934                    return false;
8935                }
8936            }
8937            return true;
8938        }
8939
8940        @Override
8941        protected ActivityIntentInfo[] newArray(int size) {
8942            return new ActivityIntentInfo[size];
8943        }
8944
8945        @Override
8946        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8947            if (!sUserManager.exists(userId)) return true;
8948            PackageParser.Package p = filter.activity.owner;
8949            if (p != null) {
8950                PackageSetting ps = (PackageSetting)p.mExtras;
8951                if (ps != null) {
8952                    // System apps are never considered stopped for purposes of
8953                    // filtering, because there may be no way for the user to
8954                    // actually re-launch them.
8955                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8956                            && ps.getStopped(userId);
8957                }
8958            }
8959            return false;
8960        }
8961
8962        @Override
8963        protected boolean isPackageForFilter(String packageName,
8964                PackageParser.ActivityIntentInfo info) {
8965            return packageName.equals(info.activity.owner.packageName);
8966        }
8967
8968        @Override
8969        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8970                int match, int userId) {
8971            if (!sUserManager.exists(userId)) return null;
8972            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8973                return null;
8974            }
8975            final PackageParser.Activity activity = info.activity;
8976            if (mSafeMode && (activity.info.applicationInfo.flags
8977                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8978                return null;
8979            }
8980            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8981            if (ps == null) {
8982                return null;
8983            }
8984            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8985                    ps.readUserState(userId), userId);
8986            if (ai == null) {
8987                return null;
8988            }
8989            final ResolveInfo res = new ResolveInfo();
8990            res.activityInfo = ai;
8991            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8992                res.filter = info;
8993            }
8994            if (info != null) {
8995                res.handleAllWebDataURI = info.handleAllWebDataURI();
8996            }
8997            res.priority = info.getPriority();
8998            res.preferredOrder = activity.owner.mPreferredOrder;
8999            //System.out.println("Result: " + res.activityInfo.className +
9000            //                   " = " + res.priority);
9001            res.match = match;
9002            res.isDefault = info.hasDefault;
9003            res.labelRes = info.labelRes;
9004            res.nonLocalizedLabel = info.nonLocalizedLabel;
9005            if (userNeedsBadging(userId)) {
9006                res.noResourceId = true;
9007            } else {
9008                res.icon = info.icon;
9009            }
9010            res.iconResourceId = info.icon;
9011            res.system = res.activityInfo.applicationInfo.isSystemApp();
9012            return res;
9013        }
9014
9015        @Override
9016        protected void sortResults(List<ResolveInfo> results) {
9017            Collections.sort(results, mResolvePrioritySorter);
9018        }
9019
9020        @Override
9021        protected void dumpFilter(PrintWriter out, String prefix,
9022                PackageParser.ActivityIntentInfo filter) {
9023            out.print(prefix); out.print(
9024                    Integer.toHexString(System.identityHashCode(filter.activity)));
9025                    out.print(' ');
9026                    filter.activity.printComponentShortName(out);
9027                    out.print(" filter ");
9028                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9029        }
9030
9031        @Override
9032        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9033            return filter.activity;
9034        }
9035
9036        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9037            PackageParser.Activity activity = (PackageParser.Activity)label;
9038            out.print(prefix); out.print(
9039                    Integer.toHexString(System.identityHashCode(activity)));
9040                    out.print(' ');
9041                    activity.printComponentShortName(out);
9042            if (count > 1) {
9043                out.print(" ("); out.print(count); out.print(" filters)");
9044            }
9045            out.println();
9046        }
9047
9048//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9049//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9050//            final List<ResolveInfo> retList = Lists.newArrayList();
9051//            while (i.hasNext()) {
9052//                final ResolveInfo resolveInfo = i.next();
9053//                if (isEnabledLP(resolveInfo.activityInfo)) {
9054//                    retList.add(resolveInfo);
9055//                }
9056//            }
9057//            return retList;
9058//        }
9059
9060        // Keys are String (activity class name), values are Activity.
9061        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9062                = new ArrayMap<ComponentName, PackageParser.Activity>();
9063        private int mFlags;
9064    }
9065
9066    private final class ServiceIntentResolver
9067            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9068        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9069                boolean defaultOnly, int userId) {
9070            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9071            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9072        }
9073
9074        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9075                int userId) {
9076            if (!sUserManager.exists(userId)) return null;
9077            mFlags = flags;
9078            return super.queryIntent(intent, resolvedType,
9079                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9080        }
9081
9082        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9083                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9084            if (!sUserManager.exists(userId)) return null;
9085            if (packageServices == null) {
9086                return null;
9087            }
9088            mFlags = flags;
9089            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9090            final int N = packageServices.size();
9091            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9092                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9093
9094            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9095            for (int i = 0; i < N; ++i) {
9096                intentFilters = packageServices.get(i).intents;
9097                if (intentFilters != null && intentFilters.size() > 0) {
9098                    PackageParser.ServiceIntentInfo[] array =
9099                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9100                    intentFilters.toArray(array);
9101                    listCut.add(array);
9102                }
9103            }
9104            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9105        }
9106
9107        public final void addService(PackageParser.Service s) {
9108            mServices.put(s.getComponentName(), s);
9109            if (DEBUG_SHOW_INFO) {
9110                Log.v(TAG, "  "
9111                        + (s.info.nonLocalizedLabel != null
9112                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9113                Log.v(TAG, "    Class=" + s.info.name);
9114            }
9115            final int NI = s.intents.size();
9116            int j;
9117            for (j=0; j<NI; j++) {
9118                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9119                if (DEBUG_SHOW_INFO) {
9120                    Log.v(TAG, "    IntentFilter:");
9121                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9122                }
9123                if (!intent.debugCheck()) {
9124                    Log.w(TAG, "==> For Service " + s.info.name);
9125                }
9126                addFilter(intent);
9127            }
9128        }
9129
9130        public final void removeService(PackageParser.Service s) {
9131            mServices.remove(s.getComponentName());
9132            if (DEBUG_SHOW_INFO) {
9133                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9134                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9135                Log.v(TAG, "    Class=" + s.info.name);
9136            }
9137            final int NI = s.intents.size();
9138            int j;
9139            for (j=0; j<NI; j++) {
9140                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9141                if (DEBUG_SHOW_INFO) {
9142                    Log.v(TAG, "    IntentFilter:");
9143                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9144                }
9145                removeFilter(intent);
9146            }
9147        }
9148
9149        @Override
9150        protected boolean allowFilterResult(
9151                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9152            ServiceInfo filterSi = filter.service.info;
9153            for (int i=dest.size()-1; i>=0; i--) {
9154                ServiceInfo destAi = dest.get(i).serviceInfo;
9155                if (destAi.name == filterSi.name
9156                        && destAi.packageName == filterSi.packageName) {
9157                    return false;
9158                }
9159            }
9160            return true;
9161        }
9162
9163        @Override
9164        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9165            return new PackageParser.ServiceIntentInfo[size];
9166        }
9167
9168        @Override
9169        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9170            if (!sUserManager.exists(userId)) return true;
9171            PackageParser.Package p = filter.service.owner;
9172            if (p != null) {
9173                PackageSetting ps = (PackageSetting)p.mExtras;
9174                if (ps != null) {
9175                    // System apps are never considered stopped for purposes of
9176                    // filtering, because there may be no way for the user to
9177                    // actually re-launch them.
9178                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9179                            && ps.getStopped(userId);
9180                }
9181            }
9182            return false;
9183        }
9184
9185        @Override
9186        protected boolean isPackageForFilter(String packageName,
9187                PackageParser.ServiceIntentInfo info) {
9188            return packageName.equals(info.service.owner.packageName);
9189        }
9190
9191        @Override
9192        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9193                int match, int userId) {
9194            if (!sUserManager.exists(userId)) return null;
9195            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9196            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9197                return null;
9198            }
9199            final PackageParser.Service service = info.service;
9200            if (mSafeMode && (service.info.applicationInfo.flags
9201                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9202                return null;
9203            }
9204            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9205            if (ps == null) {
9206                return null;
9207            }
9208            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9209                    ps.readUserState(userId), userId);
9210            if (si == null) {
9211                return null;
9212            }
9213            final ResolveInfo res = new ResolveInfo();
9214            res.serviceInfo = si;
9215            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9216                res.filter = filter;
9217            }
9218            res.priority = info.getPriority();
9219            res.preferredOrder = service.owner.mPreferredOrder;
9220            res.match = match;
9221            res.isDefault = info.hasDefault;
9222            res.labelRes = info.labelRes;
9223            res.nonLocalizedLabel = info.nonLocalizedLabel;
9224            res.icon = info.icon;
9225            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9226            return res;
9227        }
9228
9229        @Override
9230        protected void sortResults(List<ResolveInfo> results) {
9231            Collections.sort(results, mResolvePrioritySorter);
9232        }
9233
9234        @Override
9235        protected void dumpFilter(PrintWriter out, String prefix,
9236                PackageParser.ServiceIntentInfo filter) {
9237            out.print(prefix); out.print(
9238                    Integer.toHexString(System.identityHashCode(filter.service)));
9239                    out.print(' ');
9240                    filter.service.printComponentShortName(out);
9241                    out.print(" filter ");
9242                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9243        }
9244
9245        @Override
9246        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9247            return filter.service;
9248        }
9249
9250        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9251            PackageParser.Service service = (PackageParser.Service)label;
9252            out.print(prefix); out.print(
9253                    Integer.toHexString(System.identityHashCode(service)));
9254                    out.print(' ');
9255                    service.printComponentShortName(out);
9256            if (count > 1) {
9257                out.print(" ("); out.print(count); out.print(" filters)");
9258            }
9259            out.println();
9260        }
9261
9262//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9263//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9264//            final List<ResolveInfo> retList = Lists.newArrayList();
9265//            while (i.hasNext()) {
9266//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9267//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9268//                    retList.add(resolveInfo);
9269//                }
9270//            }
9271//            return retList;
9272//        }
9273
9274        // Keys are String (activity class name), values are Activity.
9275        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9276                = new ArrayMap<ComponentName, PackageParser.Service>();
9277        private int mFlags;
9278    };
9279
9280    private final class ProviderIntentResolver
9281            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9282        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9283                boolean defaultOnly, int userId) {
9284            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9285            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9286        }
9287
9288        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9289                int userId) {
9290            if (!sUserManager.exists(userId))
9291                return null;
9292            mFlags = flags;
9293            return super.queryIntent(intent, resolvedType,
9294                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9295        }
9296
9297        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9298                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9299            if (!sUserManager.exists(userId))
9300                return null;
9301            if (packageProviders == null) {
9302                return null;
9303            }
9304            mFlags = flags;
9305            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9306            final int N = packageProviders.size();
9307            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9308                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9309
9310            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9311            for (int i = 0; i < N; ++i) {
9312                intentFilters = packageProviders.get(i).intents;
9313                if (intentFilters != null && intentFilters.size() > 0) {
9314                    PackageParser.ProviderIntentInfo[] array =
9315                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9316                    intentFilters.toArray(array);
9317                    listCut.add(array);
9318                }
9319            }
9320            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9321        }
9322
9323        public final void addProvider(PackageParser.Provider p) {
9324            if (mProviders.containsKey(p.getComponentName())) {
9325                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9326                return;
9327            }
9328
9329            mProviders.put(p.getComponentName(), p);
9330            if (DEBUG_SHOW_INFO) {
9331                Log.v(TAG, "  "
9332                        + (p.info.nonLocalizedLabel != null
9333                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9334                Log.v(TAG, "    Class=" + p.info.name);
9335            }
9336            final int NI = p.intents.size();
9337            int j;
9338            for (j = 0; j < NI; j++) {
9339                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9340                if (DEBUG_SHOW_INFO) {
9341                    Log.v(TAG, "    IntentFilter:");
9342                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9343                }
9344                if (!intent.debugCheck()) {
9345                    Log.w(TAG, "==> For Provider " + p.info.name);
9346                }
9347                addFilter(intent);
9348            }
9349        }
9350
9351        public final void removeProvider(PackageParser.Provider p) {
9352            mProviders.remove(p.getComponentName());
9353            if (DEBUG_SHOW_INFO) {
9354                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9355                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9356                Log.v(TAG, "    Class=" + p.info.name);
9357            }
9358            final int NI = p.intents.size();
9359            int j;
9360            for (j = 0; j < NI; j++) {
9361                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9362                if (DEBUG_SHOW_INFO) {
9363                    Log.v(TAG, "    IntentFilter:");
9364                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9365                }
9366                removeFilter(intent);
9367            }
9368        }
9369
9370        @Override
9371        protected boolean allowFilterResult(
9372                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9373            ProviderInfo filterPi = filter.provider.info;
9374            for (int i = dest.size() - 1; i >= 0; i--) {
9375                ProviderInfo destPi = dest.get(i).providerInfo;
9376                if (destPi.name == filterPi.name
9377                        && destPi.packageName == filterPi.packageName) {
9378                    return false;
9379                }
9380            }
9381            return true;
9382        }
9383
9384        @Override
9385        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9386            return new PackageParser.ProviderIntentInfo[size];
9387        }
9388
9389        @Override
9390        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9391            if (!sUserManager.exists(userId))
9392                return true;
9393            PackageParser.Package p = filter.provider.owner;
9394            if (p != null) {
9395                PackageSetting ps = (PackageSetting) p.mExtras;
9396                if (ps != null) {
9397                    // System apps are never considered stopped for purposes of
9398                    // filtering, because there may be no way for the user to
9399                    // actually re-launch them.
9400                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9401                            && ps.getStopped(userId);
9402                }
9403            }
9404            return false;
9405        }
9406
9407        @Override
9408        protected boolean isPackageForFilter(String packageName,
9409                PackageParser.ProviderIntentInfo info) {
9410            return packageName.equals(info.provider.owner.packageName);
9411        }
9412
9413        @Override
9414        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9415                int match, int userId) {
9416            if (!sUserManager.exists(userId))
9417                return null;
9418            final PackageParser.ProviderIntentInfo info = filter;
9419            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9420                return null;
9421            }
9422            final PackageParser.Provider provider = info.provider;
9423            if (mSafeMode && (provider.info.applicationInfo.flags
9424                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9425                return null;
9426            }
9427            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9428            if (ps == null) {
9429                return null;
9430            }
9431            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9432                    ps.readUserState(userId), userId);
9433            if (pi == null) {
9434                return null;
9435            }
9436            final ResolveInfo res = new ResolveInfo();
9437            res.providerInfo = pi;
9438            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9439                res.filter = filter;
9440            }
9441            res.priority = info.getPriority();
9442            res.preferredOrder = provider.owner.mPreferredOrder;
9443            res.match = match;
9444            res.isDefault = info.hasDefault;
9445            res.labelRes = info.labelRes;
9446            res.nonLocalizedLabel = info.nonLocalizedLabel;
9447            res.icon = info.icon;
9448            res.system = res.providerInfo.applicationInfo.isSystemApp();
9449            return res;
9450        }
9451
9452        @Override
9453        protected void sortResults(List<ResolveInfo> results) {
9454            Collections.sort(results, mResolvePrioritySorter);
9455        }
9456
9457        @Override
9458        protected void dumpFilter(PrintWriter out, String prefix,
9459                PackageParser.ProviderIntentInfo filter) {
9460            out.print(prefix);
9461            out.print(
9462                    Integer.toHexString(System.identityHashCode(filter.provider)));
9463            out.print(' ');
9464            filter.provider.printComponentShortName(out);
9465            out.print(" filter ");
9466            out.println(Integer.toHexString(System.identityHashCode(filter)));
9467        }
9468
9469        @Override
9470        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9471            return filter.provider;
9472        }
9473
9474        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9475            PackageParser.Provider provider = (PackageParser.Provider)label;
9476            out.print(prefix); out.print(
9477                    Integer.toHexString(System.identityHashCode(provider)));
9478                    out.print(' ');
9479                    provider.printComponentShortName(out);
9480            if (count > 1) {
9481                out.print(" ("); out.print(count); out.print(" filters)");
9482            }
9483            out.println();
9484        }
9485
9486        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9487                = new ArrayMap<ComponentName, PackageParser.Provider>();
9488        private int mFlags;
9489    };
9490
9491    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9492            new Comparator<ResolveInfo>() {
9493        public int compare(ResolveInfo r1, ResolveInfo r2) {
9494            int v1 = r1.priority;
9495            int v2 = r2.priority;
9496            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9497            if (v1 != v2) {
9498                return (v1 > v2) ? -1 : 1;
9499            }
9500            v1 = r1.preferredOrder;
9501            v2 = r2.preferredOrder;
9502            if (v1 != v2) {
9503                return (v1 > v2) ? -1 : 1;
9504            }
9505            if (r1.isDefault != r2.isDefault) {
9506                return r1.isDefault ? -1 : 1;
9507            }
9508            v1 = r1.match;
9509            v2 = r2.match;
9510            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9511            if (v1 != v2) {
9512                return (v1 > v2) ? -1 : 1;
9513            }
9514            if (r1.system != r2.system) {
9515                return r1.system ? -1 : 1;
9516            }
9517            return 0;
9518        }
9519    };
9520
9521    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9522            new Comparator<ProviderInfo>() {
9523        public int compare(ProviderInfo p1, ProviderInfo p2) {
9524            final int v1 = p1.initOrder;
9525            final int v2 = p2.initOrder;
9526            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9527        }
9528    };
9529
9530    final void sendPackageBroadcast(final String action, final String pkg,
9531            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9532            final int[] userIds) {
9533        mHandler.post(new Runnable() {
9534            @Override
9535            public void run() {
9536                try {
9537                    final IActivityManager am = ActivityManagerNative.getDefault();
9538                    if (am == null) return;
9539                    final int[] resolvedUserIds;
9540                    if (userIds == null) {
9541                        resolvedUserIds = am.getRunningUserIds();
9542                    } else {
9543                        resolvedUserIds = userIds;
9544                    }
9545                    for (int id : resolvedUserIds) {
9546                        final Intent intent = new Intent(action,
9547                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9548                        if (extras != null) {
9549                            intent.putExtras(extras);
9550                        }
9551                        if (targetPkg != null) {
9552                            intent.setPackage(targetPkg);
9553                        }
9554                        // Modify the UID when posting to other users
9555                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9556                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9557                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9558                            intent.putExtra(Intent.EXTRA_UID, uid);
9559                        }
9560                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9561                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9562                        if (DEBUG_BROADCASTS) {
9563                            RuntimeException here = new RuntimeException("here");
9564                            here.fillInStackTrace();
9565                            Slog.d(TAG, "Sending to user " + id + ": "
9566                                    + intent.toShortString(false, true, false, false)
9567                                    + " " + intent.getExtras(), here);
9568                        }
9569                        am.broadcastIntent(null, intent, null, finishedReceiver,
9570                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9571                                null, finishedReceiver != null, false, id);
9572                    }
9573                } catch (RemoteException ex) {
9574                }
9575            }
9576        });
9577    }
9578
9579    /**
9580     * Check if the external storage media is available. This is true if there
9581     * is a mounted external storage medium or if the external storage is
9582     * emulated.
9583     */
9584    private boolean isExternalMediaAvailable() {
9585        return mMediaMounted || Environment.isExternalStorageEmulated();
9586    }
9587
9588    @Override
9589    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9590        // writer
9591        synchronized (mPackages) {
9592            if (!isExternalMediaAvailable()) {
9593                // If the external storage is no longer mounted at this point,
9594                // the caller may not have been able to delete all of this
9595                // packages files and can not delete any more.  Bail.
9596                return null;
9597            }
9598            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9599            if (lastPackage != null) {
9600                pkgs.remove(lastPackage);
9601            }
9602            if (pkgs.size() > 0) {
9603                return pkgs.get(0);
9604            }
9605        }
9606        return null;
9607    }
9608
9609    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9610        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9611                userId, andCode ? 1 : 0, packageName);
9612        if (mSystemReady) {
9613            msg.sendToTarget();
9614        } else {
9615            if (mPostSystemReadyMessages == null) {
9616                mPostSystemReadyMessages = new ArrayList<>();
9617            }
9618            mPostSystemReadyMessages.add(msg);
9619        }
9620    }
9621
9622    void startCleaningPackages() {
9623        // reader
9624        synchronized (mPackages) {
9625            if (!isExternalMediaAvailable()) {
9626                return;
9627            }
9628            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9629                return;
9630            }
9631        }
9632        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9633        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9634        IActivityManager am = ActivityManagerNative.getDefault();
9635        if (am != null) {
9636            try {
9637                am.startService(null, intent, null, mContext.getOpPackageName(),
9638                        UserHandle.USER_OWNER);
9639            } catch (RemoteException e) {
9640            }
9641        }
9642    }
9643
9644    @Override
9645    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9646            int installFlags, String installerPackageName, VerificationParams verificationParams,
9647            String packageAbiOverride) {
9648        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9649                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9650    }
9651
9652    @Override
9653    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9654            int installFlags, String installerPackageName, VerificationParams verificationParams,
9655            String packageAbiOverride, int userId) {
9656        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9657
9658        final int callingUid = Binder.getCallingUid();
9659        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9660
9661        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9662            try {
9663                if (observer != null) {
9664                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9665                }
9666            } catch (RemoteException re) {
9667            }
9668            return;
9669        }
9670
9671        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9672            installFlags |= PackageManager.INSTALL_FROM_ADB;
9673
9674        } else {
9675            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9676            // about installerPackageName.
9677
9678            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9679            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9680        }
9681
9682        UserHandle user;
9683        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9684            user = UserHandle.ALL;
9685        } else {
9686            user = new UserHandle(userId);
9687        }
9688
9689        // Only system components can circumvent runtime permissions when installing.
9690        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9691                && mContext.checkCallingOrSelfPermission(Manifest.permission
9692                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9693            throw new SecurityException("You need the "
9694                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9695                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9696        }
9697
9698        verificationParams.setInstallerUid(callingUid);
9699
9700        final File originFile = new File(originPath);
9701        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9702
9703        final Message msg = mHandler.obtainMessage(INIT_COPY);
9704        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9705                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9706        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9707        msg.obj = params;
9708
9709        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9710                System.identityHashCode(msg.obj));
9711        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9712                System.identityHashCode(msg.obj));
9713
9714        mHandler.sendMessage(msg);
9715    }
9716
9717    void installStage(String packageName, File stagedDir, String stagedCid,
9718            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9719            String installerPackageName, int installerUid, UserHandle user) {
9720        final VerificationParams verifParams = new VerificationParams(
9721                null, sessionParams.originatingUri, sessionParams.referrerUri, installerUid, null);
9722        verifParams.setInstallerUid(installerUid);
9723
9724        final OriginInfo origin;
9725        if (stagedDir != null) {
9726            origin = OriginInfo.fromStagedFile(stagedDir);
9727        } else {
9728            origin = OriginInfo.fromStagedContainer(stagedCid);
9729        }
9730
9731        final Message msg = mHandler.obtainMessage(INIT_COPY);
9732        final InstallParams params = new InstallParams(origin, null, observer,
9733                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9734                verifParams, user, sessionParams.abiOverride,
9735                sessionParams.grantedRuntimePermissions);
9736        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9737        msg.obj = params;
9738
9739        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9740                System.identityHashCode(msg.obj));
9741        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9742                System.identityHashCode(msg.obj));
9743
9744        mHandler.sendMessage(msg);
9745    }
9746
9747    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9748        Bundle extras = new Bundle(1);
9749        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9750
9751        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9752                packageName, extras, null, null, new int[] {userId});
9753        try {
9754            IActivityManager am = ActivityManagerNative.getDefault();
9755            final boolean isSystem =
9756                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9757            if (isSystem && am.isUserRunning(userId, false)) {
9758                // The just-installed/enabled app is bundled on the system, so presumed
9759                // to be able to run automatically without needing an explicit launch.
9760                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9761                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9762                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9763                        .setPackage(packageName);
9764                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9765                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9766            }
9767        } catch (RemoteException e) {
9768            // shouldn't happen
9769            Slog.w(TAG, "Unable to bootstrap installed package", e);
9770        }
9771    }
9772
9773    @Override
9774    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9775            int userId) {
9776        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9777        PackageSetting pkgSetting;
9778        final int uid = Binder.getCallingUid();
9779        enforceCrossUserPermission(uid, userId, true, true,
9780                "setApplicationHiddenSetting for user " + userId);
9781
9782        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9783            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9784            return false;
9785        }
9786
9787        long callingId = Binder.clearCallingIdentity();
9788        try {
9789            boolean sendAdded = false;
9790            boolean sendRemoved = false;
9791            // writer
9792            synchronized (mPackages) {
9793                pkgSetting = mSettings.mPackages.get(packageName);
9794                if (pkgSetting == null) {
9795                    return false;
9796                }
9797                if (pkgSetting.getHidden(userId) != hidden) {
9798                    pkgSetting.setHidden(hidden, userId);
9799                    mSettings.writePackageRestrictionsLPr(userId);
9800                    if (hidden) {
9801                        sendRemoved = true;
9802                    } else {
9803                        sendAdded = true;
9804                    }
9805                }
9806            }
9807            if (sendAdded) {
9808                sendPackageAddedForUser(packageName, pkgSetting, userId);
9809                return true;
9810            }
9811            if (sendRemoved) {
9812                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9813                        "hiding pkg");
9814                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9815                return true;
9816            }
9817        } finally {
9818            Binder.restoreCallingIdentity(callingId);
9819        }
9820        return false;
9821    }
9822
9823    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9824            int userId) {
9825        final PackageRemovedInfo info = new PackageRemovedInfo();
9826        info.removedPackage = packageName;
9827        info.removedUsers = new int[] {userId};
9828        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9829        info.sendBroadcast(false, false, false);
9830    }
9831
9832    /**
9833     * Returns true if application is not found or there was an error. Otherwise it returns
9834     * the hidden state of the package for the given user.
9835     */
9836    @Override
9837    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9838        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9839        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9840                false, "getApplicationHidden for user " + userId);
9841        PackageSetting pkgSetting;
9842        long callingId = Binder.clearCallingIdentity();
9843        try {
9844            // writer
9845            synchronized (mPackages) {
9846                pkgSetting = mSettings.mPackages.get(packageName);
9847                if (pkgSetting == null) {
9848                    return true;
9849                }
9850                return pkgSetting.getHidden(userId);
9851            }
9852        } finally {
9853            Binder.restoreCallingIdentity(callingId);
9854        }
9855    }
9856
9857    /**
9858     * @hide
9859     */
9860    @Override
9861    public int installExistingPackageAsUser(String packageName, int userId) {
9862        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9863                null);
9864        PackageSetting pkgSetting;
9865        final int uid = Binder.getCallingUid();
9866        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9867                + userId);
9868        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9869            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9870        }
9871
9872        long callingId = Binder.clearCallingIdentity();
9873        try {
9874            boolean sendAdded = false;
9875
9876            // writer
9877            synchronized (mPackages) {
9878                pkgSetting = mSettings.mPackages.get(packageName);
9879                if (pkgSetting == null) {
9880                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9881                }
9882                if (!pkgSetting.getInstalled(userId)) {
9883                    pkgSetting.setInstalled(true, userId);
9884                    pkgSetting.setHidden(false, userId);
9885                    mSettings.writePackageRestrictionsLPr(userId);
9886                    sendAdded = true;
9887                }
9888            }
9889
9890            if (sendAdded) {
9891                sendPackageAddedForUser(packageName, pkgSetting, userId);
9892            }
9893        } finally {
9894            Binder.restoreCallingIdentity(callingId);
9895        }
9896
9897        return PackageManager.INSTALL_SUCCEEDED;
9898    }
9899
9900    boolean isUserRestricted(int userId, String restrictionKey) {
9901        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9902        if (restrictions.getBoolean(restrictionKey, false)) {
9903            Log.w(TAG, "User is restricted: " + restrictionKey);
9904            return true;
9905        }
9906        return false;
9907    }
9908
9909    @Override
9910    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9911        mContext.enforceCallingOrSelfPermission(
9912                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9913                "Only package verification agents can verify applications");
9914
9915        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9916        final PackageVerificationResponse response = new PackageVerificationResponse(
9917                verificationCode, Binder.getCallingUid());
9918        msg.arg1 = id;
9919        msg.obj = response;
9920        mHandler.sendMessage(msg);
9921    }
9922
9923    @Override
9924    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9925            long millisecondsToDelay) {
9926        mContext.enforceCallingOrSelfPermission(
9927                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9928                "Only package verification agents can extend verification timeouts");
9929
9930        final PackageVerificationState state = mPendingVerification.get(id);
9931        final PackageVerificationResponse response = new PackageVerificationResponse(
9932                verificationCodeAtTimeout, Binder.getCallingUid());
9933
9934        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9935            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9936        }
9937        if (millisecondsToDelay < 0) {
9938            millisecondsToDelay = 0;
9939        }
9940        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9941                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9942            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9943        }
9944
9945        if ((state != null) && !state.timeoutExtended()) {
9946            state.extendTimeout();
9947
9948            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9949            msg.arg1 = id;
9950            msg.obj = response;
9951            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9952        }
9953    }
9954
9955    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9956            int verificationCode, UserHandle user) {
9957        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9958        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9959        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9960        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9961        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9962
9963        mContext.sendBroadcastAsUser(intent, user,
9964                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9965    }
9966
9967    private ComponentName matchComponentForVerifier(String packageName,
9968            List<ResolveInfo> receivers) {
9969        ActivityInfo targetReceiver = null;
9970
9971        final int NR = receivers.size();
9972        for (int i = 0; i < NR; i++) {
9973            final ResolveInfo info = receivers.get(i);
9974            if (info.activityInfo == null) {
9975                continue;
9976            }
9977
9978            if (packageName.equals(info.activityInfo.packageName)) {
9979                targetReceiver = info.activityInfo;
9980                break;
9981            }
9982        }
9983
9984        if (targetReceiver == null) {
9985            return null;
9986        }
9987
9988        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9989    }
9990
9991    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9992            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9993        if (pkgInfo.verifiers.length == 0) {
9994            return null;
9995        }
9996
9997        final int N = pkgInfo.verifiers.length;
9998        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9999        for (int i = 0; i < N; i++) {
10000            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10001
10002            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10003                    receivers);
10004            if (comp == null) {
10005                continue;
10006            }
10007
10008            final int verifierUid = getUidForVerifier(verifierInfo);
10009            if (verifierUid == -1) {
10010                continue;
10011            }
10012
10013            if (DEBUG_VERIFY) {
10014                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10015                        + " with the correct signature");
10016            }
10017            sufficientVerifiers.add(comp);
10018            verificationState.addSufficientVerifier(verifierUid);
10019        }
10020
10021        return sufficientVerifiers;
10022    }
10023
10024    private int getUidForVerifier(VerifierInfo verifierInfo) {
10025        synchronized (mPackages) {
10026            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10027            if (pkg == null) {
10028                return -1;
10029            } else if (pkg.mSignatures.length != 1) {
10030                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10031                        + " has more than one signature; ignoring");
10032                return -1;
10033            }
10034
10035            /*
10036             * If the public key of the package's signature does not match
10037             * our expected public key, then this is a different package and
10038             * we should skip.
10039             */
10040
10041            final byte[] expectedPublicKey;
10042            try {
10043                final Signature verifierSig = pkg.mSignatures[0];
10044                final PublicKey publicKey = verifierSig.getPublicKey();
10045                expectedPublicKey = publicKey.getEncoded();
10046            } catch (CertificateException e) {
10047                return -1;
10048            }
10049
10050            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10051
10052            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10053                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10054                        + " does not have the expected public key; ignoring");
10055                return -1;
10056            }
10057
10058            return pkg.applicationInfo.uid;
10059        }
10060    }
10061
10062    @Override
10063    public void finishPackageInstall(int token) {
10064        enforceSystemOrRoot("Only the system is allowed to finish installs");
10065
10066        if (DEBUG_INSTALL) {
10067            Slog.v(TAG, "BM finishing package install for " + token);
10068        }
10069        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10070
10071        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10072        mHandler.sendMessage(msg);
10073    }
10074
10075    /**
10076     * Get the verification agent timeout.
10077     *
10078     * @return verification timeout in milliseconds
10079     */
10080    private long getVerificationTimeout() {
10081        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10082                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10083                DEFAULT_VERIFICATION_TIMEOUT);
10084    }
10085
10086    /**
10087     * Get the default verification agent response code.
10088     *
10089     * @return default verification response code
10090     */
10091    private int getDefaultVerificationResponse() {
10092        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10093                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10094                DEFAULT_VERIFICATION_RESPONSE);
10095    }
10096
10097    /**
10098     * Check whether or not package verification has been enabled.
10099     *
10100     * @return true if verification should be performed
10101     */
10102    private boolean isVerificationEnabled(int userId, int installFlags) {
10103        if (!DEFAULT_VERIFY_ENABLE) {
10104            return false;
10105        }
10106
10107        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10108
10109        // Check if installing from ADB
10110        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10111            // Do not run verification in a test harness environment
10112            if (ActivityManager.isRunningInTestHarness()) {
10113                return false;
10114            }
10115            if (ensureVerifyAppsEnabled) {
10116                return true;
10117            }
10118            // Check if the developer does not want package verification for ADB installs
10119            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10120                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10121                return false;
10122            }
10123        }
10124
10125        if (ensureVerifyAppsEnabled) {
10126            return true;
10127        }
10128
10129        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10130                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10131    }
10132
10133    @Override
10134    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10135            throws RemoteException {
10136        mContext.enforceCallingOrSelfPermission(
10137                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10138                "Only intentfilter verification agents can verify applications");
10139
10140        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10141        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10142                Binder.getCallingUid(), verificationCode, failedDomains);
10143        msg.arg1 = id;
10144        msg.obj = response;
10145        mHandler.sendMessage(msg);
10146    }
10147
10148    @Override
10149    public int getIntentVerificationStatus(String packageName, int userId) {
10150        synchronized (mPackages) {
10151            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10152        }
10153    }
10154
10155    @Override
10156    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10157        mContext.enforceCallingOrSelfPermission(
10158                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10159
10160        boolean result = false;
10161        synchronized (mPackages) {
10162            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10163        }
10164        if (result) {
10165            scheduleWritePackageRestrictionsLocked(userId);
10166        }
10167        return result;
10168    }
10169
10170    @Override
10171    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10172        synchronized (mPackages) {
10173            return mSettings.getIntentFilterVerificationsLPr(packageName);
10174        }
10175    }
10176
10177    @Override
10178    public List<IntentFilter> getAllIntentFilters(String packageName) {
10179        if (TextUtils.isEmpty(packageName)) {
10180            return Collections.<IntentFilter>emptyList();
10181        }
10182        synchronized (mPackages) {
10183            PackageParser.Package pkg = mPackages.get(packageName);
10184            if (pkg == null || pkg.activities == null) {
10185                return Collections.<IntentFilter>emptyList();
10186            }
10187            final int count = pkg.activities.size();
10188            ArrayList<IntentFilter> result = new ArrayList<>();
10189            for (int n=0; n<count; n++) {
10190                PackageParser.Activity activity = pkg.activities.get(n);
10191                if (activity.intents != null || activity.intents.size() > 0) {
10192                    result.addAll(activity.intents);
10193                }
10194            }
10195            return result;
10196        }
10197    }
10198
10199    @Override
10200    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10201        mContext.enforceCallingOrSelfPermission(
10202                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10203
10204        synchronized (mPackages) {
10205            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10206            if (packageName != null) {
10207                result |= updateIntentVerificationStatus(packageName,
10208                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10209                        userId);
10210                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10211                        packageName, userId);
10212            }
10213            return result;
10214        }
10215    }
10216
10217    @Override
10218    public String getDefaultBrowserPackageName(int userId) {
10219        synchronized (mPackages) {
10220            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10221        }
10222    }
10223
10224    /**
10225     * Get the "allow unknown sources" setting.
10226     *
10227     * @return the current "allow unknown sources" setting
10228     */
10229    private int getUnknownSourcesSettings() {
10230        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10231                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10232                -1);
10233    }
10234
10235    @Override
10236    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10237        final int uid = Binder.getCallingUid();
10238        // writer
10239        synchronized (mPackages) {
10240            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10241            if (targetPackageSetting == null) {
10242                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10243            }
10244
10245            PackageSetting installerPackageSetting;
10246            if (installerPackageName != null) {
10247                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10248                if (installerPackageSetting == null) {
10249                    throw new IllegalArgumentException("Unknown installer package: "
10250                            + installerPackageName);
10251                }
10252            } else {
10253                installerPackageSetting = null;
10254            }
10255
10256            Signature[] callerSignature;
10257            Object obj = mSettings.getUserIdLPr(uid);
10258            if (obj != null) {
10259                if (obj instanceof SharedUserSetting) {
10260                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10261                } else if (obj instanceof PackageSetting) {
10262                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10263                } else {
10264                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10265                }
10266            } else {
10267                throw new SecurityException("Unknown calling uid " + uid);
10268            }
10269
10270            // Verify: can't set installerPackageName to a package that is
10271            // not signed with the same cert as the caller.
10272            if (installerPackageSetting != null) {
10273                if (compareSignatures(callerSignature,
10274                        installerPackageSetting.signatures.mSignatures)
10275                        != PackageManager.SIGNATURE_MATCH) {
10276                    throw new SecurityException(
10277                            "Caller does not have same cert as new installer package "
10278                            + installerPackageName);
10279                }
10280            }
10281
10282            // Verify: if target already has an installer package, it must
10283            // be signed with the same cert as the caller.
10284            if (targetPackageSetting.installerPackageName != null) {
10285                PackageSetting setting = mSettings.mPackages.get(
10286                        targetPackageSetting.installerPackageName);
10287                // If the currently set package isn't valid, then it's always
10288                // okay to change it.
10289                if (setting != null) {
10290                    if (compareSignatures(callerSignature,
10291                            setting.signatures.mSignatures)
10292                            != PackageManager.SIGNATURE_MATCH) {
10293                        throw new SecurityException(
10294                                "Caller does not have same cert as old installer package "
10295                                + targetPackageSetting.installerPackageName);
10296                    }
10297                }
10298            }
10299
10300            // Okay!
10301            targetPackageSetting.installerPackageName = installerPackageName;
10302            scheduleWriteSettingsLocked();
10303        }
10304    }
10305
10306    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10307        // Queue up an async operation since the package installation may take a little while.
10308        mHandler.post(new Runnable() {
10309            public void run() {
10310                mHandler.removeCallbacks(this);
10311                 // Result object to be returned
10312                PackageInstalledInfo res = new PackageInstalledInfo();
10313                res.returnCode = currentStatus;
10314                res.uid = -1;
10315                res.pkg = null;
10316                res.removedInfo = new PackageRemovedInfo();
10317                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10318                    args.doPreInstall(res.returnCode);
10319                    synchronized (mInstallLock) {
10320                        installPackageTracedLI(args, res);
10321                    }
10322                    args.doPostInstall(res.returnCode, res.uid);
10323                }
10324
10325                // A restore should be performed at this point if (a) the install
10326                // succeeded, (b) the operation is not an update, and (c) the new
10327                // package has not opted out of backup participation.
10328                final boolean update = res.removedInfo.removedPackage != null;
10329                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10330                boolean doRestore = !update
10331                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10332
10333                // Set up the post-install work request bookkeeping.  This will be used
10334                // and cleaned up by the post-install event handling regardless of whether
10335                // there's a restore pass performed.  Token values are >= 1.
10336                int token;
10337                if (mNextInstallToken < 0) mNextInstallToken = 1;
10338                token = mNextInstallToken++;
10339
10340                PostInstallData data = new PostInstallData(args, res);
10341                mRunningInstalls.put(token, data);
10342                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10343
10344                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10345                    // Pass responsibility to the Backup Manager.  It will perform a
10346                    // restore if appropriate, then pass responsibility back to the
10347                    // Package Manager to run the post-install observer callbacks
10348                    // and broadcasts.
10349                    IBackupManager bm = IBackupManager.Stub.asInterface(
10350                            ServiceManager.getService(Context.BACKUP_SERVICE));
10351                    if (bm != null) {
10352                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10353                                + " to BM for possible restore");
10354                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10355                        try {
10356                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10357                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10358                            } else {
10359                                doRestore = false;
10360                            }
10361                        } catch (RemoteException e) {
10362                            // can't happen; the backup manager is local
10363                        } catch (Exception e) {
10364                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10365                            doRestore = false;
10366                        }
10367                    } else {
10368                        Slog.e(TAG, "Backup Manager not found!");
10369                        doRestore = false;
10370                    }
10371                }
10372
10373                if (!doRestore) {
10374                    // No restore possible, or the Backup Manager was mysteriously not
10375                    // available -- just fire the post-install work request directly.
10376                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10377
10378                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10379
10380                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10381                    mHandler.sendMessage(msg);
10382                }
10383            }
10384        });
10385    }
10386
10387    private abstract class HandlerParams {
10388        private static final int MAX_RETRIES = 4;
10389
10390        /**
10391         * Number of times startCopy() has been attempted and had a non-fatal
10392         * error.
10393         */
10394        private int mRetries = 0;
10395
10396        /** User handle for the user requesting the information or installation. */
10397        private final UserHandle mUser;
10398        String traceMethod;
10399        int traceCookie;
10400
10401        HandlerParams(UserHandle user) {
10402            mUser = user;
10403        }
10404
10405        UserHandle getUser() {
10406            return mUser;
10407        }
10408
10409        HandlerParams setTraceMethod(String traceMethod) {
10410            this.traceMethod = traceMethod;
10411            return this;
10412        }
10413
10414        HandlerParams setTraceCookie(int traceCookie) {
10415            this.traceCookie = traceCookie;
10416            return this;
10417        }
10418
10419        final boolean startCopy() {
10420            boolean res;
10421            try {
10422                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10423
10424                if (++mRetries > MAX_RETRIES) {
10425                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10426                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10427                    handleServiceError();
10428                    return false;
10429                } else {
10430                    handleStartCopy();
10431                    res = true;
10432                }
10433            } catch (RemoteException e) {
10434                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10435                mHandler.sendEmptyMessage(MCS_RECONNECT);
10436                res = false;
10437            }
10438            handleReturnCode();
10439            return res;
10440        }
10441
10442        final void serviceError() {
10443            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10444            handleServiceError();
10445            handleReturnCode();
10446        }
10447
10448        abstract void handleStartCopy() throws RemoteException;
10449        abstract void handleServiceError();
10450        abstract void handleReturnCode();
10451    }
10452
10453    class MeasureParams extends HandlerParams {
10454        private final PackageStats mStats;
10455        private boolean mSuccess;
10456
10457        private final IPackageStatsObserver mObserver;
10458
10459        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10460            super(new UserHandle(stats.userHandle));
10461            mObserver = observer;
10462            mStats = stats;
10463        }
10464
10465        @Override
10466        public String toString() {
10467            return "MeasureParams{"
10468                + Integer.toHexString(System.identityHashCode(this))
10469                + " " + mStats.packageName + "}";
10470        }
10471
10472        @Override
10473        void handleStartCopy() throws RemoteException {
10474            synchronized (mInstallLock) {
10475                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10476            }
10477
10478            if (mSuccess) {
10479                final boolean mounted;
10480                if (Environment.isExternalStorageEmulated()) {
10481                    mounted = true;
10482                } else {
10483                    final String status = Environment.getExternalStorageState();
10484                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10485                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10486                }
10487
10488                if (mounted) {
10489                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10490
10491                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10492                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10493
10494                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10495                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10496
10497                    // Always subtract cache size, since it's a subdirectory
10498                    mStats.externalDataSize -= mStats.externalCacheSize;
10499
10500                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10501                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10502
10503                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10504                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10505                }
10506            }
10507        }
10508
10509        @Override
10510        void handleReturnCode() {
10511            if (mObserver != null) {
10512                try {
10513                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10514                } catch (RemoteException e) {
10515                    Slog.i(TAG, "Observer no longer exists.");
10516                }
10517            }
10518        }
10519
10520        @Override
10521        void handleServiceError() {
10522            Slog.e(TAG, "Could not measure application " + mStats.packageName
10523                            + " external storage");
10524        }
10525    }
10526
10527    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10528            throws RemoteException {
10529        long result = 0;
10530        for (File path : paths) {
10531            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10532        }
10533        return result;
10534    }
10535
10536    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10537        for (File path : paths) {
10538            try {
10539                mcs.clearDirectory(path.getAbsolutePath());
10540            } catch (RemoteException e) {
10541            }
10542        }
10543    }
10544
10545    static class OriginInfo {
10546        /**
10547         * Location where install is coming from, before it has been
10548         * copied/renamed into place. This could be a single monolithic APK
10549         * file, or a cluster directory. This location may be untrusted.
10550         */
10551        final File file;
10552        final String cid;
10553
10554        /**
10555         * Flag indicating that {@link #file} or {@link #cid} has already been
10556         * staged, meaning downstream users don't need to defensively copy the
10557         * contents.
10558         */
10559        final boolean staged;
10560
10561        /**
10562         * Flag indicating that {@link #file} or {@link #cid} is an already
10563         * installed app that is being moved.
10564         */
10565        final boolean existing;
10566
10567        final String resolvedPath;
10568        final File resolvedFile;
10569
10570        static OriginInfo fromNothing() {
10571            return new OriginInfo(null, null, false, false);
10572        }
10573
10574        static OriginInfo fromUntrustedFile(File file) {
10575            return new OriginInfo(file, null, false, false);
10576        }
10577
10578        static OriginInfo fromExistingFile(File file) {
10579            return new OriginInfo(file, null, false, true);
10580        }
10581
10582        static OriginInfo fromStagedFile(File file) {
10583            return new OriginInfo(file, null, true, false);
10584        }
10585
10586        static OriginInfo fromStagedContainer(String cid) {
10587            return new OriginInfo(null, cid, true, false);
10588        }
10589
10590        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10591            this.file = file;
10592            this.cid = cid;
10593            this.staged = staged;
10594            this.existing = existing;
10595
10596            if (cid != null) {
10597                resolvedPath = PackageHelper.getSdDir(cid);
10598                resolvedFile = new File(resolvedPath);
10599            } else if (file != null) {
10600                resolvedPath = file.getAbsolutePath();
10601                resolvedFile = file;
10602            } else {
10603                resolvedPath = null;
10604                resolvedFile = null;
10605            }
10606        }
10607    }
10608
10609    class MoveInfo {
10610        final int moveId;
10611        final String fromUuid;
10612        final String toUuid;
10613        final String packageName;
10614        final String dataAppName;
10615        final int appId;
10616        final String seinfo;
10617
10618        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10619                String dataAppName, int appId, String seinfo) {
10620            this.moveId = moveId;
10621            this.fromUuid = fromUuid;
10622            this.toUuid = toUuid;
10623            this.packageName = packageName;
10624            this.dataAppName = dataAppName;
10625            this.appId = appId;
10626            this.seinfo = seinfo;
10627        }
10628    }
10629
10630    class InstallParams extends HandlerParams {
10631        final OriginInfo origin;
10632        final MoveInfo move;
10633        final IPackageInstallObserver2 observer;
10634        int installFlags;
10635        final String installerPackageName;
10636        final String volumeUuid;
10637        final VerificationParams verificationParams;
10638        private InstallArgs mArgs;
10639        private int mRet;
10640        final String packageAbiOverride;
10641        final String[] grantedRuntimePermissions;
10642
10643        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10644                int installFlags, String installerPackageName, String volumeUuid,
10645                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10646                String[] grantedPermissions) {
10647            super(user);
10648            this.origin = origin;
10649            this.move = move;
10650            this.observer = observer;
10651            this.installFlags = installFlags;
10652            this.installerPackageName = installerPackageName;
10653            this.volumeUuid = volumeUuid;
10654            this.verificationParams = verificationParams;
10655            this.packageAbiOverride = packageAbiOverride;
10656            this.grantedRuntimePermissions = grantedPermissions;
10657        }
10658
10659        @Override
10660        public String toString() {
10661            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10662                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10663        }
10664
10665        public ManifestDigest getManifestDigest() {
10666            if (verificationParams == null) {
10667                return null;
10668            }
10669            return verificationParams.getManifestDigest();
10670        }
10671
10672        private int installLocationPolicy(PackageInfoLite pkgLite) {
10673            String packageName = pkgLite.packageName;
10674            int installLocation = pkgLite.installLocation;
10675            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10676            // reader
10677            synchronized (mPackages) {
10678                PackageParser.Package pkg = mPackages.get(packageName);
10679                if (pkg != null) {
10680                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10681                        // Check for downgrading.
10682                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10683                            try {
10684                                checkDowngrade(pkg, pkgLite);
10685                            } catch (PackageManagerException e) {
10686                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10687                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10688                            }
10689                        }
10690                        // Check for updated system application.
10691                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10692                            if (onSd) {
10693                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10694                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10695                            }
10696                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10697                        } else {
10698                            if (onSd) {
10699                                // Install flag overrides everything.
10700                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10701                            }
10702                            // If current upgrade specifies particular preference
10703                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10704                                // Application explicitly specified internal.
10705                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10706                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10707                                // App explictly prefers external. Let policy decide
10708                            } else {
10709                                // Prefer previous location
10710                                if (isExternal(pkg)) {
10711                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10712                                }
10713                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10714                            }
10715                        }
10716                    } else {
10717                        // Invalid install. Return error code
10718                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10719                    }
10720                }
10721            }
10722            // All the special cases have been taken care of.
10723            // Return result based on recommended install location.
10724            if (onSd) {
10725                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10726            }
10727            return pkgLite.recommendedInstallLocation;
10728        }
10729
10730        /*
10731         * Invoke remote method to get package information and install
10732         * location values. Override install location based on default
10733         * policy if needed and then create install arguments based
10734         * on the install location.
10735         */
10736        public void handleStartCopy() throws RemoteException {
10737            int ret = PackageManager.INSTALL_SUCCEEDED;
10738
10739            // If we're already staged, we've firmly committed to an install location
10740            if (origin.staged) {
10741                if (origin.file != null) {
10742                    installFlags |= PackageManager.INSTALL_INTERNAL;
10743                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10744                } else if (origin.cid != null) {
10745                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10746                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10747                } else {
10748                    throw new IllegalStateException("Invalid stage location");
10749                }
10750            }
10751
10752            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10753            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10754            PackageInfoLite pkgLite = null;
10755
10756            if (onInt && onSd) {
10757                // Check if both bits are set.
10758                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10759                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10760            } else {
10761                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10762                        packageAbiOverride);
10763
10764                /*
10765                 * If we have too little free space, try to free cache
10766                 * before giving up.
10767                 */
10768                if (!origin.staged && pkgLite.recommendedInstallLocation
10769                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10770                    // TODO: focus freeing disk space on the target device
10771                    final StorageManager storage = StorageManager.from(mContext);
10772                    final long lowThreshold = storage.getStorageLowBytes(
10773                            Environment.getDataDirectory());
10774
10775                    final long sizeBytes = mContainerService.calculateInstalledSize(
10776                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10777
10778                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10779                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10780                                installFlags, packageAbiOverride);
10781                    }
10782
10783                    /*
10784                     * The cache free must have deleted the file we
10785                     * downloaded to install.
10786                     *
10787                     * TODO: fix the "freeCache" call to not delete
10788                     *       the file we care about.
10789                     */
10790                    if (pkgLite.recommendedInstallLocation
10791                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10792                        pkgLite.recommendedInstallLocation
10793                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10794                    }
10795                }
10796            }
10797
10798            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10799                int loc = pkgLite.recommendedInstallLocation;
10800                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10801                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10802                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10803                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10804                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10805                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10806                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10807                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10808                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10809                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10810                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10811                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10812                } else {
10813                    // Override with defaults if needed.
10814                    loc = installLocationPolicy(pkgLite);
10815                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10816                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10817                    } else if (!onSd && !onInt) {
10818                        // Override install location with flags
10819                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10820                            // Set the flag to install on external media.
10821                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10822                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10823                        } else {
10824                            // Make sure the flag for installing on external
10825                            // media is unset
10826                            installFlags |= PackageManager.INSTALL_INTERNAL;
10827                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10828                        }
10829                    }
10830                }
10831            }
10832
10833            final InstallArgs args = createInstallArgs(this);
10834            mArgs = args;
10835
10836            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10837                 /*
10838                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10839                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10840                 */
10841                int userIdentifier = getUser().getIdentifier();
10842                if (userIdentifier == UserHandle.USER_ALL
10843                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10844                    userIdentifier = UserHandle.USER_OWNER;
10845                }
10846
10847                /*
10848                 * Determine if we have any installed package verifiers. If we
10849                 * do, then we'll defer to them to verify the packages.
10850                 */
10851                final int requiredUid = mRequiredVerifierPackage == null ? -1
10852                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10853                if (!origin.existing && requiredUid != -1
10854                        && isVerificationEnabled(userIdentifier, installFlags)) {
10855                    final Intent verification = new Intent(
10856                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10857                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10858                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10859                            PACKAGE_MIME_TYPE);
10860                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10861
10862                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10863                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10864                            0 /* TODO: Which userId? */);
10865
10866                    if (DEBUG_VERIFY) {
10867                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10868                                + verification.toString() + " with " + pkgLite.verifiers.length
10869                                + " optional verifiers");
10870                    }
10871
10872                    final int verificationId = mPendingVerificationToken++;
10873
10874                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10875
10876                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10877                            installerPackageName);
10878
10879                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10880                            installFlags);
10881
10882                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10883                            pkgLite.packageName);
10884
10885                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10886                            pkgLite.versionCode);
10887
10888                    if (verificationParams != null) {
10889                        if (verificationParams.getVerificationURI() != null) {
10890                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10891                                 verificationParams.getVerificationURI());
10892                        }
10893                        if (verificationParams.getOriginatingURI() != null) {
10894                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10895                                  verificationParams.getOriginatingURI());
10896                        }
10897                        if (verificationParams.getReferrer() != null) {
10898                            verification.putExtra(Intent.EXTRA_REFERRER,
10899                                  verificationParams.getReferrer());
10900                        }
10901                        if (verificationParams.getOriginatingUid() >= 0) {
10902                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10903                                  verificationParams.getOriginatingUid());
10904                        }
10905                        if (verificationParams.getInstallerUid() >= 0) {
10906                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10907                                  verificationParams.getInstallerUid());
10908                        }
10909                    }
10910
10911                    final PackageVerificationState verificationState = new PackageVerificationState(
10912                            requiredUid, args);
10913
10914                    mPendingVerification.append(verificationId, verificationState);
10915
10916                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10917                            receivers, verificationState);
10918
10919                    // Apps installed for "all" users use the device owner to verify the app
10920                    UserHandle verifierUser = getUser();
10921                    if (verifierUser == UserHandle.ALL) {
10922                        verifierUser = UserHandle.OWNER;
10923                    }
10924
10925                    /*
10926                     * If any sufficient verifiers were listed in the package
10927                     * manifest, attempt to ask them.
10928                     */
10929                    if (sufficientVerifiers != null) {
10930                        final int N = sufficientVerifiers.size();
10931                        if (N == 0) {
10932                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10933                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10934                        } else {
10935                            for (int i = 0; i < N; i++) {
10936                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10937
10938                                final Intent sufficientIntent = new Intent(verification);
10939                                sufficientIntent.setComponent(verifierComponent);
10940                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10941                            }
10942                        }
10943                    }
10944
10945                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10946                            mRequiredVerifierPackage, receivers);
10947                    if (ret == PackageManager.INSTALL_SUCCEEDED
10948                            && mRequiredVerifierPackage != null) {
10949                        Trace.asyncTraceBegin(
10950                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10951                        /*
10952                         * Send the intent to the required verification agent,
10953                         * but only start the verification timeout after the
10954                         * target BroadcastReceivers have run.
10955                         */
10956                        verification.setComponent(requiredVerifierComponent);
10957                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10958                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10959                                new BroadcastReceiver() {
10960                                    @Override
10961                                    public void onReceive(Context context, Intent intent) {
10962                                        final Message msg = mHandler
10963                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10964                                        msg.arg1 = verificationId;
10965                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10966                                    }
10967                                }, null, 0, null, null);
10968
10969                        /*
10970                         * We don't want the copy to proceed until verification
10971                         * succeeds, so null out this field.
10972                         */
10973                        mArgs = null;
10974                    }
10975                } else {
10976                    /*
10977                     * No package verification is enabled, so immediately start
10978                     * the remote call to initiate copy using temporary file.
10979                     */
10980                    ret = args.copyApk(mContainerService, true);
10981                }
10982            }
10983
10984            mRet = ret;
10985        }
10986
10987        @Override
10988        void handleReturnCode() {
10989            // If mArgs is null, then MCS couldn't be reached. When it
10990            // reconnects, it will try again to install. At that point, this
10991            // will succeed.
10992            if (mArgs != null) {
10993                processPendingInstall(mArgs, mRet);
10994            }
10995        }
10996
10997        @Override
10998        void handleServiceError() {
10999            mArgs = createInstallArgs(this);
11000            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11001        }
11002
11003        public boolean isForwardLocked() {
11004            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11005        }
11006    }
11007
11008    /**
11009     * Used during creation of InstallArgs
11010     *
11011     * @param installFlags package installation flags
11012     * @return true if should be installed on external storage
11013     */
11014    private static boolean installOnExternalAsec(int installFlags) {
11015        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11016            return false;
11017        }
11018        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11019            return true;
11020        }
11021        return false;
11022    }
11023
11024    /**
11025     * Used during creation of InstallArgs
11026     *
11027     * @param installFlags package installation flags
11028     * @return true if should be installed as forward locked
11029     */
11030    private static boolean installForwardLocked(int installFlags) {
11031        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11032    }
11033
11034    private InstallArgs createInstallArgs(InstallParams params) {
11035        if (params.move != null) {
11036            return new MoveInstallArgs(params);
11037        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11038            return new AsecInstallArgs(params);
11039        } else {
11040            return new FileInstallArgs(params);
11041        }
11042    }
11043
11044    /**
11045     * Create args that describe an existing installed package. Typically used
11046     * when cleaning up old installs, or used as a move source.
11047     */
11048    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11049            String resourcePath, String[] instructionSets) {
11050        final boolean isInAsec;
11051        if (installOnExternalAsec(installFlags)) {
11052            /* Apps on SD card are always in ASEC containers. */
11053            isInAsec = true;
11054        } else if (installForwardLocked(installFlags)
11055                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11056            /*
11057             * Forward-locked apps are only in ASEC containers if they're the
11058             * new style
11059             */
11060            isInAsec = true;
11061        } else {
11062            isInAsec = false;
11063        }
11064
11065        if (isInAsec) {
11066            return new AsecInstallArgs(codePath, instructionSets,
11067                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11068        } else {
11069            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11070        }
11071    }
11072
11073    static abstract class InstallArgs {
11074        /** @see InstallParams#origin */
11075        final OriginInfo origin;
11076        /** @see InstallParams#move */
11077        final MoveInfo move;
11078
11079        final IPackageInstallObserver2 observer;
11080        // Always refers to PackageManager flags only
11081        final int installFlags;
11082        final String installerPackageName;
11083        final String volumeUuid;
11084        final ManifestDigest manifestDigest;
11085        final UserHandle user;
11086        final String abiOverride;
11087        final String[] installGrantPermissions;
11088        /** If non-null, drop an async trace when the install completes */
11089        final String traceMethod;
11090        final int traceCookie;
11091
11092        // The list of instruction sets supported by this app. This is currently
11093        // only used during the rmdex() phase to clean up resources. We can get rid of this
11094        // if we move dex files under the common app path.
11095        /* nullable */ String[] instructionSets;
11096
11097        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11098                int installFlags, String installerPackageName, String volumeUuid,
11099                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11100                String abiOverride, String[] installGrantPermissions,
11101                String traceMethod, int traceCookie) {
11102            this.origin = origin;
11103            this.move = move;
11104            this.installFlags = installFlags;
11105            this.observer = observer;
11106            this.installerPackageName = installerPackageName;
11107            this.volumeUuid = volumeUuid;
11108            this.manifestDigest = manifestDigest;
11109            this.user = user;
11110            this.instructionSets = instructionSets;
11111            this.abiOverride = abiOverride;
11112            this.installGrantPermissions = installGrantPermissions;
11113            this.traceMethod = traceMethod;
11114            this.traceCookie = traceCookie;
11115        }
11116
11117        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11118        abstract int doPreInstall(int status);
11119
11120        /**
11121         * Rename package into final resting place. All paths on the given
11122         * scanned package should be updated to reflect the rename.
11123         */
11124        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11125        abstract int doPostInstall(int status, int uid);
11126
11127        /** @see PackageSettingBase#codePathString */
11128        abstract String getCodePath();
11129        /** @see PackageSettingBase#resourcePathString */
11130        abstract String getResourcePath();
11131
11132        // Need installer lock especially for dex file removal.
11133        abstract void cleanUpResourcesLI();
11134        abstract boolean doPostDeleteLI(boolean delete);
11135
11136        /**
11137         * Called before the source arguments are copied. This is used mostly
11138         * for MoveParams when it needs to read the source file to put it in the
11139         * destination.
11140         */
11141        int doPreCopy() {
11142            return PackageManager.INSTALL_SUCCEEDED;
11143        }
11144
11145        /**
11146         * Called after the source arguments are copied. This is used mostly for
11147         * MoveParams when it needs to read the source file to put it in the
11148         * destination.
11149         *
11150         * @return
11151         */
11152        int doPostCopy(int uid) {
11153            return PackageManager.INSTALL_SUCCEEDED;
11154        }
11155
11156        protected boolean isFwdLocked() {
11157            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11158        }
11159
11160        protected boolean isExternalAsec() {
11161            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11162        }
11163
11164        UserHandle getUser() {
11165            return user;
11166        }
11167    }
11168
11169    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11170        if (!allCodePaths.isEmpty()) {
11171            if (instructionSets == null) {
11172                throw new IllegalStateException("instructionSet == null");
11173            }
11174            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11175            for (String codePath : allCodePaths) {
11176                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11177                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11178                    if (retCode < 0) {
11179                        Slog.w(TAG, "Couldn't remove dex file for package: "
11180                                + " at location " + codePath + ", retcode=" + retCode);
11181                        // we don't consider this to be a failure of the core package deletion
11182                    }
11183                }
11184            }
11185        }
11186    }
11187
11188    /**
11189     * Logic to handle installation of non-ASEC applications, including copying
11190     * and renaming logic.
11191     */
11192    class FileInstallArgs extends InstallArgs {
11193        private File codeFile;
11194        private File resourceFile;
11195
11196        // Example topology:
11197        // /data/app/com.example/base.apk
11198        // /data/app/com.example/split_foo.apk
11199        // /data/app/com.example/lib/arm/libfoo.so
11200        // /data/app/com.example/lib/arm64/libfoo.so
11201        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11202
11203        /** New install */
11204        FileInstallArgs(InstallParams params) {
11205            super(params.origin, params.move, params.observer, params.installFlags,
11206                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11207                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11208                    params.grantedRuntimePermissions,
11209                    params.traceMethod, params.traceCookie);
11210            if (isFwdLocked()) {
11211                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11212            }
11213        }
11214
11215        /** Existing install */
11216        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11217            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11218                    null, null, null, 0);
11219            this.codeFile = (codePath != null) ? new File(codePath) : null;
11220            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11221        }
11222
11223        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11224            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11225            try {
11226                return doCopyApk(imcs, temp);
11227            } finally {
11228                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11229            }
11230        }
11231
11232        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11233            if (origin.staged) {
11234                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11235                codeFile = origin.file;
11236                resourceFile = origin.file;
11237                return PackageManager.INSTALL_SUCCEEDED;
11238            }
11239
11240            try {
11241                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11242                codeFile = tempDir;
11243                resourceFile = tempDir;
11244            } catch (IOException e) {
11245                Slog.w(TAG, "Failed to create copy file: " + e);
11246                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11247            }
11248
11249            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11250                @Override
11251                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11252                    if (!FileUtils.isValidExtFilename(name)) {
11253                        throw new IllegalArgumentException("Invalid filename: " + name);
11254                    }
11255                    try {
11256                        final File file = new File(codeFile, name);
11257                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11258                                O_RDWR | O_CREAT, 0644);
11259                        Os.chmod(file.getAbsolutePath(), 0644);
11260                        return new ParcelFileDescriptor(fd);
11261                    } catch (ErrnoException e) {
11262                        throw new RemoteException("Failed to open: " + e.getMessage());
11263                    }
11264                }
11265            };
11266
11267            int ret = PackageManager.INSTALL_SUCCEEDED;
11268            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11269            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11270                Slog.e(TAG, "Failed to copy package");
11271                return ret;
11272            }
11273
11274            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11275            NativeLibraryHelper.Handle handle = null;
11276            try {
11277                handle = NativeLibraryHelper.Handle.create(codeFile);
11278                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11279                        abiOverride);
11280            } catch (IOException e) {
11281                Slog.e(TAG, "Copying native libraries failed", e);
11282                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11283            } finally {
11284                IoUtils.closeQuietly(handle);
11285            }
11286
11287            return ret;
11288        }
11289
11290        int doPreInstall(int status) {
11291            if (status != PackageManager.INSTALL_SUCCEEDED) {
11292                cleanUp();
11293            }
11294            return status;
11295        }
11296
11297        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11298            if (status != PackageManager.INSTALL_SUCCEEDED) {
11299                cleanUp();
11300                return false;
11301            }
11302
11303            final File targetDir = codeFile.getParentFile();
11304            final File beforeCodeFile = codeFile;
11305            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11306
11307            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11308            try {
11309                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11310            } catch (ErrnoException e) {
11311                Slog.w(TAG, "Failed to rename", e);
11312                return false;
11313            }
11314
11315            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11316                Slog.w(TAG, "Failed to restorecon");
11317                return false;
11318            }
11319
11320            // Reflect the rename internally
11321            codeFile = afterCodeFile;
11322            resourceFile = afterCodeFile;
11323
11324            // Reflect the rename in scanned details
11325            pkg.codePath = afterCodeFile.getAbsolutePath();
11326            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11327                    pkg.baseCodePath);
11328            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11329                    pkg.splitCodePaths);
11330
11331            // Reflect the rename in app info
11332            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11333            pkg.applicationInfo.setCodePath(pkg.codePath);
11334            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11335            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11336            pkg.applicationInfo.setResourcePath(pkg.codePath);
11337            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11338            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11339
11340            return true;
11341        }
11342
11343        int doPostInstall(int status, int uid) {
11344            if (status != PackageManager.INSTALL_SUCCEEDED) {
11345                cleanUp();
11346            }
11347            return status;
11348        }
11349
11350        @Override
11351        String getCodePath() {
11352            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11353        }
11354
11355        @Override
11356        String getResourcePath() {
11357            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11358        }
11359
11360        private boolean cleanUp() {
11361            if (codeFile == null || !codeFile.exists()) {
11362                return false;
11363            }
11364
11365            if (codeFile.isDirectory()) {
11366                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11367            } else {
11368                codeFile.delete();
11369            }
11370
11371            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11372                resourceFile.delete();
11373            }
11374
11375            return true;
11376        }
11377
11378        void cleanUpResourcesLI() {
11379            // Try enumerating all code paths before deleting
11380            List<String> allCodePaths = Collections.EMPTY_LIST;
11381            if (codeFile != null && codeFile.exists()) {
11382                try {
11383                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11384                    allCodePaths = pkg.getAllCodePaths();
11385                } catch (PackageParserException e) {
11386                    // Ignored; we tried our best
11387                }
11388            }
11389
11390            cleanUp();
11391            removeDexFiles(allCodePaths, instructionSets);
11392        }
11393
11394        boolean doPostDeleteLI(boolean delete) {
11395            // XXX err, shouldn't we respect the delete flag?
11396            cleanUpResourcesLI();
11397            return true;
11398        }
11399    }
11400
11401    private boolean isAsecExternal(String cid) {
11402        final String asecPath = PackageHelper.getSdFilesystem(cid);
11403        return !asecPath.startsWith(mAsecInternalPath);
11404    }
11405
11406    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11407            PackageManagerException {
11408        if (copyRet < 0) {
11409            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11410                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11411                throw new PackageManagerException(copyRet, message);
11412            }
11413        }
11414    }
11415
11416    /**
11417     * Extract the MountService "container ID" from the full code path of an
11418     * .apk.
11419     */
11420    static String cidFromCodePath(String fullCodePath) {
11421        int eidx = fullCodePath.lastIndexOf("/");
11422        String subStr1 = fullCodePath.substring(0, eidx);
11423        int sidx = subStr1.lastIndexOf("/");
11424        return subStr1.substring(sidx+1, eidx);
11425    }
11426
11427    /**
11428     * Logic to handle installation of ASEC applications, including copying and
11429     * renaming logic.
11430     */
11431    class AsecInstallArgs extends InstallArgs {
11432        static final String RES_FILE_NAME = "pkg.apk";
11433        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11434
11435        String cid;
11436        String packagePath;
11437        String resourcePath;
11438
11439        /** New install */
11440        AsecInstallArgs(InstallParams params) {
11441            super(params.origin, params.move, params.observer, params.installFlags,
11442                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11443                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11444                    params.grantedRuntimePermissions,
11445                    params.traceMethod, params.traceCookie);
11446        }
11447
11448        /** Existing install */
11449        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11450                        boolean isExternal, boolean isForwardLocked) {
11451            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11452                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11453                    instructionSets, null, null, null, 0);
11454            // Hackily pretend we're still looking at a full code path
11455            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11456                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11457            }
11458
11459            // Extract cid from fullCodePath
11460            int eidx = fullCodePath.lastIndexOf("/");
11461            String subStr1 = fullCodePath.substring(0, eidx);
11462            int sidx = subStr1.lastIndexOf("/");
11463            cid = subStr1.substring(sidx+1, eidx);
11464            setMountPath(subStr1);
11465        }
11466
11467        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11468            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11469                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11470                    instructionSets, null, null, null, 0);
11471            this.cid = cid;
11472            setMountPath(PackageHelper.getSdDir(cid));
11473        }
11474
11475        void createCopyFile() {
11476            cid = mInstallerService.allocateExternalStageCidLegacy();
11477        }
11478
11479        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11480            if (origin.staged) {
11481                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11482                cid = origin.cid;
11483                setMountPath(PackageHelper.getSdDir(cid));
11484                return PackageManager.INSTALL_SUCCEEDED;
11485            }
11486
11487            if (temp) {
11488                createCopyFile();
11489            } else {
11490                /*
11491                 * Pre-emptively destroy the container since it's destroyed if
11492                 * copying fails due to it existing anyway.
11493                 */
11494                PackageHelper.destroySdDir(cid);
11495            }
11496
11497            final String newMountPath = imcs.copyPackageToContainer(
11498                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11499                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11500
11501            if (newMountPath != null) {
11502                setMountPath(newMountPath);
11503                return PackageManager.INSTALL_SUCCEEDED;
11504            } else {
11505                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11506            }
11507        }
11508
11509        @Override
11510        String getCodePath() {
11511            return packagePath;
11512        }
11513
11514        @Override
11515        String getResourcePath() {
11516            return resourcePath;
11517        }
11518
11519        int doPreInstall(int status) {
11520            if (status != PackageManager.INSTALL_SUCCEEDED) {
11521                // Destroy container
11522                PackageHelper.destroySdDir(cid);
11523            } else {
11524                boolean mounted = PackageHelper.isContainerMounted(cid);
11525                if (!mounted) {
11526                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11527                            Process.SYSTEM_UID);
11528                    if (newMountPath != null) {
11529                        setMountPath(newMountPath);
11530                    } else {
11531                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11532                    }
11533                }
11534            }
11535            return status;
11536        }
11537
11538        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11539            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11540            String newMountPath = null;
11541            if (PackageHelper.isContainerMounted(cid)) {
11542                // Unmount the container
11543                if (!PackageHelper.unMountSdDir(cid)) {
11544                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11545                    return false;
11546                }
11547            }
11548            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11549                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11550                        " which might be stale. Will try to clean up.");
11551                // Clean up the stale container and proceed to recreate.
11552                if (!PackageHelper.destroySdDir(newCacheId)) {
11553                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11554                    return false;
11555                }
11556                // Successfully cleaned up stale container. Try to rename again.
11557                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11558                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11559                            + " inspite of cleaning it up.");
11560                    return false;
11561                }
11562            }
11563            if (!PackageHelper.isContainerMounted(newCacheId)) {
11564                Slog.w(TAG, "Mounting container " + newCacheId);
11565                newMountPath = PackageHelper.mountSdDir(newCacheId,
11566                        getEncryptKey(), Process.SYSTEM_UID);
11567            } else {
11568                newMountPath = PackageHelper.getSdDir(newCacheId);
11569            }
11570            if (newMountPath == null) {
11571                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11572                return false;
11573            }
11574            Log.i(TAG, "Succesfully renamed " + cid +
11575                    " to " + newCacheId +
11576                    " at new path: " + newMountPath);
11577            cid = newCacheId;
11578
11579            final File beforeCodeFile = new File(packagePath);
11580            setMountPath(newMountPath);
11581            final File afterCodeFile = new File(packagePath);
11582
11583            // Reflect the rename in scanned details
11584            pkg.codePath = afterCodeFile.getAbsolutePath();
11585            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11586                    pkg.baseCodePath);
11587            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11588                    pkg.splitCodePaths);
11589
11590            // Reflect the rename in app info
11591            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11592            pkg.applicationInfo.setCodePath(pkg.codePath);
11593            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11594            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11595            pkg.applicationInfo.setResourcePath(pkg.codePath);
11596            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11597            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11598
11599            return true;
11600        }
11601
11602        private void setMountPath(String mountPath) {
11603            final File mountFile = new File(mountPath);
11604
11605            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11606            if (monolithicFile.exists()) {
11607                packagePath = monolithicFile.getAbsolutePath();
11608                if (isFwdLocked()) {
11609                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11610                } else {
11611                    resourcePath = packagePath;
11612                }
11613            } else {
11614                packagePath = mountFile.getAbsolutePath();
11615                resourcePath = packagePath;
11616            }
11617        }
11618
11619        int doPostInstall(int status, int uid) {
11620            if (status != PackageManager.INSTALL_SUCCEEDED) {
11621                cleanUp();
11622            } else {
11623                final int groupOwner;
11624                final String protectedFile;
11625                if (isFwdLocked()) {
11626                    groupOwner = UserHandle.getSharedAppGid(uid);
11627                    protectedFile = RES_FILE_NAME;
11628                } else {
11629                    groupOwner = -1;
11630                    protectedFile = null;
11631                }
11632
11633                if (uid < Process.FIRST_APPLICATION_UID
11634                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11635                    Slog.e(TAG, "Failed to finalize " + cid);
11636                    PackageHelper.destroySdDir(cid);
11637                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11638                }
11639
11640                boolean mounted = PackageHelper.isContainerMounted(cid);
11641                if (!mounted) {
11642                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11643                }
11644            }
11645            return status;
11646        }
11647
11648        private void cleanUp() {
11649            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11650
11651            // Destroy secure container
11652            PackageHelper.destroySdDir(cid);
11653        }
11654
11655        private List<String> getAllCodePaths() {
11656            final File codeFile = new File(getCodePath());
11657            if (codeFile != null && codeFile.exists()) {
11658                try {
11659                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11660                    return pkg.getAllCodePaths();
11661                } catch (PackageParserException e) {
11662                    // Ignored; we tried our best
11663                }
11664            }
11665            return Collections.EMPTY_LIST;
11666        }
11667
11668        void cleanUpResourcesLI() {
11669            // Enumerate all code paths before deleting
11670            cleanUpResourcesLI(getAllCodePaths());
11671        }
11672
11673        private void cleanUpResourcesLI(List<String> allCodePaths) {
11674            cleanUp();
11675            removeDexFiles(allCodePaths, instructionSets);
11676        }
11677
11678        String getPackageName() {
11679            return getAsecPackageName(cid);
11680        }
11681
11682        boolean doPostDeleteLI(boolean delete) {
11683            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11684            final List<String> allCodePaths = getAllCodePaths();
11685            boolean mounted = PackageHelper.isContainerMounted(cid);
11686            if (mounted) {
11687                // Unmount first
11688                if (PackageHelper.unMountSdDir(cid)) {
11689                    mounted = false;
11690                }
11691            }
11692            if (!mounted && delete) {
11693                cleanUpResourcesLI(allCodePaths);
11694            }
11695            return !mounted;
11696        }
11697
11698        @Override
11699        int doPreCopy() {
11700            if (isFwdLocked()) {
11701                if (!PackageHelper.fixSdPermissions(cid,
11702                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11703                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11704                }
11705            }
11706
11707            return PackageManager.INSTALL_SUCCEEDED;
11708        }
11709
11710        @Override
11711        int doPostCopy(int uid) {
11712            if (isFwdLocked()) {
11713                if (uid < Process.FIRST_APPLICATION_UID
11714                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11715                                RES_FILE_NAME)) {
11716                    Slog.e(TAG, "Failed to finalize " + cid);
11717                    PackageHelper.destroySdDir(cid);
11718                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11719                }
11720            }
11721
11722            return PackageManager.INSTALL_SUCCEEDED;
11723        }
11724    }
11725
11726    /**
11727     * Logic to handle movement of existing installed applications.
11728     */
11729    class MoveInstallArgs extends InstallArgs {
11730        private File codeFile;
11731        private File resourceFile;
11732
11733        /** New install */
11734        MoveInstallArgs(InstallParams params) {
11735            super(params.origin, params.move, params.observer, params.installFlags,
11736                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11737                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11738                    params.grantedRuntimePermissions,
11739                    params.traceMethod, params.traceCookie);
11740        }
11741
11742        int copyApk(IMediaContainerService imcs, boolean temp) {
11743            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11744                    + move.fromUuid + " to " + move.toUuid);
11745            synchronized (mInstaller) {
11746                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11747                        move.dataAppName, move.appId, move.seinfo) != 0) {
11748                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11749                }
11750            }
11751
11752            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11753            resourceFile = codeFile;
11754            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11755
11756            return PackageManager.INSTALL_SUCCEEDED;
11757        }
11758
11759        int doPreInstall(int status) {
11760            if (status != PackageManager.INSTALL_SUCCEEDED) {
11761                cleanUp(move.toUuid);
11762            }
11763            return status;
11764        }
11765
11766        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11767            if (status != PackageManager.INSTALL_SUCCEEDED) {
11768                cleanUp(move.toUuid);
11769                return false;
11770            }
11771
11772            // Reflect the move in app info
11773            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11774            pkg.applicationInfo.setCodePath(pkg.codePath);
11775            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11776            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11777            pkg.applicationInfo.setResourcePath(pkg.codePath);
11778            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11779            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11780
11781            return true;
11782        }
11783
11784        int doPostInstall(int status, int uid) {
11785            if (status == PackageManager.INSTALL_SUCCEEDED) {
11786                cleanUp(move.fromUuid);
11787            } else {
11788                cleanUp(move.toUuid);
11789            }
11790            return status;
11791        }
11792
11793        @Override
11794        String getCodePath() {
11795            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11796        }
11797
11798        @Override
11799        String getResourcePath() {
11800            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11801        }
11802
11803        private boolean cleanUp(String volumeUuid) {
11804            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11805                    move.dataAppName);
11806            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11807            synchronized (mInstallLock) {
11808                // Clean up both app data and code
11809                removeDataDirsLI(volumeUuid, move.packageName);
11810                if (codeFile.isDirectory()) {
11811                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11812                } else {
11813                    codeFile.delete();
11814                }
11815            }
11816            return true;
11817        }
11818
11819        void cleanUpResourcesLI() {
11820            throw new UnsupportedOperationException();
11821        }
11822
11823        boolean doPostDeleteLI(boolean delete) {
11824            throw new UnsupportedOperationException();
11825        }
11826    }
11827
11828    static String getAsecPackageName(String packageCid) {
11829        int idx = packageCid.lastIndexOf("-");
11830        if (idx == -1) {
11831            return packageCid;
11832        }
11833        return packageCid.substring(0, idx);
11834    }
11835
11836    // Utility method used to create code paths based on package name and available index.
11837    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11838        String idxStr = "";
11839        int idx = 1;
11840        // Fall back to default value of idx=1 if prefix is not
11841        // part of oldCodePath
11842        if (oldCodePath != null) {
11843            String subStr = oldCodePath;
11844            // Drop the suffix right away
11845            if (suffix != null && subStr.endsWith(suffix)) {
11846                subStr = subStr.substring(0, subStr.length() - suffix.length());
11847            }
11848            // If oldCodePath already contains prefix find out the
11849            // ending index to either increment or decrement.
11850            int sidx = subStr.lastIndexOf(prefix);
11851            if (sidx != -1) {
11852                subStr = subStr.substring(sidx + prefix.length());
11853                if (subStr != null) {
11854                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11855                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11856                    }
11857                    try {
11858                        idx = Integer.parseInt(subStr);
11859                        if (idx <= 1) {
11860                            idx++;
11861                        } else {
11862                            idx--;
11863                        }
11864                    } catch(NumberFormatException e) {
11865                    }
11866                }
11867            }
11868        }
11869        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11870        return prefix + idxStr;
11871    }
11872
11873    private File getNextCodePath(File targetDir, String packageName) {
11874        int suffix = 1;
11875        File result;
11876        do {
11877            result = new File(targetDir, packageName + "-" + suffix);
11878            suffix++;
11879        } while (result.exists());
11880        return result;
11881    }
11882
11883    // Utility method that returns the relative package path with respect
11884    // to the installation directory. Like say for /data/data/com.test-1.apk
11885    // string com.test-1 is returned.
11886    static String deriveCodePathName(String codePath) {
11887        if (codePath == null) {
11888            return null;
11889        }
11890        final File codeFile = new File(codePath);
11891        final String name = codeFile.getName();
11892        if (codeFile.isDirectory()) {
11893            return name;
11894        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11895            final int lastDot = name.lastIndexOf('.');
11896            return name.substring(0, lastDot);
11897        } else {
11898            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11899            return null;
11900        }
11901    }
11902
11903    class PackageInstalledInfo {
11904        String name;
11905        int uid;
11906        // The set of users that originally had this package installed.
11907        int[] origUsers;
11908        // The set of users that now have this package installed.
11909        int[] newUsers;
11910        PackageParser.Package pkg;
11911        int returnCode;
11912        String returnMsg;
11913        PackageRemovedInfo removedInfo;
11914
11915        public void setError(int code, String msg) {
11916            returnCode = code;
11917            returnMsg = msg;
11918            Slog.w(TAG, msg);
11919        }
11920
11921        public void setError(String msg, PackageParserException e) {
11922            returnCode = e.error;
11923            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11924            Slog.w(TAG, msg, e);
11925        }
11926
11927        public void setError(String msg, PackageManagerException e) {
11928            returnCode = e.error;
11929            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11930            Slog.w(TAG, msg, e);
11931        }
11932
11933        // In some error cases we want to convey more info back to the observer
11934        String origPackage;
11935        String origPermission;
11936    }
11937
11938    /*
11939     * Install a non-existing package.
11940     */
11941    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11942            UserHandle user, String installerPackageName, String volumeUuid,
11943            PackageInstalledInfo res) {
11944        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11945
11946        // Remember this for later, in case we need to rollback this install
11947        String pkgName = pkg.packageName;
11948
11949        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11950        // TODO: b/23350563
11951        final boolean dataDirExists = Environment
11952                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11953
11954        synchronized(mPackages) {
11955            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11956                // A package with the same name is already installed, though
11957                // it has been renamed to an older name.  The package we
11958                // are trying to install should be installed as an update to
11959                // the existing one, but that has not been requested, so bail.
11960                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11961                        + " without first uninstalling package running as "
11962                        + mSettings.mRenamedPackages.get(pkgName));
11963                return;
11964            }
11965            if (mPackages.containsKey(pkgName)) {
11966                // Don't allow installation over an existing package with the same name.
11967                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11968                        + " without first uninstalling.");
11969                return;
11970            }
11971        }
11972
11973        try {
11974            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11975                    System.currentTimeMillis(), user);
11976
11977            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11978            // delete the partially installed application. the data directory will have to be
11979            // restored if it was already existing
11980            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11981                // remove package from internal structures.  Note that we want deletePackageX to
11982                // delete the package data and cache directories that it created in
11983                // scanPackageLocked, unless those directories existed before we even tried to
11984                // install.
11985                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11986                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11987                                res.removedInfo, true);
11988            }
11989
11990        } catch (PackageManagerException e) {
11991            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11992        }
11993
11994        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11995    }
11996
11997    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11998        // Can't rotate keys during boot or if sharedUser.
11999        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12000                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12001            return false;
12002        }
12003        // app is using upgradeKeySets; make sure all are valid
12004        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12005        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12006        for (int i = 0; i < upgradeKeySets.length; i++) {
12007            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12008                Slog.wtf(TAG, "Package "
12009                         + (oldPs.name != null ? oldPs.name : "<null>")
12010                         + " contains upgrade-key-set reference to unknown key-set: "
12011                         + upgradeKeySets[i]
12012                         + " reverting to signatures check.");
12013                return false;
12014            }
12015        }
12016        return true;
12017    }
12018
12019    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12020        // Upgrade keysets are being used.  Determine if new package has a superset of the
12021        // required keys.
12022        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12023        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12024        for (int i = 0; i < upgradeKeySets.length; i++) {
12025            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12026            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12027                return true;
12028            }
12029        }
12030        return false;
12031    }
12032
12033    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12034            UserHandle user, String installerPackageName, String volumeUuid,
12035            PackageInstalledInfo res) {
12036        final PackageParser.Package oldPackage;
12037        final String pkgName = pkg.packageName;
12038        final int[] allUsers;
12039        final boolean[] perUserInstalled;
12040
12041        // First find the old package info and check signatures
12042        synchronized(mPackages) {
12043            oldPackage = mPackages.get(pkgName);
12044            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12045            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12046            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12047                if(!checkUpgradeKeySetLP(ps, pkg)) {
12048                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12049                            "New package not signed by keys specified by upgrade-keysets: "
12050                            + pkgName);
12051                    return;
12052                }
12053            } else {
12054                // default to original signature matching
12055                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12056                    != PackageManager.SIGNATURE_MATCH) {
12057                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12058                            "New package has a different signature: " + pkgName);
12059                    return;
12060                }
12061            }
12062
12063            // In case of rollback, remember per-user/profile install state
12064            allUsers = sUserManager.getUserIds();
12065            perUserInstalled = new boolean[allUsers.length];
12066            for (int i = 0; i < allUsers.length; i++) {
12067                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12068            }
12069        }
12070
12071        boolean sysPkg = (isSystemApp(oldPackage));
12072        if (sysPkg) {
12073            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12074                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12075        } else {
12076            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12077                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12078        }
12079    }
12080
12081    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12082            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12083            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12084            String volumeUuid, PackageInstalledInfo res) {
12085        String pkgName = deletedPackage.packageName;
12086        boolean deletedPkg = true;
12087        boolean updatedSettings = false;
12088
12089        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12090                + deletedPackage);
12091        long origUpdateTime;
12092        if (pkg.mExtras != null) {
12093            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12094        } else {
12095            origUpdateTime = 0;
12096        }
12097
12098        // First delete the existing package while retaining the data directory
12099        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12100                res.removedInfo, true)) {
12101            // If the existing package wasn't successfully deleted
12102            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12103            deletedPkg = false;
12104        } else {
12105            // Successfully deleted the old package; proceed with replace.
12106
12107            // If deleted package lived in a container, give users a chance to
12108            // relinquish resources before killing.
12109            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12110                if (DEBUG_INSTALL) {
12111                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12112                }
12113                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12114                final ArrayList<String> pkgList = new ArrayList<String>(1);
12115                pkgList.add(deletedPackage.applicationInfo.packageName);
12116                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12117            }
12118
12119            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12120            try {
12121                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12122                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12123                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12124                        perUserInstalled, res, user);
12125                updatedSettings = true;
12126            } catch (PackageManagerException e) {
12127                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12128            }
12129        }
12130
12131        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12132            // remove package from internal structures.  Note that we want deletePackageX to
12133            // delete the package data and cache directories that it created in
12134            // scanPackageLocked, unless those directories existed before we even tried to
12135            // install.
12136            if(updatedSettings) {
12137                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12138                deletePackageLI(
12139                        pkgName, null, true, allUsers, perUserInstalled,
12140                        PackageManager.DELETE_KEEP_DATA,
12141                                res.removedInfo, true);
12142            }
12143            // Since we failed to install the new package we need to restore the old
12144            // package that we deleted.
12145            if (deletedPkg) {
12146                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12147                File restoreFile = new File(deletedPackage.codePath);
12148                // Parse old package
12149                boolean oldExternal = isExternal(deletedPackage);
12150                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12151                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12152                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12153                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12154                try {
12155                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
12156                } catch (PackageManagerException e) {
12157                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12158                            + e.getMessage());
12159                    return;
12160                }
12161                // Restore of old package succeeded. Update permissions.
12162                // writer
12163                synchronized (mPackages) {
12164                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12165                            UPDATE_PERMISSIONS_ALL);
12166                    // can downgrade to reader
12167                    mSettings.writeLPr();
12168                }
12169                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12170            }
12171        }
12172    }
12173
12174    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12175            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12176            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12177            String volumeUuid, PackageInstalledInfo res) {
12178        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12179                + ", old=" + deletedPackage);
12180        boolean disabledSystem = false;
12181        boolean updatedSettings = false;
12182        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12183        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12184                != 0) {
12185            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12186        }
12187        String packageName = deletedPackage.packageName;
12188        if (packageName == null) {
12189            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12190                    "Attempt to delete null packageName.");
12191            return;
12192        }
12193        PackageParser.Package oldPkg;
12194        PackageSetting oldPkgSetting;
12195        // reader
12196        synchronized (mPackages) {
12197            oldPkg = mPackages.get(packageName);
12198            oldPkgSetting = mSettings.mPackages.get(packageName);
12199            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12200                    (oldPkgSetting == null)) {
12201                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12202                        "Couldn't find package:" + packageName + " information");
12203                return;
12204            }
12205        }
12206
12207        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12208
12209        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12210        res.removedInfo.removedPackage = packageName;
12211        // Remove existing system package
12212        removePackageLI(oldPkgSetting, true);
12213        // writer
12214        synchronized (mPackages) {
12215            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12216            if (!disabledSystem && deletedPackage != null) {
12217                // We didn't need to disable the .apk as a current system package,
12218                // which means we are replacing another update that is already
12219                // installed.  We need to make sure to delete the older one's .apk.
12220                res.removedInfo.args = createInstallArgsForExisting(0,
12221                        deletedPackage.applicationInfo.getCodePath(),
12222                        deletedPackage.applicationInfo.getResourcePath(),
12223                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12224            } else {
12225                res.removedInfo.args = null;
12226            }
12227        }
12228
12229        // Successfully disabled the old package. Now proceed with re-installation
12230        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12231
12232        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12233        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12234
12235        PackageParser.Package newPackage = null;
12236        try {
12237            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12238            if (newPackage.mExtras != null) {
12239                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12240                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12241                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12242
12243                // is the update attempting to change shared user? that isn't going to work...
12244                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12245                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12246                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12247                            + " to " + newPkgSetting.sharedUser);
12248                    updatedSettings = true;
12249                }
12250            }
12251
12252            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12253                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12254                        perUserInstalled, res, user);
12255                updatedSettings = true;
12256            }
12257
12258        } catch (PackageManagerException e) {
12259            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12260        }
12261
12262        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12263            // Re installation failed. Restore old information
12264            // Remove new pkg information
12265            if (newPackage != null) {
12266                removeInstalledPackageLI(newPackage, true);
12267            }
12268            // Add back the old system package
12269            try {
12270                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12271            } catch (PackageManagerException e) {
12272                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12273            }
12274            // Restore the old system information in Settings
12275            synchronized (mPackages) {
12276                if (disabledSystem) {
12277                    mSettings.enableSystemPackageLPw(packageName);
12278                }
12279                if (updatedSettings) {
12280                    mSettings.setInstallerPackageName(packageName,
12281                            oldPkgSetting.installerPackageName);
12282                }
12283                mSettings.writeLPr();
12284            }
12285        }
12286    }
12287
12288    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12289            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12290            UserHandle user) {
12291        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12292
12293        String pkgName = newPackage.packageName;
12294        synchronized (mPackages) {
12295            //write settings. the installStatus will be incomplete at this stage.
12296            //note that the new package setting would have already been
12297            //added to mPackages. It hasn't been persisted yet.
12298            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12299            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12300            mSettings.writeLPr();
12301            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12302        }
12303
12304        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12305        synchronized (mPackages) {
12306            updatePermissionsLPw(newPackage.packageName, newPackage,
12307                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12308                            ? UPDATE_PERMISSIONS_ALL : 0));
12309            // For system-bundled packages, we assume that installing an upgraded version
12310            // of the package implies that the user actually wants to run that new code,
12311            // so we enable the package.
12312            PackageSetting ps = mSettings.mPackages.get(pkgName);
12313            if (ps != null) {
12314                if (isSystemApp(newPackage)) {
12315                    // NB: implicit assumption that system package upgrades apply to all users
12316                    if (DEBUG_INSTALL) {
12317                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12318                    }
12319                    if (res.origUsers != null) {
12320                        for (int userHandle : res.origUsers) {
12321                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12322                                    userHandle, installerPackageName);
12323                        }
12324                    }
12325                    // Also convey the prior install/uninstall state
12326                    if (allUsers != null && perUserInstalled != null) {
12327                        for (int i = 0; i < allUsers.length; i++) {
12328                            if (DEBUG_INSTALL) {
12329                                Slog.d(TAG, "    user " + allUsers[i]
12330                                        + " => " + perUserInstalled[i]);
12331                            }
12332                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12333                        }
12334                        // these install state changes will be persisted in the
12335                        // upcoming call to mSettings.writeLPr().
12336                    }
12337                }
12338                // It's implied that when a user requests installation, they want the app to be
12339                // installed and enabled.
12340                int userId = user.getIdentifier();
12341                if (userId != UserHandle.USER_ALL) {
12342                    ps.setInstalled(true, userId);
12343                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12344                }
12345            }
12346            res.name = pkgName;
12347            res.uid = newPackage.applicationInfo.uid;
12348            res.pkg = newPackage;
12349            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12350            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12351            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12352            //to update install status
12353            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12354            mSettings.writeLPr();
12355            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12356        }
12357
12358        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12359    }
12360
12361    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12362        try {
12363            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12364            installPackageLI(args, res);
12365        } finally {
12366            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12367        }
12368    }
12369
12370    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12371        final int installFlags = args.installFlags;
12372        final String installerPackageName = args.installerPackageName;
12373        final String volumeUuid = args.volumeUuid;
12374        final File tmpPackageFile = new File(args.getCodePath());
12375        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12376        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12377                || (args.volumeUuid != null));
12378        boolean replace = false;
12379        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12380        if (args.move != null) {
12381            // moving a complete application; perfom an initial scan on the new install location
12382            scanFlags |= SCAN_INITIAL;
12383        }
12384        // Result object to be returned
12385        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12386
12387        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12388
12389        // Retrieve PackageSettings and parse package
12390        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12391                | PackageParser.PARSE_ENFORCE_CODE
12392                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12393                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12394        PackageParser pp = new PackageParser();
12395        pp.setSeparateProcesses(mSeparateProcesses);
12396        pp.setDisplayMetrics(mMetrics);
12397
12398        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12399        final PackageParser.Package pkg;
12400        try {
12401            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12402        } catch (PackageParserException e) {
12403            res.setError("Failed parse during installPackageLI", e);
12404            return;
12405        } finally {
12406            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12407        }
12408
12409        // Mark that we have an install time CPU ABI override.
12410        pkg.cpuAbiOverride = args.abiOverride;
12411
12412        String pkgName = res.name = pkg.packageName;
12413        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12414            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12415                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12416                return;
12417            }
12418        }
12419
12420        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12421        try {
12422            pp.collectCertificates(pkg, parseFlags);
12423            pp.collectManifestDigest(pkg);
12424        } catch (PackageParserException e) {
12425            res.setError("Failed collect during installPackageLI", e);
12426            return;
12427        } finally {
12428            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12429        }
12430
12431        /* If the installer passed in a manifest digest, compare it now. */
12432        if (args.manifestDigest != null) {
12433            if (DEBUG_INSTALL) {
12434                final String parsedManifest = pkg.manifestDigest == null ? "null"
12435                        : pkg.manifestDigest.toString();
12436                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12437                        + parsedManifest);
12438            }
12439
12440            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12441                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12442                return;
12443            }
12444        } else if (DEBUG_INSTALL) {
12445            final String parsedManifest = pkg.manifestDigest == null
12446                    ? "null" : pkg.manifestDigest.toString();
12447            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12448        }
12449
12450        // Get rid of all references to package scan path via parser.
12451        pp = null;
12452        String oldCodePath = null;
12453        boolean systemApp = false;
12454        synchronized (mPackages) {
12455            // Check if installing already existing package
12456            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12457                String oldName = mSettings.mRenamedPackages.get(pkgName);
12458                if (pkg.mOriginalPackages != null
12459                        && pkg.mOriginalPackages.contains(oldName)
12460                        && mPackages.containsKey(oldName)) {
12461                    // This package is derived from an original package,
12462                    // and this device has been updating from that original
12463                    // name.  We must continue using the original name, so
12464                    // rename the new package here.
12465                    pkg.setPackageName(oldName);
12466                    pkgName = pkg.packageName;
12467                    replace = true;
12468                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12469                            + oldName + " pkgName=" + pkgName);
12470                } else if (mPackages.containsKey(pkgName)) {
12471                    // This package, under its official name, already exists
12472                    // on the device; we should replace it.
12473                    replace = true;
12474                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12475                }
12476
12477                // Prevent apps opting out from runtime permissions
12478                if (replace) {
12479                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12480                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12481                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12482                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12483                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12484                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12485                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12486                                        + " doesn't support runtime permissions but the old"
12487                                        + " target SDK " + oldTargetSdk + " does.");
12488                        return;
12489                    }
12490                }
12491            }
12492
12493            PackageSetting ps = mSettings.mPackages.get(pkgName);
12494            if (ps != null) {
12495                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12496
12497                // Quick sanity check that we're signed correctly if updating;
12498                // we'll check this again later when scanning, but we want to
12499                // bail early here before tripping over redefined permissions.
12500                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12501                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12502                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12503                                + pkg.packageName + " upgrade keys do not match the "
12504                                + "previously installed version");
12505                        return;
12506                    }
12507                } else {
12508                    try {
12509                        verifySignaturesLP(ps, pkg);
12510                    } catch (PackageManagerException e) {
12511                        res.setError(e.error, e.getMessage());
12512                        return;
12513                    }
12514                }
12515
12516                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12517                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12518                    systemApp = (ps.pkg.applicationInfo.flags &
12519                            ApplicationInfo.FLAG_SYSTEM) != 0;
12520                }
12521                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12522            }
12523
12524            // Check whether the newly-scanned package wants to define an already-defined perm
12525            int N = pkg.permissions.size();
12526            for (int i = N-1; i >= 0; i--) {
12527                PackageParser.Permission perm = pkg.permissions.get(i);
12528                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12529                if (bp != null) {
12530                    // If the defining package is signed with our cert, it's okay.  This
12531                    // also includes the "updating the same package" case, of course.
12532                    // "updating same package" could also involve key-rotation.
12533                    final boolean sigsOk;
12534                    if (bp.sourcePackage.equals(pkg.packageName)
12535                            && (bp.packageSetting instanceof PackageSetting)
12536                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12537                                    scanFlags))) {
12538                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12539                    } else {
12540                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12541                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12542                    }
12543                    if (!sigsOk) {
12544                        // If the owning package is the system itself, we log but allow
12545                        // install to proceed; we fail the install on all other permission
12546                        // redefinitions.
12547                        if (!bp.sourcePackage.equals("android")) {
12548                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12549                                    + pkg.packageName + " attempting to redeclare permission "
12550                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12551                            res.origPermission = perm.info.name;
12552                            res.origPackage = bp.sourcePackage;
12553                            return;
12554                        } else {
12555                            Slog.w(TAG, "Package " + pkg.packageName
12556                                    + " attempting to redeclare system permission "
12557                                    + perm.info.name + "; ignoring new declaration");
12558                            pkg.permissions.remove(i);
12559                        }
12560                    }
12561                }
12562            }
12563
12564        }
12565
12566        if (systemApp && onExternal) {
12567            // Disable updates to system apps on sdcard
12568            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12569                    "Cannot install updates to system apps on sdcard");
12570            return;
12571        }
12572
12573        if (args.move != null) {
12574            // We did an in-place move, so dex is ready to roll
12575            scanFlags |= SCAN_NO_DEX;
12576            scanFlags |= SCAN_MOVE;
12577
12578            synchronized (mPackages) {
12579                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12580                if (ps == null) {
12581                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12582                            "Missing settings for moved package " + pkgName);
12583                }
12584
12585                // We moved the entire application as-is, so bring over the
12586                // previously derived ABI information.
12587                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12588                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12589            }
12590
12591        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12592            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12593            scanFlags |= SCAN_NO_DEX;
12594
12595            try {
12596                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12597                        true /* extract libs */);
12598            } catch (PackageManagerException pme) {
12599                Slog.e(TAG, "Error deriving application ABI", pme);
12600                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12601                return;
12602            }
12603
12604            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12605            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
12606
12607            int result = mPackageDexOptimizer
12608                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12609                            false /* defer */, false /* inclDependencies */,
12610                            true /* boot complete */);
12611
12612            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12613            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12614                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12615                return;
12616            }
12617        }
12618
12619        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12620            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12621            return;
12622        }
12623
12624        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12625
12626        if (replace) {
12627            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12628                    installerPackageName, volumeUuid, res);
12629        } else {
12630            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12631                    args.user, installerPackageName, volumeUuid, res);
12632        }
12633        synchronized (mPackages) {
12634            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12635            if (ps != null) {
12636                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12637            }
12638        }
12639    }
12640
12641    private void startIntentFilterVerifications(int userId, boolean replacing,
12642            PackageParser.Package pkg) {
12643        if (mIntentFilterVerifierComponent == null) {
12644            Slog.w(TAG, "No IntentFilter verification will not be done as "
12645                    + "there is no IntentFilterVerifier available!");
12646            return;
12647        }
12648
12649        final int verifierUid = getPackageUid(
12650                mIntentFilterVerifierComponent.getPackageName(),
12651                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12652
12653        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12654        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12655        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12656        mHandler.sendMessage(msg);
12657    }
12658
12659    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12660            PackageParser.Package pkg) {
12661        int size = pkg.activities.size();
12662        if (size == 0) {
12663            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12664                    "No activity, so no need to verify any IntentFilter!");
12665            return;
12666        }
12667
12668        final boolean hasDomainURLs = hasDomainURLs(pkg);
12669        if (!hasDomainURLs) {
12670            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12671                    "No domain URLs, so no need to verify any IntentFilter!");
12672            return;
12673        }
12674
12675        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12676                + " if any IntentFilter from the " + size
12677                + " Activities needs verification ...");
12678
12679        int count = 0;
12680        final String packageName = pkg.packageName;
12681
12682        synchronized (mPackages) {
12683            // If this is a new install and we see that we've already run verification for this
12684            // package, we have nothing to do: it means the state was restored from backup.
12685            if (!replacing) {
12686                IntentFilterVerificationInfo ivi =
12687                        mSettings.getIntentFilterVerificationLPr(packageName);
12688                if (ivi != null) {
12689                    if (DEBUG_DOMAIN_VERIFICATION) {
12690                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12691                                + ivi.getStatusString());
12692                    }
12693                    return;
12694                }
12695            }
12696
12697            // If any filters need to be verified, then all need to be.
12698            boolean needToVerify = false;
12699            for (PackageParser.Activity a : pkg.activities) {
12700                for (ActivityIntentInfo filter : a.intents) {
12701                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12702                        if (DEBUG_DOMAIN_VERIFICATION) {
12703                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12704                        }
12705                        needToVerify = true;
12706                        break;
12707                    }
12708                }
12709            }
12710
12711            if (needToVerify) {
12712                final int verificationId = mIntentFilterVerificationToken++;
12713                for (PackageParser.Activity a : pkg.activities) {
12714                    for (ActivityIntentInfo filter : a.intents) {
12715                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12716                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12717                                    "Verification needed for IntentFilter:" + filter.toString());
12718                            mIntentFilterVerifier.addOneIntentFilterVerification(
12719                                    verifierUid, userId, verificationId, filter, packageName);
12720                            count++;
12721                        }
12722                    }
12723                }
12724            }
12725        }
12726
12727        if (count > 0) {
12728            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12729                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12730                    +  " for userId:" + userId);
12731            mIntentFilterVerifier.startVerifications(userId);
12732        } else {
12733            if (DEBUG_DOMAIN_VERIFICATION) {
12734                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12735            }
12736        }
12737    }
12738
12739    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12740        final ComponentName cn  = filter.activity.getComponentName();
12741        final String packageName = cn.getPackageName();
12742
12743        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12744                packageName);
12745        if (ivi == null) {
12746            return true;
12747        }
12748        int status = ivi.getStatus();
12749        switch (status) {
12750            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12751            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12752                return true;
12753
12754            default:
12755                // Nothing to do
12756                return false;
12757        }
12758    }
12759
12760    private static boolean isMultiArch(PackageSetting ps) {
12761        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12762    }
12763
12764    private static boolean isMultiArch(ApplicationInfo info) {
12765        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12766    }
12767
12768    private static boolean isExternal(PackageParser.Package pkg) {
12769        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12770    }
12771
12772    private static boolean isExternal(PackageSetting ps) {
12773        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12774    }
12775
12776    private static boolean isExternal(ApplicationInfo info) {
12777        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12778    }
12779
12780    private static boolean isSystemApp(PackageParser.Package pkg) {
12781        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12782    }
12783
12784    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12785        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12786    }
12787
12788    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12789        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12790    }
12791
12792    private static boolean isSystemApp(PackageSetting ps) {
12793        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12794    }
12795
12796    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12797        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12798    }
12799
12800    private int packageFlagsToInstallFlags(PackageSetting ps) {
12801        int installFlags = 0;
12802        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12803            // This existing package was an external ASEC install when we have
12804            // the external flag without a UUID
12805            installFlags |= PackageManager.INSTALL_EXTERNAL;
12806        }
12807        if (ps.isForwardLocked()) {
12808            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12809        }
12810        return installFlags;
12811    }
12812
12813    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12814        if (isExternal(pkg)) {
12815            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12816                return mSettings.getExternalVersion();
12817            } else {
12818                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12819            }
12820        } else {
12821            return mSettings.getInternalVersion();
12822        }
12823    }
12824
12825    private void deleteTempPackageFiles() {
12826        final FilenameFilter filter = new FilenameFilter() {
12827            public boolean accept(File dir, String name) {
12828                return name.startsWith("vmdl") && name.endsWith(".tmp");
12829            }
12830        };
12831        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12832            file.delete();
12833        }
12834    }
12835
12836    @Override
12837    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12838            int flags) {
12839        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12840                flags);
12841    }
12842
12843    @Override
12844    public void deletePackage(final String packageName,
12845            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12846        mContext.enforceCallingOrSelfPermission(
12847                android.Manifest.permission.DELETE_PACKAGES, null);
12848        Preconditions.checkNotNull(packageName);
12849        Preconditions.checkNotNull(observer);
12850        final int uid = Binder.getCallingUid();
12851        if (UserHandle.getUserId(uid) != userId) {
12852            mContext.enforceCallingPermission(
12853                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12854                    "deletePackage for user " + userId);
12855        }
12856        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12857            try {
12858                observer.onPackageDeleted(packageName,
12859                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12860            } catch (RemoteException re) {
12861            }
12862            return;
12863        }
12864
12865        boolean uninstallBlocked = false;
12866        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12867            int[] users = sUserManager.getUserIds();
12868            for (int i = 0; i < users.length; ++i) {
12869                if (getBlockUninstallForUser(packageName, users[i])) {
12870                    uninstallBlocked = true;
12871                    break;
12872                }
12873            }
12874        } else {
12875            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12876        }
12877        if (uninstallBlocked) {
12878            try {
12879                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12880                        null);
12881            } catch (RemoteException re) {
12882            }
12883            return;
12884        }
12885
12886        if (DEBUG_REMOVE) {
12887            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12888        }
12889        // Queue up an async operation since the package deletion may take a little while.
12890        mHandler.post(new Runnable() {
12891            public void run() {
12892                mHandler.removeCallbacks(this);
12893                final int returnCode = deletePackageX(packageName, userId, flags);
12894                if (observer != null) {
12895                    try {
12896                        observer.onPackageDeleted(packageName, returnCode, null);
12897                    } catch (RemoteException e) {
12898                        Log.i(TAG, "Observer no longer exists.");
12899                    } //end catch
12900                } //end if
12901            } //end run
12902        });
12903    }
12904
12905    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12906        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12907                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12908        try {
12909            if (dpm != null) {
12910                if (dpm.isDeviceOwner(packageName)) {
12911                    return true;
12912                }
12913                int[] users;
12914                if (userId == UserHandle.USER_ALL) {
12915                    users = sUserManager.getUserIds();
12916                } else {
12917                    users = new int[]{userId};
12918                }
12919                for (int i = 0; i < users.length; ++i) {
12920                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12921                        return true;
12922                    }
12923                }
12924            }
12925        } catch (RemoteException e) {
12926        }
12927        return false;
12928    }
12929
12930    /**
12931     *  This method is an internal method that could be get invoked either
12932     *  to delete an installed package or to clean up a failed installation.
12933     *  After deleting an installed package, a broadcast is sent to notify any
12934     *  listeners that the package has been installed. For cleaning up a failed
12935     *  installation, the broadcast is not necessary since the package's
12936     *  installation wouldn't have sent the initial broadcast either
12937     *  The key steps in deleting a package are
12938     *  deleting the package information in internal structures like mPackages,
12939     *  deleting the packages base directories through installd
12940     *  updating mSettings to reflect current status
12941     *  persisting settings for later use
12942     *  sending a broadcast if necessary
12943     */
12944    private int deletePackageX(String packageName, int userId, int flags) {
12945        final PackageRemovedInfo info = new PackageRemovedInfo();
12946        final boolean res;
12947
12948        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12949                ? UserHandle.ALL : new UserHandle(userId);
12950
12951        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12952            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12953            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12954        }
12955
12956        boolean removedForAllUsers = false;
12957        boolean systemUpdate = false;
12958
12959        // for the uninstall-updates case and restricted profiles, remember the per-
12960        // userhandle installed state
12961        int[] allUsers;
12962        boolean[] perUserInstalled;
12963        synchronized (mPackages) {
12964            PackageSetting ps = mSettings.mPackages.get(packageName);
12965            allUsers = sUserManager.getUserIds();
12966            perUserInstalled = new boolean[allUsers.length];
12967            for (int i = 0; i < allUsers.length; i++) {
12968                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12969            }
12970        }
12971
12972        synchronized (mInstallLock) {
12973            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12974            res = deletePackageLI(packageName, removeForUser,
12975                    true, allUsers, perUserInstalled,
12976                    flags | REMOVE_CHATTY, info, true);
12977            systemUpdate = info.isRemovedPackageSystemUpdate;
12978            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12979                removedForAllUsers = true;
12980            }
12981            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12982                    + " removedForAllUsers=" + removedForAllUsers);
12983        }
12984
12985        if (res) {
12986            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12987
12988            // If the removed package was a system update, the old system package
12989            // was re-enabled; we need to broadcast this information
12990            if (systemUpdate) {
12991                Bundle extras = new Bundle(1);
12992                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12993                        ? info.removedAppId : info.uid);
12994                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12995
12996                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12997                        extras, null, null, null);
12998                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12999                        extras, null, null, null);
13000                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13001                        null, packageName, null, null);
13002            }
13003        }
13004        // Force a gc here.
13005        Runtime.getRuntime().gc();
13006        // Delete the resources here after sending the broadcast to let
13007        // other processes clean up before deleting resources.
13008        if (info.args != null) {
13009            synchronized (mInstallLock) {
13010                info.args.doPostDeleteLI(true);
13011            }
13012        }
13013
13014        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13015    }
13016
13017    class PackageRemovedInfo {
13018        String removedPackage;
13019        int uid = -1;
13020        int removedAppId = -1;
13021        int[] removedUsers = null;
13022        boolean isRemovedPackageSystemUpdate = false;
13023        // Clean up resources deleted packages.
13024        InstallArgs args = null;
13025
13026        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13027            Bundle extras = new Bundle(1);
13028            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13029            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13030            if (replacing) {
13031                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13032            }
13033            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13034            if (removedPackage != null) {
13035                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13036                        extras, null, null, removedUsers);
13037                if (fullRemove && !replacing) {
13038                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13039                            extras, null, null, removedUsers);
13040                }
13041            }
13042            if (removedAppId >= 0) {
13043                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13044                        removedUsers);
13045            }
13046        }
13047    }
13048
13049    /*
13050     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13051     * flag is not set, the data directory is removed as well.
13052     * make sure this flag is set for partially installed apps. If not its meaningless to
13053     * delete a partially installed application.
13054     */
13055    private void removePackageDataLI(PackageSetting ps,
13056            int[] allUserHandles, boolean[] perUserInstalled,
13057            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13058        String packageName = ps.name;
13059        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13060        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13061        // Retrieve object to delete permissions for shared user later on
13062        final PackageSetting deletedPs;
13063        // reader
13064        synchronized (mPackages) {
13065            deletedPs = mSettings.mPackages.get(packageName);
13066            if (outInfo != null) {
13067                outInfo.removedPackage = packageName;
13068                outInfo.removedUsers = deletedPs != null
13069                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13070                        : null;
13071            }
13072        }
13073        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13074            removeDataDirsLI(ps.volumeUuid, packageName);
13075            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13076        }
13077        // writer
13078        synchronized (mPackages) {
13079            if (deletedPs != null) {
13080                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13081                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13082                    clearDefaultBrowserIfNeeded(packageName);
13083                    if (outInfo != null) {
13084                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13085                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13086                    }
13087                    updatePermissionsLPw(deletedPs.name, null, 0);
13088                    if (deletedPs.sharedUser != null) {
13089                        // Remove permissions associated with package. Since runtime
13090                        // permissions are per user we have to kill the removed package
13091                        // or packages running under the shared user of the removed
13092                        // package if revoking the permissions requested only by the removed
13093                        // package is successful and this causes a change in gids.
13094                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13095                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13096                                    userId);
13097                            if (userIdToKill == UserHandle.USER_ALL
13098                                    || userIdToKill >= UserHandle.USER_OWNER) {
13099                                // If gids changed for this user, kill all affected packages.
13100                                mHandler.post(new Runnable() {
13101                                    @Override
13102                                    public void run() {
13103                                        // This has to happen with no lock held.
13104                                        killApplication(deletedPs.name, deletedPs.appId,
13105                                                KILL_APP_REASON_GIDS_CHANGED);
13106                                    }
13107                                });
13108                                break;
13109                            }
13110                        }
13111                    }
13112                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13113                }
13114                // make sure to preserve per-user disabled state if this removal was just
13115                // a downgrade of a system app to the factory package
13116                if (allUserHandles != null && perUserInstalled != null) {
13117                    if (DEBUG_REMOVE) {
13118                        Slog.d(TAG, "Propagating install state across downgrade");
13119                    }
13120                    for (int i = 0; i < allUserHandles.length; i++) {
13121                        if (DEBUG_REMOVE) {
13122                            Slog.d(TAG, "    user " + allUserHandles[i]
13123                                    + " => " + perUserInstalled[i]);
13124                        }
13125                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13126                    }
13127                }
13128            }
13129            // can downgrade to reader
13130            if (writeSettings) {
13131                // Save settings now
13132                mSettings.writeLPr();
13133            }
13134        }
13135        if (outInfo != null) {
13136            // A user ID was deleted here. Go through all users and remove it
13137            // from KeyStore.
13138            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13139        }
13140    }
13141
13142    static boolean locationIsPrivileged(File path) {
13143        try {
13144            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13145                    .getCanonicalPath();
13146            return path.getCanonicalPath().startsWith(privilegedAppDir);
13147        } catch (IOException e) {
13148            Slog.e(TAG, "Unable to access code path " + path);
13149        }
13150        return false;
13151    }
13152
13153    /*
13154     * Tries to delete system package.
13155     */
13156    private boolean deleteSystemPackageLI(PackageSetting newPs,
13157            int[] allUserHandles, boolean[] perUserInstalled,
13158            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13159        final boolean applyUserRestrictions
13160                = (allUserHandles != null) && (perUserInstalled != null);
13161        PackageSetting disabledPs = null;
13162        // Confirm if the system package has been updated
13163        // An updated system app can be deleted. This will also have to restore
13164        // the system pkg from system partition
13165        // reader
13166        synchronized (mPackages) {
13167            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13168        }
13169        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13170                + " disabledPs=" + disabledPs);
13171        if (disabledPs == null) {
13172            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13173            return false;
13174        } else if (DEBUG_REMOVE) {
13175            Slog.d(TAG, "Deleting system pkg from data partition");
13176        }
13177        if (DEBUG_REMOVE) {
13178            if (applyUserRestrictions) {
13179                Slog.d(TAG, "Remembering install states:");
13180                for (int i = 0; i < allUserHandles.length; i++) {
13181                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13182                }
13183            }
13184        }
13185        // Delete the updated package
13186        outInfo.isRemovedPackageSystemUpdate = true;
13187        if (disabledPs.versionCode < newPs.versionCode) {
13188            // Delete data for downgrades
13189            flags &= ~PackageManager.DELETE_KEEP_DATA;
13190        } else {
13191            // Preserve data by setting flag
13192            flags |= PackageManager.DELETE_KEEP_DATA;
13193        }
13194        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13195                allUserHandles, perUserInstalled, outInfo, writeSettings);
13196        if (!ret) {
13197            return false;
13198        }
13199        // writer
13200        synchronized (mPackages) {
13201            // Reinstate the old system package
13202            mSettings.enableSystemPackageLPw(newPs.name);
13203            // Remove any native libraries from the upgraded package.
13204            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13205        }
13206        // Install the system package
13207        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13208        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13209        if (locationIsPrivileged(disabledPs.codePath)) {
13210            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13211        }
13212
13213        final PackageParser.Package newPkg;
13214        try {
13215            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13216        } catch (PackageManagerException e) {
13217            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13218            return false;
13219        }
13220
13221        // writer
13222        synchronized (mPackages) {
13223            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13224
13225            // Propagate the permissions state as we do not want to drop on the floor
13226            // runtime permissions. The update permissions method below will take
13227            // care of removing obsolete permissions and grant install permissions.
13228            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13229            updatePermissionsLPw(newPkg.packageName, newPkg,
13230                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13231
13232            if (applyUserRestrictions) {
13233                if (DEBUG_REMOVE) {
13234                    Slog.d(TAG, "Propagating install state across reinstall");
13235                }
13236                for (int i = 0; i < allUserHandles.length; i++) {
13237                    if (DEBUG_REMOVE) {
13238                        Slog.d(TAG, "    user " + allUserHandles[i]
13239                                + " => " + perUserInstalled[i]);
13240                    }
13241                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13242
13243                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13244                }
13245                // Regardless of writeSettings we need to ensure that this restriction
13246                // state propagation is persisted
13247                mSettings.writeAllUsersPackageRestrictionsLPr();
13248            }
13249            // can downgrade to reader here
13250            if (writeSettings) {
13251                mSettings.writeLPr();
13252            }
13253        }
13254        return true;
13255    }
13256
13257    private boolean deleteInstalledPackageLI(PackageSetting ps,
13258            boolean deleteCodeAndResources, int flags,
13259            int[] allUserHandles, boolean[] perUserInstalled,
13260            PackageRemovedInfo outInfo, boolean writeSettings) {
13261        if (outInfo != null) {
13262            outInfo.uid = ps.appId;
13263        }
13264
13265        // Delete package data from internal structures and also remove data if flag is set
13266        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13267
13268        // Delete application code and resources
13269        if (deleteCodeAndResources && (outInfo != null)) {
13270            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13271                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13272            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13273        }
13274        return true;
13275    }
13276
13277    @Override
13278    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13279            int userId) {
13280        mContext.enforceCallingOrSelfPermission(
13281                android.Manifest.permission.DELETE_PACKAGES, null);
13282        synchronized (mPackages) {
13283            PackageSetting ps = mSettings.mPackages.get(packageName);
13284            if (ps == null) {
13285                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13286                return false;
13287            }
13288            if (!ps.getInstalled(userId)) {
13289                // Can't block uninstall for an app that is not installed or enabled.
13290                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13291                return false;
13292            }
13293            ps.setBlockUninstall(blockUninstall, userId);
13294            mSettings.writePackageRestrictionsLPr(userId);
13295        }
13296        return true;
13297    }
13298
13299    @Override
13300    public boolean getBlockUninstallForUser(String packageName, int userId) {
13301        synchronized (mPackages) {
13302            PackageSetting ps = mSettings.mPackages.get(packageName);
13303            if (ps == null) {
13304                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13305                return false;
13306            }
13307            return ps.getBlockUninstall(userId);
13308        }
13309    }
13310
13311    /*
13312     * This method handles package deletion in general
13313     */
13314    private boolean deletePackageLI(String packageName, UserHandle user,
13315            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13316            int flags, PackageRemovedInfo outInfo,
13317            boolean writeSettings) {
13318        if (packageName == null) {
13319            Slog.w(TAG, "Attempt to delete null packageName.");
13320            return false;
13321        }
13322        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13323        PackageSetting ps;
13324        boolean dataOnly = false;
13325        int removeUser = -1;
13326        int appId = -1;
13327        synchronized (mPackages) {
13328            ps = mSettings.mPackages.get(packageName);
13329            if (ps == null) {
13330                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13331                return false;
13332            }
13333            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13334                    && user.getIdentifier() != UserHandle.USER_ALL) {
13335                // The caller is asking that the package only be deleted for a single
13336                // user.  To do this, we just mark its uninstalled state and delete
13337                // its data.  If this is a system app, we only allow this to happen if
13338                // they have set the special DELETE_SYSTEM_APP which requests different
13339                // semantics than normal for uninstalling system apps.
13340                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13341                final int userId = user.getIdentifier();
13342                ps.setUserState(userId,
13343                        COMPONENT_ENABLED_STATE_DEFAULT,
13344                        false, //installed
13345                        true,  //stopped
13346                        true,  //notLaunched
13347                        false, //hidden
13348                        null, null, null,
13349                        false, // blockUninstall
13350                        ps.readUserState(userId).domainVerificationStatus, 0);
13351                if (!isSystemApp(ps)) {
13352                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13353                        // Other user still have this package installed, so all
13354                        // we need to do is clear this user's data and save that
13355                        // it is uninstalled.
13356                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13357                        removeUser = user.getIdentifier();
13358                        appId = ps.appId;
13359                        scheduleWritePackageRestrictionsLocked(removeUser);
13360                    } else {
13361                        // We need to set it back to 'installed' so the uninstall
13362                        // broadcasts will be sent correctly.
13363                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13364                        ps.setInstalled(true, user.getIdentifier());
13365                    }
13366                } else {
13367                    // This is a system app, so we assume that the
13368                    // other users still have this package installed, so all
13369                    // we need to do is clear this user's data and save that
13370                    // it is uninstalled.
13371                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13372                    removeUser = user.getIdentifier();
13373                    appId = ps.appId;
13374                    scheduleWritePackageRestrictionsLocked(removeUser);
13375                }
13376            }
13377        }
13378
13379        if (removeUser >= 0) {
13380            // From above, we determined that we are deleting this only
13381            // for a single user.  Continue the work here.
13382            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13383            if (outInfo != null) {
13384                outInfo.removedPackage = packageName;
13385                outInfo.removedAppId = appId;
13386                outInfo.removedUsers = new int[] {removeUser};
13387            }
13388            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13389            removeKeystoreDataIfNeeded(removeUser, appId);
13390            schedulePackageCleaning(packageName, removeUser, false);
13391            synchronized (mPackages) {
13392                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13393                    scheduleWritePackageRestrictionsLocked(removeUser);
13394                }
13395                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13396            }
13397            return true;
13398        }
13399
13400        if (dataOnly) {
13401            // Delete application data first
13402            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13403            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13404            return true;
13405        }
13406
13407        boolean ret = false;
13408        if (isSystemApp(ps)) {
13409            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13410            // When an updated system application is deleted we delete the existing resources as well and
13411            // fall back to existing code in system partition
13412            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13413                    flags, outInfo, writeSettings);
13414        } else {
13415            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13416            // Kill application pre-emptively especially for apps on sd.
13417            killApplication(packageName, ps.appId, "uninstall pkg");
13418            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13419                    allUserHandles, perUserInstalled,
13420                    outInfo, writeSettings);
13421        }
13422
13423        return ret;
13424    }
13425
13426    private final class ClearStorageConnection implements ServiceConnection {
13427        IMediaContainerService mContainerService;
13428
13429        @Override
13430        public void onServiceConnected(ComponentName name, IBinder service) {
13431            synchronized (this) {
13432                mContainerService = IMediaContainerService.Stub.asInterface(service);
13433                notifyAll();
13434            }
13435        }
13436
13437        @Override
13438        public void onServiceDisconnected(ComponentName name) {
13439        }
13440    }
13441
13442    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13443        final boolean mounted;
13444        if (Environment.isExternalStorageEmulated()) {
13445            mounted = true;
13446        } else {
13447            final String status = Environment.getExternalStorageState();
13448
13449            mounted = status.equals(Environment.MEDIA_MOUNTED)
13450                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13451        }
13452
13453        if (!mounted) {
13454            return;
13455        }
13456
13457        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13458        int[] users;
13459        if (userId == UserHandle.USER_ALL) {
13460            users = sUserManager.getUserIds();
13461        } else {
13462            users = new int[] { userId };
13463        }
13464        final ClearStorageConnection conn = new ClearStorageConnection();
13465        if (mContext.bindServiceAsUser(
13466                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13467            try {
13468                for (int curUser : users) {
13469                    long timeout = SystemClock.uptimeMillis() + 5000;
13470                    synchronized (conn) {
13471                        long now = SystemClock.uptimeMillis();
13472                        while (conn.mContainerService == null && now < timeout) {
13473                            try {
13474                                conn.wait(timeout - now);
13475                            } catch (InterruptedException e) {
13476                            }
13477                        }
13478                    }
13479                    if (conn.mContainerService == null) {
13480                        return;
13481                    }
13482
13483                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13484                    clearDirectory(conn.mContainerService,
13485                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13486                    if (allData) {
13487                        clearDirectory(conn.mContainerService,
13488                                userEnv.buildExternalStorageAppDataDirs(packageName));
13489                        clearDirectory(conn.mContainerService,
13490                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13491                    }
13492                }
13493            } finally {
13494                mContext.unbindService(conn);
13495            }
13496        }
13497    }
13498
13499    @Override
13500    public void clearApplicationUserData(final String packageName,
13501            final IPackageDataObserver observer, final int userId) {
13502        mContext.enforceCallingOrSelfPermission(
13503                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13504        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13505        // Queue up an async operation since the package deletion may take a little while.
13506        mHandler.post(new Runnable() {
13507            public void run() {
13508                mHandler.removeCallbacks(this);
13509                final boolean succeeded;
13510                synchronized (mInstallLock) {
13511                    succeeded = clearApplicationUserDataLI(packageName, userId);
13512                }
13513                clearExternalStorageDataSync(packageName, userId, true);
13514                if (succeeded) {
13515                    // invoke DeviceStorageMonitor's update method to clear any notifications
13516                    DeviceStorageMonitorInternal
13517                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13518                    if (dsm != null) {
13519                        dsm.checkMemory();
13520                    }
13521                }
13522                if(observer != null) {
13523                    try {
13524                        observer.onRemoveCompleted(packageName, succeeded);
13525                    } catch (RemoteException e) {
13526                        Log.i(TAG, "Observer no longer exists.");
13527                    }
13528                } //end if observer
13529            } //end run
13530        });
13531    }
13532
13533    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13534        if (packageName == null) {
13535            Slog.w(TAG, "Attempt to delete null packageName.");
13536            return false;
13537        }
13538
13539        // Try finding details about the requested package
13540        PackageParser.Package pkg;
13541        synchronized (mPackages) {
13542            pkg = mPackages.get(packageName);
13543            if (pkg == null) {
13544                final PackageSetting ps = mSettings.mPackages.get(packageName);
13545                if (ps != null) {
13546                    pkg = ps.pkg;
13547                }
13548            }
13549
13550            if (pkg == null) {
13551                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13552                return false;
13553            }
13554
13555            PackageSetting ps = (PackageSetting) pkg.mExtras;
13556            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13557        }
13558
13559        // Always delete data directories for package, even if we found no other
13560        // record of app. This helps users recover from UID mismatches without
13561        // resorting to a full data wipe.
13562        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13563        if (retCode < 0) {
13564            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13565            return false;
13566        }
13567
13568        final int appId = pkg.applicationInfo.uid;
13569        removeKeystoreDataIfNeeded(userId, appId);
13570
13571        // Create a native library symlink only if we have native libraries
13572        // and if the native libraries are 32 bit libraries. We do not provide
13573        // this symlink for 64 bit libraries.
13574        if (pkg.applicationInfo.primaryCpuAbi != null &&
13575                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13576            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13577            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13578                    nativeLibPath, userId) < 0) {
13579                Slog.w(TAG, "Failed linking native library dir");
13580                return false;
13581            }
13582        }
13583
13584        return true;
13585    }
13586
13587    /**
13588     * Reverts user permission state changes (permissions and flags) in
13589     * all packages for a given user.
13590     *
13591     * @param userId The device user for which to do a reset.
13592     */
13593    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13594        final int packageCount = mPackages.size();
13595        for (int i = 0; i < packageCount; i++) {
13596            PackageParser.Package pkg = mPackages.valueAt(i);
13597            PackageSetting ps = (PackageSetting) pkg.mExtras;
13598            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13599        }
13600    }
13601
13602    /**
13603     * Reverts user permission state changes (permissions and flags).
13604     *
13605     * @param ps The package for which to reset.
13606     * @param userId The device user for which to do a reset.
13607     */
13608    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13609            final PackageSetting ps, final int userId) {
13610        if (ps.pkg == null) {
13611            return;
13612        }
13613
13614        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13615                | FLAG_PERMISSION_USER_FIXED
13616                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13617
13618        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13619                | FLAG_PERMISSION_POLICY_FIXED;
13620
13621        boolean writeInstallPermissions = false;
13622        boolean writeRuntimePermissions = false;
13623
13624        final int permissionCount = ps.pkg.requestedPermissions.size();
13625        for (int i = 0; i < permissionCount; i++) {
13626            String permission = ps.pkg.requestedPermissions.get(i);
13627
13628            BasePermission bp = mSettings.mPermissions.get(permission);
13629            if (bp == null) {
13630                continue;
13631            }
13632
13633            // If shared user we just reset the state to which only this app contributed.
13634            if (ps.sharedUser != null) {
13635                boolean used = false;
13636                final int packageCount = ps.sharedUser.packages.size();
13637                for (int j = 0; j < packageCount; j++) {
13638                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13639                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13640                            && pkg.pkg.requestedPermissions.contains(permission)) {
13641                        used = true;
13642                        break;
13643                    }
13644                }
13645                if (used) {
13646                    continue;
13647                }
13648            }
13649
13650            PermissionsState permissionsState = ps.getPermissionsState();
13651
13652            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13653
13654            // Always clear the user settable flags.
13655            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13656                    bp.name) != null;
13657            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13658                if (hasInstallState) {
13659                    writeInstallPermissions = true;
13660                } else {
13661                    writeRuntimePermissions = true;
13662                }
13663            }
13664
13665            // Below is only runtime permission handling.
13666            if (!bp.isRuntime()) {
13667                continue;
13668            }
13669
13670            // Never clobber system or policy.
13671            if ((oldFlags & policyOrSystemFlags) != 0) {
13672                continue;
13673            }
13674
13675            // If this permission was granted by default, make sure it is.
13676            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13677                if (permissionsState.grantRuntimePermission(bp, userId)
13678                        != PERMISSION_OPERATION_FAILURE) {
13679                    writeRuntimePermissions = true;
13680                }
13681            } else {
13682                // Otherwise, reset the permission.
13683                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13684                switch (revokeResult) {
13685                    case PERMISSION_OPERATION_SUCCESS: {
13686                        writeRuntimePermissions = true;
13687                    } break;
13688
13689                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13690                        writeRuntimePermissions = true;
13691                        final int appId = ps.appId;
13692                        mHandler.post(new Runnable() {
13693                            @Override
13694                            public void run() {
13695                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13696                            }
13697                        });
13698                    } break;
13699                }
13700            }
13701        }
13702
13703        // Synchronously write as we are taking permissions away.
13704        if (writeRuntimePermissions) {
13705            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13706        }
13707
13708        // Synchronously write as we are taking permissions away.
13709        if (writeInstallPermissions) {
13710            mSettings.writeLPr();
13711        }
13712    }
13713
13714    /**
13715     * Remove entries from the keystore daemon. Will only remove it if the
13716     * {@code appId} is valid.
13717     */
13718    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13719        if (appId < 0) {
13720            return;
13721        }
13722
13723        final KeyStore keyStore = KeyStore.getInstance();
13724        if (keyStore != null) {
13725            if (userId == UserHandle.USER_ALL) {
13726                for (final int individual : sUserManager.getUserIds()) {
13727                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13728                }
13729            } else {
13730                keyStore.clearUid(UserHandle.getUid(userId, appId));
13731            }
13732        } else {
13733            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13734        }
13735    }
13736
13737    @Override
13738    public void deleteApplicationCacheFiles(final String packageName,
13739            final IPackageDataObserver observer) {
13740        mContext.enforceCallingOrSelfPermission(
13741                android.Manifest.permission.DELETE_CACHE_FILES, null);
13742        // Queue up an async operation since the package deletion may take a little while.
13743        final int userId = UserHandle.getCallingUserId();
13744        mHandler.post(new Runnable() {
13745            public void run() {
13746                mHandler.removeCallbacks(this);
13747                final boolean succeded;
13748                synchronized (mInstallLock) {
13749                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13750                }
13751                clearExternalStorageDataSync(packageName, userId, false);
13752                if (observer != null) {
13753                    try {
13754                        observer.onRemoveCompleted(packageName, succeded);
13755                    } catch (RemoteException e) {
13756                        Log.i(TAG, "Observer no longer exists.");
13757                    }
13758                } //end if observer
13759            } //end run
13760        });
13761    }
13762
13763    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13764        if (packageName == null) {
13765            Slog.w(TAG, "Attempt to delete null packageName.");
13766            return false;
13767        }
13768        PackageParser.Package p;
13769        synchronized (mPackages) {
13770            p = mPackages.get(packageName);
13771        }
13772        if (p == null) {
13773            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13774            return false;
13775        }
13776        final ApplicationInfo applicationInfo = p.applicationInfo;
13777        if (applicationInfo == null) {
13778            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13779            return false;
13780        }
13781        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13782        if (retCode < 0) {
13783            Slog.w(TAG, "Couldn't remove cache files for package: "
13784                       + packageName + " u" + userId);
13785            return false;
13786        }
13787        return true;
13788    }
13789
13790    @Override
13791    public void getPackageSizeInfo(final String packageName, int userHandle,
13792            final IPackageStatsObserver observer) {
13793        mContext.enforceCallingOrSelfPermission(
13794                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13795        if (packageName == null) {
13796            throw new IllegalArgumentException("Attempt to get size of null packageName");
13797        }
13798
13799        PackageStats stats = new PackageStats(packageName, userHandle);
13800
13801        /*
13802         * Queue up an async operation since the package measurement may take a
13803         * little while.
13804         */
13805        Message msg = mHandler.obtainMessage(INIT_COPY);
13806        msg.obj = new MeasureParams(stats, observer);
13807        mHandler.sendMessage(msg);
13808    }
13809
13810    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13811            PackageStats pStats) {
13812        if (packageName == null) {
13813            Slog.w(TAG, "Attempt to get size of null packageName.");
13814            return false;
13815        }
13816        PackageParser.Package p;
13817        boolean dataOnly = false;
13818        String libDirRoot = null;
13819        String asecPath = null;
13820        PackageSetting ps = null;
13821        synchronized (mPackages) {
13822            p = mPackages.get(packageName);
13823            ps = mSettings.mPackages.get(packageName);
13824            if(p == null) {
13825                dataOnly = true;
13826                if((ps == null) || (ps.pkg == null)) {
13827                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13828                    return false;
13829                }
13830                p = ps.pkg;
13831            }
13832            if (ps != null) {
13833                libDirRoot = ps.legacyNativeLibraryPathString;
13834            }
13835            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13836                final long token = Binder.clearCallingIdentity();
13837                try {
13838                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13839                    if (secureContainerId != null) {
13840                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13841                    }
13842                } finally {
13843                    Binder.restoreCallingIdentity(token);
13844                }
13845            }
13846        }
13847        String publicSrcDir = null;
13848        if(!dataOnly) {
13849            final ApplicationInfo applicationInfo = p.applicationInfo;
13850            if (applicationInfo == null) {
13851                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13852                return false;
13853            }
13854            if (p.isForwardLocked()) {
13855                publicSrcDir = applicationInfo.getBaseResourcePath();
13856            }
13857        }
13858        // TODO: extend to measure size of split APKs
13859        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13860        // not just the first level.
13861        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13862        // just the primary.
13863        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13864
13865        String apkPath;
13866        File packageDir = new File(p.codePath);
13867
13868        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13869            apkPath = packageDir.getAbsolutePath();
13870            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13871            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13872                libDirRoot = null;
13873            }
13874        } else {
13875            apkPath = p.baseCodePath;
13876        }
13877
13878        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13879                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13880        if (res < 0) {
13881            return false;
13882        }
13883
13884        // Fix-up for forward-locked applications in ASEC containers.
13885        if (!isExternal(p)) {
13886            pStats.codeSize += pStats.externalCodeSize;
13887            pStats.externalCodeSize = 0L;
13888        }
13889
13890        return true;
13891    }
13892
13893
13894    @Override
13895    public void addPackageToPreferred(String packageName) {
13896        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13897    }
13898
13899    @Override
13900    public void removePackageFromPreferred(String packageName) {
13901        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13902    }
13903
13904    @Override
13905    public List<PackageInfo> getPreferredPackages(int flags) {
13906        return new ArrayList<PackageInfo>();
13907    }
13908
13909    private int getUidTargetSdkVersionLockedLPr(int uid) {
13910        Object obj = mSettings.getUserIdLPr(uid);
13911        if (obj instanceof SharedUserSetting) {
13912            final SharedUserSetting sus = (SharedUserSetting) obj;
13913            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13914            final Iterator<PackageSetting> it = sus.packages.iterator();
13915            while (it.hasNext()) {
13916                final PackageSetting ps = it.next();
13917                if (ps.pkg != null) {
13918                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13919                    if (v < vers) vers = v;
13920                }
13921            }
13922            return vers;
13923        } else if (obj instanceof PackageSetting) {
13924            final PackageSetting ps = (PackageSetting) obj;
13925            if (ps.pkg != null) {
13926                return ps.pkg.applicationInfo.targetSdkVersion;
13927            }
13928        }
13929        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13930    }
13931
13932    @Override
13933    public void addPreferredActivity(IntentFilter filter, int match,
13934            ComponentName[] set, ComponentName activity, int userId) {
13935        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13936                "Adding preferred");
13937    }
13938
13939    private void addPreferredActivityInternal(IntentFilter filter, int match,
13940            ComponentName[] set, ComponentName activity, boolean always, int userId,
13941            String opname) {
13942        // writer
13943        int callingUid = Binder.getCallingUid();
13944        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13945        if (filter.countActions() == 0) {
13946            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13947            return;
13948        }
13949        synchronized (mPackages) {
13950            if (mContext.checkCallingOrSelfPermission(
13951                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13952                    != PackageManager.PERMISSION_GRANTED) {
13953                if (getUidTargetSdkVersionLockedLPr(callingUid)
13954                        < Build.VERSION_CODES.FROYO) {
13955                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13956                            + callingUid);
13957                    return;
13958                }
13959                mContext.enforceCallingOrSelfPermission(
13960                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13961            }
13962
13963            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13964            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13965                    + userId + ":");
13966            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13967            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13968            scheduleWritePackageRestrictionsLocked(userId);
13969        }
13970    }
13971
13972    @Override
13973    public void replacePreferredActivity(IntentFilter filter, int match,
13974            ComponentName[] set, ComponentName activity, int userId) {
13975        if (filter.countActions() != 1) {
13976            throw new IllegalArgumentException(
13977                    "replacePreferredActivity expects filter to have only 1 action.");
13978        }
13979        if (filter.countDataAuthorities() != 0
13980                || filter.countDataPaths() != 0
13981                || filter.countDataSchemes() > 1
13982                || filter.countDataTypes() != 0) {
13983            throw new IllegalArgumentException(
13984                    "replacePreferredActivity expects filter to have no data authorities, " +
13985                    "paths, or types; and at most one scheme.");
13986        }
13987
13988        final int callingUid = Binder.getCallingUid();
13989        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13990        synchronized (mPackages) {
13991            if (mContext.checkCallingOrSelfPermission(
13992                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13993                    != PackageManager.PERMISSION_GRANTED) {
13994                if (getUidTargetSdkVersionLockedLPr(callingUid)
13995                        < Build.VERSION_CODES.FROYO) {
13996                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13997                            + Binder.getCallingUid());
13998                    return;
13999                }
14000                mContext.enforceCallingOrSelfPermission(
14001                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14002            }
14003
14004            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14005            if (pir != null) {
14006                // Get all of the existing entries that exactly match this filter.
14007                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14008                if (existing != null && existing.size() == 1) {
14009                    PreferredActivity cur = existing.get(0);
14010                    if (DEBUG_PREFERRED) {
14011                        Slog.i(TAG, "Checking replace of preferred:");
14012                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14013                        if (!cur.mPref.mAlways) {
14014                            Slog.i(TAG, "  -- CUR; not mAlways!");
14015                        } else {
14016                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14017                            Slog.i(TAG, "  -- CUR: mSet="
14018                                    + Arrays.toString(cur.mPref.mSetComponents));
14019                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14020                            Slog.i(TAG, "  -- NEW: mMatch="
14021                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14022                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14023                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14024                        }
14025                    }
14026                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14027                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14028                            && cur.mPref.sameSet(set)) {
14029                        // Setting the preferred activity to what it happens to be already
14030                        if (DEBUG_PREFERRED) {
14031                            Slog.i(TAG, "Replacing with same preferred activity "
14032                                    + cur.mPref.mShortComponent + " for user "
14033                                    + userId + ":");
14034                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14035                        }
14036                        return;
14037                    }
14038                }
14039
14040                if (existing != null) {
14041                    if (DEBUG_PREFERRED) {
14042                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14043                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14044                    }
14045                    for (int i = 0; i < existing.size(); i++) {
14046                        PreferredActivity pa = existing.get(i);
14047                        if (DEBUG_PREFERRED) {
14048                            Slog.i(TAG, "Removing existing preferred activity "
14049                                    + pa.mPref.mComponent + ":");
14050                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14051                        }
14052                        pir.removeFilter(pa);
14053                    }
14054                }
14055            }
14056            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14057                    "Replacing preferred");
14058        }
14059    }
14060
14061    @Override
14062    public void clearPackagePreferredActivities(String packageName) {
14063        final int uid = Binder.getCallingUid();
14064        // writer
14065        synchronized (mPackages) {
14066            PackageParser.Package pkg = mPackages.get(packageName);
14067            if (pkg == null || pkg.applicationInfo.uid != uid) {
14068                if (mContext.checkCallingOrSelfPermission(
14069                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14070                        != PackageManager.PERMISSION_GRANTED) {
14071                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14072                            < Build.VERSION_CODES.FROYO) {
14073                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14074                                + Binder.getCallingUid());
14075                        return;
14076                    }
14077                    mContext.enforceCallingOrSelfPermission(
14078                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14079                }
14080            }
14081
14082            int user = UserHandle.getCallingUserId();
14083            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14084                scheduleWritePackageRestrictionsLocked(user);
14085            }
14086        }
14087    }
14088
14089    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14090    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14091        ArrayList<PreferredActivity> removed = null;
14092        boolean changed = false;
14093        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14094            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14095            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14096            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14097                continue;
14098            }
14099            Iterator<PreferredActivity> it = pir.filterIterator();
14100            while (it.hasNext()) {
14101                PreferredActivity pa = it.next();
14102                // Mark entry for removal only if it matches the package name
14103                // and the entry is of type "always".
14104                if (packageName == null ||
14105                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14106                                && pa.mPref.mAlways)) {
14107                    if (removed == null) {
14108                        removed = new ArrayList<PreferredActivity>();
14109                    }
14110                    removed.add(pa);
14111                }
14112            }
14113            if (removed != null) {
14114                for (int j=0; j<removed.size(); j++) {
14115                    PreferredActivity pa = removed.get(j);
14116                    pir.removeFilter(pa);
14117                }
14118                changed = true;
14119            }
14120        }
14121        return changed;
14122    }
14123
14124    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14125    private void clearIntentFilterVerificationsLPw(int userId) {
14126        final int packageCount = mPackages.size();
14127        for (int i = 0; i < packageCount; i++) {
14128            PackageParser.Package pkg = mPackages.valueAt(i);
14129            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14130        }
14131    }
14132
14133    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14134    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14135        if (userId == UserHandle.USER_ALL) {
14136            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14137                    sUserManager.getUserIds())) {
14138                for (int oneUserId : sUserManager.getUserIds()) {
14139                    scheduleWritePackageRestrictionsLocked(oneUserId);
14140                }
14141            }
14142        } else {
14143            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14144                scheduleWritePackageRestrictionsLocked(userId);
14145            }
14146        }
14147    }
14148
14149    void clearDefaultBrowserIfNeeded(String packageName) {
14150        for (int oneUserId : sUserManager.getUserIds()) {
14151            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14152            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14153            if (packageName.equals(defaultBrowserPackageName)) {
14154                setDefaultBrowserPackageName(null, oneUserId);
14155            }
14156        }
14157    }
14158
14159    @Override
14160    public void resetApplicationPreferences(int userId) {
14161        mContext.enforceCallingOrSelfPermission(
14162                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14163        // writer
14164        synchronized (mPackages) {
14165            final long identity = Binder.clearCallingIdentity();
14166            try {
14167                clearPackagePreferredActivitiesLPw(null, userId);
14168                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14169                // TODO: We have to reset the default SMS and Phone. This requires
14170                // significant refactoring to keep all default apps in the package
14171                // manager (cleaner but more work) or have the services provide
14172                // callbacks to the package manager to request a default app reset.
14173                applyFactoryDefaultBrowserLPw(userId);
14174                clearIntentFilterVerificationsLPw(userId);
14175                primeDomainVerificationsLPw(userId);
14176                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14177                scheduleWritePackageRestrictionsLocked(userId);
14178            } finally {
14179                Binder.restoreCallingIdentity(identity);
14180            }
14181        }
14182    }
14183
14184    @Override
14185    public int getPreferredActivities(List<IntentFilter> outFilters,
14186            List<ComponentName> outActivities, String packageName) {
14187
14188        int num = 0;
14189        final int userId = UserHandle.getCallingUserId();
14190        // reader
14191        synchronized (mPackages) {
14192            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14193            if (pir != null) {
14194                final Iterator<PreferredActivity> it = pir.filterIterator();
14195                while (it.hasNext()) {
14196                    final PreferredActivity pa = it.next();
14197                    if (packageName == null
14198                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14199                                    && pa.mPref.mAlways)) {
14200                        if (outFilters != null) {
14201                            outFilters.add(new IntentFilter(pa));
14202                        }
14203                        if (outActivities != null) {
14204                            outActivities.add(pa.mPref.mComponent);
14205                        }
14206                    }
14207                }
14208            }
14209        }
14210
14211        return num;
14212    }
14213
14214    @Override
14215    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14216            int userId) {
14217        int callingUid = Binder.getCallingUid();
14218        if (callingUid != Process.SYSTEM_UID) {
14219            throw new SecurityException(
14220                    "addPersistentPreferredActivity can only be run by the system");
14221        }
14222        if (filter.countActions() == 0) {
14223            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14224            return;
14225        }
14226        synchronized (mPackages) {
14227            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14228                    " :");
14229            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14230            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14231                    new PersistentPreferredActivity(filter, activity));
14232            scheduleWritePackageRestrictionsLocked(userId);
14233        }
14234    }
14235
14236    @Override
14237    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14238        int callingUid = Binder.getCallingUid();
14239        if (callingUid != Process.SYSTEM_UID) {
14240            throw new SecurityException(
14241                    "clearPackagePersistentPreferredActivities can only be run by the system");
14242        }
14243        ArrayList<PersistentPreferredActivity> removed = null;
14244        boolean changed = false;
14245        synchronized (mPackages) {
14246            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14247                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14248                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14249                        .valueAt(i);
14250                if (userId != thisUserId) {
14251                    continue;
14252                }
14253                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14254                while (it.hasNext()) {
14255                    PersistentPreferredActivity ppa = it.next();
14256                    // Mark entry for removal only if it matches the package name.
14257                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14258                        if (removed == null) {
14259                            removed = new ArrayList<PersistentPreferredActivity>();
14260                        }
14261                        removed.add(ppa);
14262                    }
14263                }
14264                if (removed != null) {
14265                    for (int j=0; j<removed.size(); j++) {
14266                        PersistentPreferredActivity ppa = removed.get(j);
14267                        ppir.removeFilter(ppa);
14268                    }
14269                    changed = true;
14270                }
14271            }
14272
14273            if (changed) {
14274                scheduleWritePackageRestrictionsLocked(userId);
14275            }
14276        }
14277    }
14278
14279    /**
14280     * Common machinery for picking apart a restored XML blob and passing
14281     * it to a caller-supplied functor to be applied to the running system.
14282     */
14283    private void restoreFromXml(XmlPullParser parser, int userId,
14284            String expectedStartTag, BlobXmlRestorer functor)
14285            throws IOException, XmlPullParserException {
14286        int type;
14287        while ((type = parser.next()) != XmlPullParser.START_TAG
14288                && type != XmlPullParser.END_DOCUMENT) {
14289        }
14290        if (type != XmlPullParser.START_TAG) {
14291            // oops didn't find a start tag?!
14292            if (DEBUG_BACKUP) {
14293                Slog.e(TAG, "Didn't find start tag during restore");
14294            }
14295            return;
14296        }
14297
14298        // this is supposed to be TAG_PREFERRED_BACKUP
14299        if (!expectedStartTag.equals(parser.getName())) {
14300            if (DEBUG_BACKUP) {
14301                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14302            }
14303            return;
14304        }
14305
14306        // skip interfering stuff, then we're aligned with the backing implementation
14307        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14308        functor.apply(parser, userId);
14309    }
14310
14311    private interface BlobXmlRestorer {
14312        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14313    }
14314
14315    /**
14316     * Non-Binder method, support for the backup/restore mechanism: write the
14317     * full set of preferred activities in its canonical XML format.  Returns the
14318     * XML output as a byte array, or null if there is none.
14319     */
14320    @Override
14321    public byte[] getPreferredActivityBackup(int userId) {
14322        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14323            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14324        }
14325
14326        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14327        try {
14328            final XmlSerializer serializer = new FastXmlSerializer();
14329            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14330            serializer.startDocument(null, true);
14331            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14332
14333            synchronized (mPackages) {
14334                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14335            }
14336
14337            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14338            serializer.endDocument();
14339            serializer.flush();
14340        } catch (Exception e) {
14341            if (DEBUG_BACKUP) {
14342                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14343            }
14344            return null;
14345        }
14346
14347        return dataStream.toByteArray();
14348    }
14349
14350    @Override
14351    public void restorePreferredActivities(byte[] backup, int userId) {
14352        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14353            throw new SecurityException("Only the system may call restorePreferredActivities()");
14354        }
14355
14356        try {
14357            final XmlPullParser parser = Xml.newPullParser();
14358            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14359            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14360                    new BlobXmlRestorer() {
14361                        @Override
14362                        public void apply(XmlPullParser parser, int userId)
14363                                throws XmlPullParserException, IOException {
14364                            synchronized (mPackages) {
14365                                mSettings.readPreferredActivitiesLPw(parser, userId);
14366                            }
14367                        }
14368                    } );
14369        } catch (Exception e) {
14370            if (DEBUG_BACKUP) {
14371                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14372            }
14373        }
14374    }
14375
14376    /**
14377     * Non-Binder method, support for the backup/restore mechanism: write the
14378     * default browser (etc) settings in its canonical XML format.  Returns the default
14379     * browser XML representation as a byte array, or null if there is none.
14380     */
14381    @Override
14382    public byte[] getDefaultAppsBackup(int userId) {
14383        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14384            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14385        }
14386
14387        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14388        try {
14389            final XmlSerializer serializer = new FastXmlSerializer();
14390            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14391            serializer.startDocument(null, true);
14392            serializer.startTag(null, TAG_DEFAULT_APPS);
14393
14394            synchronized (mPackages) {
14395                mSettings.writeDefaultAppsLPr(serializer, userId);
14396            }
14397
14398            serializer.endTag(null, TAG_DEFAULT_APPS);
14399            serializer.endDocument();
14400            serializer.flush();
14401        } catch (Exception e) {
14402            if (DEBUG_BACKUP) {
14403                Slog.e(TAG, "Unable to write default apps for backup", e);
14404            }
14405            return null;
14406        }
14407
14408        return dataStream.toByteArray();
14409    }
14410
14411    @Override
14412    public void restoreDefaultApps(byte[] backup, int userId) {
14413        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14414            throw new SecurityException("Only the system may call restoreDefaultApps()");
14415        }
14416
14417        try {
14418            final XmlPullParser parser = Xml.newPullParser();
14419            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14420            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14421                    new BlobXmlRestorer() {
14422                        @Override
14423                        public void apply(XmlPullParser parser, int userId)
14424                                throws XmlPullParserException, IOException {
14425                            synchronized (mPackages) {
14426                                mSettings.readDefaultAppsLPw(parser, userId);
14427                            }
14428                        }
14429                    } );
14430        } catch (Exception e) {
14431            if (DEBUG_BACKUP) {
14432                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14433            }
14434        }
14435    }
14436
14437    @Override
14438    public byte[] getIntentFilterVerificationBackup(int userId) {
14439        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14440            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14441        }
14442
14443        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14444        try {
14445            final XmlSerializer serializer = new FastXmlSerializer();
14446            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14447            serializer.startDocument(null, true);
14448            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14449
14450            synchronized (mPackages) {
14451                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14452            }
14453
14454            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14455            serializer.endDocument();
14456            serializer.flush();
14457        } catch (Exception e) {
14458            if (DEBUG_BACKUP) {
14459                Slog.e(TAG, "Unable to write default apps for backup", e);
14460            }
14461            return null;
14462        }
14463
14464        return dataStream.toByteArray();
14465    }
14466
14467    @Override
14468    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14469        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14470            throw new SecurityException("Only the system may call restorePreferredActivities()");
14471        }
14472
14473        try {
14474            final XmlPullParser parser = Xml.newPullParser();
14475            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14476            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14477                    new BlobXmlRestorer() {
14478                        @Override
14479                        public void apply(XmlPullParser parser, int userId)
14480                                throws XmlPullParserException, IOException {
14481                            synchronized (mPackages) {
14482                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14483                                mSettings.writeLPr();
14484                            }
14485                        }
14486                    } );
14487        } catch (Exception e) {
14488            if (DEBUG_BACKUP) {
14489                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14490            }
14491        }
14492    }
14493
14494    @Override
14495    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14496            int sourceUserId, int targetUserId, int flags) {
14497        mContext.enforceCallingOrSelfPermission(
14498                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14499        int callingUid = Binder.getCallingUid();
14500        enforceOwnerRights(ownerPackage, callingUid);
14501        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14502        if (intentFilter.countActions() == 0) {
14503            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14504            return;
14505        }
14506        synchronized (mPackages) {
14507            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14508                    ownerPackage, targetUserId, flags);
14509            CrossProfileIntentResolver resolver =
14510                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14511            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14512            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14513            if (existing != null) {
14514                int size = existing.size();
14515                for (int i = 0; i < size; i++) {
14516                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14517                        return;
14518                    }
14519                }
14520            }
14521            resolver.addFilter(newFilter);
14522            scheduleWritePackageRestrictionsLocked(sourceUserId);
14523        }
14524    }
14525
14526    @Override
14527    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14528        mContext.enforceCallingOrSelfPermission(
14529                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14530        int callingUid = Binder.getCallingUid();
14531        enforceOwnerRights(ownerPackage, callingUid);
14532        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14533        synchronized (mPackages) {
14534            CrossProfileIntentResolver resolver =
14535                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14536            ArraySet<CrossProfileIntentFilter> set =
14537                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14538            for (CrossProfileIntentFilter filter : set) {
14539                if (filter.getOwnerPackage().equals(ownerPackage)) {
14540                    resolver.removeFilter(filter);
14541                }
14542            }
14543            scheduleWritePackageRestrictionsLocked(sourceUserId);
14544        }
14545    }
14546
14547    // Enforcing that callingUid is owning pkg on userId
14548    private void enforceOwnerRights(String pkg, int callingUid) {
14549        // The system owns everything.
14550        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14551            return;
14552        }
14553        int callingUserId = UserHandle.getUserId(callingUid);
14554        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14555        if (pi == null) {
14556            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14557                    + callingUserId);
14558        }
14559        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14560            throw new SecurityException("Calling uid " + callingUid
14561                    + " does not own package " + pkg);
14562        }
14563    }
14564
14565    @Override
14566    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14567        Intent intent = new Intent(Intent.ACTION_MAIN);
14568        intent.addCategory(Intent.CATEGORY_HOME);
14569
14570        final int callingUserId = UserHandle.getCallingUserId();
14571        List<ResolveInfo> list = queryIntentActivities(intent, null,
14572                PackageManager.GET_META_DATA, callingUserId);
14573        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14574                true, false, false, callingUserId);
14575
14576        allHomeCandidates.clear();
14577        if (list != null) {
14578            for (ResolveInfo ri : list) {
14579                allHomeCandidates.add(ri);
14580            }
14581        }
14582        return (preferred == null || preferred.activityInfo == null)
14583                ? null
14584                : new ComponentName(preferred.activityInfo.packageName,
14585                        preferred.activityInfo.name);
14586    }
14587
14588    @Override
14589    public void setApplicationEnabledSetting(String appPackageName,
14590            int newState, int flags, int userId, String callingPackage) {
14591        if (!sUserManager.exists(userId)) return;
14592        if (callingPackage == null) {
14593            callingPackage = Integer.toString(Binder.getCallingUid());
14594        }
14595        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14596    }
14597
14598    @Override
14599    public void setComponentEnabledSetting(ComponentName componentName,
14600            int newState, int flags, int userId) {
14601        if (!sUserManager.exists(userId)) return;
14602        setEnabledSetting(componentName.getPackageName(),
14603                componentName.getClassName(), newState, flags, userId, null);
14604    }
14605
14606    private void setEnabledSetting(final String packageName, String className, int newState,
14607            final int flags, int userId, String callingPackage) {
14608        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14609              || newState == COMPONENT_ENABLED_STATE_ENABLED
14610              || newState == COMPONENT_ENABLED_STATE_DISABLED
14611              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14612              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14613            throw new IllegalArgumentException("Invalid new component state: "
14614                    + newState);
14615        }
14616        PackageSetting pkgSetting;
14617        final int uid = Binder.getCallingUid();
14618        final int permission = mContext.checkCallingOrSelfPermission(
14619                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14620        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14621        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14622        boolean sendNow = false;
14623        boolean isApp = (className == null);
14624        String componentName = isApp ? packageName : className;
14625        int packageUid = -1;
14626        ArrayList<String> components;
14627
14628        // writer
14629        synchronized (mPackages) {
14630            pkgSetting = mSettings.mPackages.get(packageName);
14631            if (pkgSetting == null) {
14632                if (className == null) {
14633                    throw new IllegalArgumentException(
14634                            "Unknown package: " + packageName);
14635                }
14636                throw new IllegalArgumentException(
14637                        "Unknown component: " + packageName
14638                        + "/" + className);
14639            }
14640            // Allow root and verify that userId is not being specified by a different user
14641            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14642                throw new SecurityException(
14643                        "Permission Denial: attempt to change component state from pid="
14644                        + Binder.getCallingPid()
14645                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14646            }
14647            if (className == null) {
14648                // We're dealing with an application/package level state change
14649                if (pkgSetting.getEnabled(userId) == newState) {
14650                    // Nothing to do
14651                    return;
14652                }
14653                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14654                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14655                    // Don't care about who enables an app.
14656                    callingPackage = null;
14657                }
14658                pkgSetting.setEnabled(newState, userId, callingPackage);
14659                // pkgSetting.pkg.mSetEnabled = newState;
14660            } else {
14661                // We're dealing with a component level state change
14662                // First, verify that this is a valid class name.
14663                PackageParser.Package pkg = pkgSetting.pkg;
14664                if (pkg == null || !pkg.hasComponentClassName(className)) {
14665                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14666                        throw new IllegalArgumentException("Component class " + className
14667                                + " does not exist in " + packageName);
14668                    } else {
14669                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14670                                + className + " does not exist in " + packageName);
14671                    }
14672                }
14673                switch (newState) {
14674                case COMPONENT_ENABLED_STATE_ENABLED:
14675                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14676                        return;
14677                    }
14678                    break;
14679                case COMPONENT_ENABLED_STATE_DISABLED:
14680                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14681                        return;
14682                    }
14683                    break;
14684                case COMPONENT_ENABLED_STATE_DEFAULT:
14685                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14686                        return;
14687                    }
14688                    break;
14689                default:
14690                    Slog.e(TAG, "Invalid new component state: " + newState);
14691                    return;
14692                }
14693            }
14694            scheduleWritePackageRestrictionsLocked(userId);
14695            components = mPendingBroadcasts.get(userId, packageName);
14696            final boolean newPackage = components == null;
14697            if (newPackage) {
14698                components = new ArrayList<String>();
14699            }
14700            if (!components.contains(componentName)) {
14701                components.add(componentName);
14702            }
14703            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14704                sendNow = true;
14705                // Purge entry from pending broadcast list if another one exists already
14706                // since we are sending one right away.
14707                mPendingBroadcasts.remove(userId, packageName);
14708            } else {
14709                if (newPackage) {
14710                    mPendingBroadcasts.put(userId, packageName, components);
14711                }
14712                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14713                    // Schedule a message
14714                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14715                }
14716            }
14717        }
14718
14719        long callingId = Binder.clearCallingIdentity();
14720        try {
14721            if (sendNow) {
14722                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14723                sendPackageChangedBroadcast(packageName,
14724                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14725            }
14726        } finally {
14727            Binder.restoreCallingIdentity(callingId);
14728        }
14729    }
14730
14731    private void sendPackageChangedBroadcast(String packageName,
14732            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14733        if (DEBUG_INSTALL)
14734            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14735                    + componentNames);
14736        Bundle extras = new Bundle(4);
14737        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14738        String nameList[] = new String[componentNames.size()];
14739        componentNames.toArray(nameList);
14740        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14741        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14742        extras.putInt(Intent.EXTRA_UID, packageUid);
14743        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14744                new int[] {UserHandle.getUserId(packageUid)});
14745    }
14746
14747    @Override
14748    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14749        if (!sUserManager.exists(userId)) return;
14750        final int uid = Binder.getCallingUid();
14751        final int permission = mContext.checkCallingOrSelfPermission(
14752                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14753        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14754        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14755        // writer
14756        synchronized (mPackages) {
14757            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14758                    allowedByPermission, uid, userId)) {
14759                scheduleWritePackageRestrictionsLocked(userId);
14760            }
14761        }
14762    }
14763
14764    @Override
14765    public String getInstallerPackageName(String packageName) {
14766        // reader
14767        synchronized (mPackages) {
14768            return mSettings.getInstallerPackageNameLPr(packageName);
14769        }
14770    }
14771
14772    @Override
14773    public int getApplicationEnabledSetting(String packageName, int userId) {
14774        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14775        int uid = Binder.getCallingUid();
14776        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14777        // reader
14778        synchronized (mPackages) {
14779            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14780        }
14781    }
14782
14783    @Override
14784    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14785        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14786        int uid = Binder.getCallingUid();
14787        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14788        // reader
14789        synchronized (mPackages) {
14790            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14791        }
14792    }
14793
14794    @Override
14795    public void enterSafeMode() {
14796        enforceSystemOrRoot("Only the system can request entering safe mode");
14797
14798        if (!mSystemReady) {
14799            mSafeMode = true;
14800        }
14801    }
14802
14803    @Override
14804    public void systemReady() {
14805        mSystemReady = true;
14806
14807        // Read the compatibilty setting when the system is ready.
14808        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14809                mContext.getContentResolver(),
14810                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14811        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14812        if (DEBUG_SETTINGS) {
14813            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14814        }
14815
14816        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14817
14818        synchronized (mPackages) {
14819            // Verify that all of the preferred activity components actually
14820            // exist.  It is possible for applications to be updated and at
14821            // that point remove a previously declared activity component that
14822            // had been set as a preferred activity.  We try to clean this up
14823            // the next time we encounter that preferred activity, but it is
14824            // possible for the user flow to never be able to return to that
14825            // situation so here we do a sanity check to make sure we haven't
14826            // left any junk around.
14827            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14828            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14829                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14830                removed.clear();
14831                for (PreferredActivity pa : pir.filterSet()) {
14832                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14833                        removed.add(pa);
14834                    }
14835                }
14836                if (removed.size() > 0) {
14837                    for (int r=0; r<removed.size(); r++) {
14838                        PreferredActivity pa = removed.get(r);
14839                        Slog.w(TAG, "Removing dangling preferred activity: "
14840                                + pa.mPref.mComponent);
14841                        pir.removeFilter(pa);
14842                    }
14843                    mSettings.writePackageRestrictionsLPr(
14844                            mSettings.mPreferredActivities.keyAt(i));
14845                }
14846            }
14847
14848            for (int userId : UserManagerService.getInstance().getUserIds()) {
14849                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14850                    grantPermissionsUserIds = ArrayUtils.appendInt(
14851                            grantPermissionsUserIds, userId);
14852                }
14853            }
14854        }
14855        sUserManager.systemReady();
14856
14857        // If we upgraded grant all default permissions before kicking off.
14858        for (int userId : grantPermissionsUserIds) {
14859            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14860        }
14861
14862        // Kick off any messages waiting for system ready
14863        if (mPostSystemReadyMessages != null) {
14864            for (Message msg : mPostSystemReadyMessages) {
14865                msg.sendToTarget();
14866            }
14867            mPostSystemReadyMessages = null;
14868        }
14869
14870        // Watch for external volumes that come and go over time
14871        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14872        storage.registerListener(mStorageListener);
14873
14874        mInstallerService.systemReady();
14875        mPackageDexOptimizer.systemReady();
14876
14877        MountServiceInternal mountServiceInternal = LocalServices.getService(
14878                MountServiceInternal.class);
14879        mountServiceInternal.addExternalStoragePolicy(
14880                new MountServiceInternal.ExternalStorageMountPolicy() {
14881            @Override
14882            public int getMountMode(int uid, String packageName) {
14883                if (Process.isIsolated(uid)) {
14884                    return Zygote.MOUNT_EXTERNAL_NONE;
14885                }
14886                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14887                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14888                }
14889                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14890                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14891                }
14892                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14893                    return Zygote.MOUNT_EXTERNAL_READ;
14894                }
14895                return Zygote.MOUNT_EXTERNAL_WRITE;
14896            }
14897
14898            @Override
14899            public boolean hasExternalStorage(int uid, String packageName) {
14900                return true;
14901            }
14902        });
14903    }
14904
14905    @Override
14906    public boolean isSafeMode() {
14907        return mSafeMode;
14908    }
14909
14910    @Override
14911    public boolean hasSystemUidErrors() {
14912        return mHasSystemUidErrors;
14913    }
14914
14915    static String arrayToString(int[] array) {
14916        StringBuffer buf = new StringBuffer(128);
14917        buf.append('[');
14918        if (array != null) {
14919            for (int i=0; i<array.length; i++) {
14920                if (i > 0) buf.append(", ");
14921                buf.append(array[i]);
14922            }
14923        }
14924        buf.append(']');
14925        return buf.toString();
14926    }
14927
14928    static class DumpState {
14929        public static final int DUMP_LIBS = 1 << 0;
14930        public static final int DUMP_FEATURES = 1 << 1;
14931        public static final int DUMP_RESOLVERS = 1 << 2;
14932        public static final int DUMP_PERMISSIONS = 1 << 3;
14933        public static final int DUMP_PACKAGES = 1 << 4;
14934        public static final int DUMP_SHARED_USERS = 1 << 5;
14935        public static final int DUMP_MESSAGES = 1 << 6;
14936        public static final int DUMP_PROVIDERS = 1 << 7;
14937        public static final int DUMP_VERIFIERS = 1 << 8;
14938        public static final int DUMP_PREFERRED = 1 << 9;
14939        public static final int DUMP_PREFERRED_XML = 1 << 10;
14940        public static final int DUMP_KEYSETS = 1 << 11;
14941        public static final int DUMP_VERSION = 1 << 12;
14942        public static final int DUMP_INSTALLS = 1 << 13;
14943        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14944        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14945
14946        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14947
14948        private int mTypes;
14949
14950        private int mOptions;
14951
14952        private boolean mTitlePrinted;
14953
14954        private SharedUserSetting mSharedUser;
14955
14956        public boolean isDumping(int type) {
14957            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14958                return true;
14959            }
14960
14961            return (mTypes & type) != 0;
14962        }
14963
14964        public void setDump(int type) {
14965            mTypes |= type;
14966        }
14967
14968        public boolean isOptionEnabled(int option) {
14969            return (mOptions & option) != 0;
14970        }
14971
14972        public void setOptionEnabled(int option) {
14973            mOptions |= option;
14974        }
14975
14976        public boolean onTitlePrinted() {
14977            final boolean printed = mTitlePrinted;
14978            mTitlePrinted = true;
14979            return printed;
14980        }
14981
14982        public boolean getTitlePrinted() {
14983            return mTitlePrinted;
14984        }
14985
14986        public void setTitlePrinted(boolean enabled) {
14987            mTitlePrinted = enabled;
14988        }
14989
14990        public SharedUserSetting getSharedUser() {
14991            return mSharedUser;
14992        }
14993
14994        public void setSharedUser(SharedUserSetting user) {
14995            mSharedUser = user;
14996        }
14997    }
14998
14999    @Override
15000    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15001        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15002                != PackageManager.PERMISSION_GRANTED) {
15003            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15004                    + Binder.getCallingPid()
15005                    + ", uid=" + Binder.getCallingUid()
15006                    + " without permission "
15007                    + android.Manifest.permission.DUMP);
15008            return;
15009        }
15010
15011        DumpState dumpState = new DumpState();
15012        boolean fullPreferred = false;
15013        boolean checkin = false;
15014
15015        String packageName = null;
15016        ArraySet<String> permissionNames = null;
15017
15018        int opti = 0;
15019        while (opti < args.length) {
15020            String opt = args[opti];
15021            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15022                break;
15023            }
15024            opti++;
15025
15026            if ("-a".equals(opt)) {
15027                // Right now we only know how to print all.
15028            } else if ("-h".equals(opt)) {
15029                pw.println("Package manager dump options:");
15030                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15031                pw.println("    --checkin: dump for a checkin");
15032                pw.println("    -f: print details of intent filters");
15033                pw.println("    -h: print this help");
15034                pw.println("  cmd may be one of:");
15035                pw.println("    l[ibraries]: list known shared libraries");
15036                pw.println("    f[ibraries]: list device features");
15037                pw.println("    k[eysets]: print known keysets");
15038                pw.println("    r[esolvers]: dump intent resolvers");
15039                pw.println("    perm[issions]: dump permissions");
15040                pw.println("    permission [name ...]: dump declaration and use of given permission");
15041                pw.println("    pref[erred]: print preferred package settings");
15042                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15043                pw.println("    prov[iders]: dump content providers");
15044                pw.println("    p[ackages]: dump installed packages");
15045                pw.println("    s[hared-users]: dump shared user IDs");
15046                pw.println("    m[essages]: print collected runtime messages");
15047                pw.println("    v[erifiers]: print package verifier info");
15048                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15049                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15050                pw.println("    version: print database version info");
15051                pw.println("    write: write current settings now");
15052                pw.println("    installs: details about install sessions");
15053                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15054                pw.println("    <package.name>: info about given package");
15055                return;
15056            } else if ("--checkin".equals(opt)) {
15057                checkin = true;
15058            } else if ("-f".equals(opt)) {
15059                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15060            } else {
15061                pw.println("Unknown argument: " + opt + "; use -h for help");
15062            }
15063        }
15064
15065        // Is the caller requesting to dump a particular piece of data?
15066        if (opti < args.length) {
15067            String cmd = args[opti];
15068            opti++;
15069            // Is this a package name?
15070            if ("android".equals(cmd) || cmd.contains(".")) {
15071                packageName = cmd;
15072                // When dumping a single package, we always dump all of its
15073                // filter information since the amount of data will be reasonable.
15074                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15075            } else if ("check-permission".equals(cmd)) {
15076                if (opti >= args.length) {
15077                    pw.println("Error: check-permission missing permission argument");
15078                    return;
15079                }
15080                String perm = args[opti];
15081                opti++;
15082                if (opti >= args.length) {
15083                    pw.println("Error: check-permission missing package argument");
15084                    return;
15085                }
15086                String pkg = args[opti];
15087                opti++;
15088                int user = UserHandle.getUserId(Binder.getCallingUid());
15089                if (opti < args.length) {
15090                    try {
15091                        user = Integer.parseInt(args[opti]);
15092                    } catch (NumberFormatException e) {
15093                        pw.println("Error: check-permission user argument is not a number: "
15094                                + args[opti]);
15095                        return;
15096                    }
15097                }
15098                pw.println(checkPermission(perm, pkg, user));
15099                return;
15100            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15101                dumpState.setDump(DumpState.DUMP_LIBS);
15102            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15103                dumpState.setDump(DumpState.DUMP_FEATURES);
15104            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15105                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15106            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15107                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15108            } else if ("permission".equals(cmd)) {
15109                if (opti >= args.length) {
15110                    pw.println("Error: permission requires permission name");
15111                    return;
15112                }
15113                permissionNames = new ArraySet<>();
15114                while (opti < args.length) {
15115                    permissionNames.add(args[opti]);
15116                    opti++;
15117                }
15118                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15119                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15120            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15121                dumpState.setDump(DumpState.DUMP_PREFERRED);
15122            } else if ("preferred-xml".equals(cmd)) {
15123                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15124                if (opti < args.length && "--full".equals(args[opti])) {
15125                    fullPreferred = true;
15126                    opti++;
15127                }
15128            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15129                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15130            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15131                dumpState.setDump(DumpState.DUMP_PACKAGES);
15132            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15133                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15134            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15135                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15136            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15137                dumpState.setDump(DumpState.DUMP_MESSAGES);
15138            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15139                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15140            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15141                    || "intent-filter-verifiers".equals(cmd)) {
15142                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15143            } else if ("version".equals(cmd)) {
15144                dumpState.setDump(DumpState.DUMP_VERSION);
15145            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15146                dumpState.setDump(DumpState.DUMP_KEYSETS);
15147            } else if ("installs".equals(cmd)) {
15148                dumpState.setDump(DumpState.DUMP_INSTALLS);
15149            } else if ("write".equals(cmd)) {
15150                synchronized (mPackages) {
15151                    mSettings.writeLPr();
15152                    pw.println("Settings written.");
15153                    return;
15154                }
15155            }
15156        }
15157
15158        if (checkin) {
15159            pw.println("vers,1");
15160        }
15161
15162        // reader
15163        synchronized (mPackages) {
15164            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15165                if (!checkin) {
15166                    if (dumpState.onTitlePrinted())
15167                        pw.println();
15168                    pw.println("Database versions:");
15169                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15170                }
15171            }
15172
15173            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15174                if (!checkin) {
15175                    if (dumpState.onTitlePrinted())
15176                        pw.println();
15177                    pw.println("Verifiers:");
15178                    pw.print("  Required: ");
15179                    pw.print(mRequiredVerifierPackage);
15180                    pw.print(" (uid=");
15181                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15182                    pw.println(")");
15183                } else if (mRequiredVerifierPackage != null) {
15184                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15185                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15186                }
15187            }
15188
15189            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15190                    packageName == null) {
15191                if (mIntentFilterVerifierComponent != null) {
15192                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15193                    if (!checkin) {
15194                        if (dumpState.onTitlePrinted())
15195                            pw.println();
15196                        pw.println("Intent Filter Verifier:");
15197                        pw.print("  Using: ");
15198                        pw.print(verifierPackageName);
15199                        pw.print(" (uid=");
15200                        pw.print(getPackageUid(verifierPackageName, 0));
15201                        pw.println(")");
15202                    } else if (verifierPackageName != null) {
15203                        pw.print("ifv,"); pw.print(verifierPackageName);
15204                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15205                    }
15206                } else {
15207                    pw.println();
15208                    pw.println("No Intent Filter Verifier available!");
15209                }
15210            }
15211
15212            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15213                boolean printedHeader = false;
15214                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15215                while (it.hasNext()) {
15216                    String name = it.next();
15217                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15218                    if (!checkin) {
15219                        if (!printedHeader) {
15220                            if (dumpState.onTitlePrinted())
15221                                pw.println();
15222                            pw.println("Libraries:");
15223                            printedHeader = true;
15224                        }
15225                        pw.print("  ");
15226                    } else {
15227                        pw.print("lib,");
15228                    }
15229                    pw.print(name);
15230                    if (!checkin) {
15231                        pw.print(" -> ");
15232                    }
15233                    if (ent.path != null) {
15234                        if (!checkin) {
15235                            pw.print("(jar) ");
15236                            pw.print(ent.path);
15237                        } else {
15238                            pw.print(",jar,");
15239                            pw.print(ent.path);
15240                        }
15241                    } else {
15242                        if (!checkin) {
15243                            pw.print("(apk) ");
15244                            pw.print(ent.apk);
15245                        } else {
15246                            pw.print(",apk,");
15247                            pw.print(ent.apk);
15248                        }
15249                    }
15250                    pw.println();
15251                }
15252            }
15253
15254            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15255                if (dumpState.onTitlePrinted())
15256                    pw.println();
15257                if (!checkin) {
15258                    pw.println("Features:");
15259                }
15260                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15261                while (it.hasNext()) {
15262                    String name = it.next();
15263                    if (!checkin) {
15264                        pw.print("  ");
15265                    } else {
15266                        pw.print("feat,");
15267                    }
15268                    pw.println(name);
15269                }
15270            }
15271
15272            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15273                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15274                        : "Activity Resolver Table:", "  ", packageName,
15275                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15276                    dumpState.setTitlePrinted(true);
15277                }
15278                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15279                        : "Receiver Resolver Table:", "  ", packageName,
15280                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15281                    dumpState.setTitlePrinted(true);
15282                }
15283                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15284                        : "Service Resolver Table:", "  ", packageName,
15285                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15286                    dumpState.setTitlePrinted(true);
15287                }
15288                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15289                        : "Provider Resolver Table:", "  ", packageName,
15290                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15291                    dumpState.setTitlePrinted(true);
15292                }
15293            }
15294
15295            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15296                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15297                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15298                    int user = mSettings.mPreferredActivities.keyAt(i);
15299                    if (pir.dump(pw,
15300                            dumpState.getTitlePrinted()
15301                                ? "\nPreferred Activities User " + user + ":"
15302                                : "Preferred Activities User " + user + ":", "  ",
15303                            packageName, true, false)) {
15304                        dumpState.setTitlePrinted(true);
15305                    }
15306                }
15307            }
15308
15309            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15310                pw.flush();
15311                FileOutputStream fout = new FileOutputStream(fd);
15312                BufferedOutputStream str = new BufferedOutputStream(fout);
15313                XmlSerializer serializer = new FastXmlSerializer();
15314                try {
15315                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15316                    serializer.startDocument(null, true);
15317                    serializer.setFeature(
15318                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15319                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15320                    serializer.endDocument();
15321                    serializer.flush();
15322                } catch (IllegalArgumentException e) {
15323                    pw.println("Failed writing: " + e);
15324                } catch (IllegalStateException e) {
15325                    pw.println("Failed writing: " + e);
15326                } catch (IOException e) {
15327                    pw.println("Failed writing: " + e);
15328                }
15329            }
15330
15331            if (!checkin
15332                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15333                    && packageName == null) {
15334                pw.println();
15335                int count = mSettings.mPackages.size();
15336                if (count == 0) {
15337                    pw.println("No applications!");
15338                    pw.println();
15339                } else {
15340                    final String prefix = "  ";
15341                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15342                    if (allPackageSettings.size() == 0) {
15343                        pw.println("No domain preferred apps!");
15344                        pw.println();
15345                    } else {
15346                        pw.println("App verification status:");
15347                        pw.println();
15348                        count = 0;
15349                        for (PackageSetting ps : allPackageSettings) {
15350                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15351                            if (ivi == null || ivi.getPackageName() == null) continue;
15352                            pw.println(prefix + "Package: " + ivi.getPackageName());
15353                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15354                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15355                            pw.println();
15356                            count++;
15357                        }
15358                        if (count == 0) {
15359                            pw.println(prefix + "No app verification established.");
15360                            pw.println();
15361                        }
15362                        for (int userId : sUserManager.getUserIds()) {
15363                            pw.println("App linkages for user " + userId + ":");
15364                            pw.println();
15365                            count = 0;
15366                            for (PackageSetting ps : allPackageSettings) {
15367                                final long status = ps.getDomainVerificationStatusForUser(userId);
15368                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15369                                    continue;
15370                                }
15371                                pw.println(prefix + "Package: " + ps.name);
15372                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15373                                String statusStr = IntentFilterVerificationInfo.
15374                                        getStatusStringFromValue(status);
15375                                pw.println(prefix + "Status:  " + statusStr);
15376                                pw.println();
15377                                count++;
15378                            }
15379                            if (count == 0) {
15380                                pw.println(prefix + "No configured app linkages.");
15381                                pw.println();
15382                            }
15383                        }
15384                    }
15385                }
15386            }
15387
15388            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15389                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15390                if (packageName == null && permissionNames == null) {
15391                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15392                        if (iperm == 0) {
15393                            if (dumpState.onTitlePrinted())
15394                                pw.println();
15395                            pw.println("AppOp Permissions:");
15396                        }
15397                        pw.print("  AppOp Permission ");
15398                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15399                        pw.println(":");
15400                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15401                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15402                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15403                        }
15404                    }
15405                }
15406            }
15407
15408            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15409                boolean printedSomething = false;
15410                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15411                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15412                        continue;
15413                    }
15414                    if (!printedSomething) {
15415                        if (dumpState.onTitlePrinted())
15416                            pw.println();
15417                        pw.println("Registered ContentProviders:");
15418                        printedSomething = true;
15419                    }
15420                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15421                    pw.print("    "); pw.println(p.toString());
15422                }
15423                printedSomething = false;
15424                for (Map.Entry<String, PackageParser.Provider> entry :
15425                        mProvidersByAuthority.entrySet()) {
15426                    PackageParser.Provider p = entry.getValue();
15427                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15428                        continue;
15429                    }
15430                    if (!printedSomething) {
15431                        if (dumpState.onTitlePrinted())
15432                            pw.println();
15433                        pw.println("ContentProvider Authorities:");
15434                        printedSomething = true;
15435                    }
15436                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15437                    pw.print("    "); pw.println(p.toString());
15438                    if (p.info != null && p.info.applicationInfo != null) {
15439                        final String appInfo = p.info.applicationInfo.toString();
15440                        pw.print("      applicationInfo="); pw.println(appInfo);
15441                    }
15442                }
15443            }
15444
15445            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15446                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15447            }
15448
15449            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15450                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15451            }
15452
15453            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15454                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15455            }
15456
15457            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15458                // XXX should handle packageName != null by dumping only install data that
15459                // the given package is involved with.
15460                if (dumpState.onTitlePrinted()) pw.println();
15461                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15462            }
15463
15464            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15465                if (dumpState.onTitlePrinted()) pw.println();
15466                mSettings.dumpReadMessagesLPr(pw, dumpState);
15467
15468                pw.println();
15469                pw.println("Package warning messages:");
15470                BufferedReader in = null;
15471                String line = null;
15472                try {
15473                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15474                    while ((line = in.readLine()) != null) {
15475                        if (line.contains("ignored: updated version")) continue;
15476                        pw.println(line);
15477                    }
15478                } catch (IOException ignored) {
15479                } finally {
15480                    IoUtils.closeQuietly(in);
15481                }
15482            }
15483
15484            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15485                BufferedReader in = null;
15486                String line = null;
15487                try {
15488                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15489                    while ((line = in.readLine()) != null) {
15490                        if (line.contains("ignored: updated version")) continue;
15491                        pw.print("msg,");
15492                        pw.println(line);
15493                    }
15494                } catch (IOException ignored) {
15495                } finally {
15496                    IoUtils.closeQuietly(in);
15497                }
15498            }
15499        }
15500    }
15501
15502    private String dumpDomainString(String packageName) {
15503        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15504        List<IntentFilter> filters = getAllIntentFilters(packageName);
15505
15506        ArraySet<String> result = new ArraySet<>();
15507        if (iviList.size() > 0) {
15508            for (IntentFilterVerificationInfo ivi : iviList) {
15509                for (String host : ivi.getDomains()) {
15510                    result.add(host);
15511                }
15512            }
15513        }
15514        if (filters != null && filters.size() > 0) {
15515            for (IntentFilter filter : filters) {
15516                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15517                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15518                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15519                    result.addAll(filter.getHostsList());
15520                }
15521            }
15522        }
15523
15524        StringBuilder sb = new StringBuilder(result.size() * 16);
15525        for (String domain : result) {
15526            if (sb.length() > 0) sb.append(" ");
15527            sb.append(domain);
15528        }
15529        return sb.toString();
15530    }
15531
15532    // ------- apps on sdcard specific code -------
15533    static final boolean DEBUG_SD_INSTALL = false;
15534
15535    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15536
15537    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15538
15539    private boolean mMediaMounted = false;
15540
15541    static String getEncryptKey() {
15542        try {
15543            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15544                    SD_ENCRYPTION_KEYSTORE_NAME);
15545            if (sdEncKey == null) {
15546                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15547                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15548                if (sdEncKey == null) {
15549                    Slog.e(TAG, "Failed to create encryption keys");
15550                    return null;
15551                }
15552            }
15553            return sdEncKey;
15554        } catch (NoSuchAlgorithmException nsae) {
15555            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15556            return null;
15557        } catch (IOException ioe) {
15558            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15559            return null;
15560        }
15561    }
15562
15563    /*
15564     * Update media status on PackageManager.
15565     */
15566    @Override
15567    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15568        int callingUid = Binder.getCallingUid();
15569        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15570            throw new SecurityException("Media status can only be updated by the system");
15571        }
15572        // reader; this apparently protects mMediaMounted, but should probably
15573        // be a different lock in that case.
15574        synchronized (mPackages) {
15575            Log.i(TAG, "Updating external media status from "
15576                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15577                    + (mediaStatus ? "mounted" : "unmounted"));
15578            if (DEBUG_SD_INSTALL)
15579                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15580                        + ", mMediaMounted=" + mMediaMounted);
15581            if (mediaStatus == mMediaMounted) {
15582                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15583                        : 0, -1);
15584                mHandler.sendMessage(msg);
15585                return;
15586            }
15587            mMediaMounted = mediaStatus;
15588        }
15589        // Queue up an async operation since the package installation may take a
15590        // little while.
15591        mHandler.post(new Runnable() {
15592            public void run() {
15593                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15594            }
15595        });
15596    }
15597
15598    /**
15599     * Called by MountService when the initial ASECs to scan are available.
15600     * Should block until all the ASEC containers are finished being scanned.
15601     */
15602    public void scanAvailableAsecs() {
15603        updateExternalMediaStatusInner(true, false, false);
15604        if (mShouldRestoreconData) {
15605            SELinuxMMAC.setRestoreconDone();
15606            mShouldRestoreconData = false;
15607        }
15608    }
15609
15610    /*
15611     * Collect information of applications on external media, map them against
15612     * existing containers and update information based on current mount status.
15613     * Please note that we always have to report status if reportStatus has been
15614     * set to true especially when unloading packages.
15615     */
15616    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15617            boolean externalStorage) {
15618        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15619        int[] uidArr = EmptyArray.INT;
15620
15621        final String[] list = PackageHelper.getSecureContainerList();
15622        if (ArrayUtils.isEmpty(list)) {
15623            Log.i(TAG, "No secure containers found");
15624        } else {
15625            // Process list of secure containers and categorize them
15626            // as active or stale based on their package internal state.
15627
15628            // reader
15629            synchronized (mPackages) {
15630                for (String cid : list) {
15631                    // Leave stages untouched for now; installer service owns them
15632                    if (PackageInstallerService.isStageName(cid)) continue;
15633
15634                    if (DEBUG_SD_INSTALL)
15635                        Log.i(TAG, "Processing container " + cid);
15636                    String pkgName = getAsecPackageName(cid);
15637                    if (pkgName == null) {
15638                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15639                        continue;
15640                    }
15641                    if (DEBUG_SD_INSTALL)
15642                        Log.i(TAG, "Looking for pkg : " + pkgName);
15643
15644                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15645                    if (ps == null) {
15646                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15647                        continue;
15648                    }
15649
15650                    /*
15651                     * Skip packages that are not external if we're unmounting
15652                     * external storage.
15653                     */
15654                    if (externalStorage && !isMounted && !isExternal(ps)) {
15655                        continue;
15656                    }
15657
15658                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15659                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15660                    // The package status is changed only if the code path
15661                    // matches between settings and the container id.
15662                    if (ps.codePathString != null
15663                            && ps.codePathString.startsWith(args.getCodePath())) {
15664                        if (DEBUG_SD_INSTALL) {
15665                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15666                                    + " at code path: " + ps.codePathString);
15667                        }
15668
15669                        // We do have a valid package installed on sdcard
15670                        processCids.put(args, ps.codePathString);
15671                        final int uid = ps.appId;
15672                        if (uid != -1) {
15673                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15674                        }
15675                    } else {
15676                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15677                                + ps.codePathString);
15678                    }
15679                }
15680            }
15681
15682            Arrays.sort(uidArr);
15683        }
15684
15685        // Process packages with valid entries.
15686        if (isMounted) {
15687            if (DEBUG_SD_INSTALL)
15688                Log.i(TAG, "Loading packages");
15689            loadMediaPackages(processCids, uidArr);
15690            startCleaningPackages();
15691            mInstallerService.onSecureContainersAvailable();
15692        } else {
15693            if (DEBUG_SD_INSTALL)
15694                Log.i(TAG, "Unloading packages");
15695            unloadMediaPackages(processCids, uidArr, reportStatus);
15696        }
15697    }
15698
15699    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15700            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15701        final int size = infos.size();
15702        final String[] packageNames = new String[size];
15703        final int[] packageUids = new int[size];
15704        for (int i = 0; i < size; i++) {
15705            final ApplicationInfo info = infos.get(i);
15706            packageNames[i] = info.packageName;
15707            packageUids[i] = info.uid;
15708        }
15709        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15710                finishedReceiver);
15711    }
15712
15713    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15714            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15715        sendResourcesChangedBroadcast(mediaStatus, replacing,
15716                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15717    }
15718
15719    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15720            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15721        int size = pkgList.length;
15722        if (size > 0) {
15723            // Send broadcasts here
15724            Bundle extras = new Bundle();
15725            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15726            if (uidArr != null) {
15727                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15728            }
15729            if (replacing) {
15730                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15731            }
15732            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15733                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15734            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15735        }
15736    }
15737
15738   /*
15739     * Look at potentially valid container ids from processCids If package
15740     * information doesn't match the one on record or package scanning fails,
15741     * the cid is added to list of removeCids. We currently don't delete stale
15742     * containers.
15743     */
15744    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15745        ArrayList<String> pkgList = new ArrayList<String>();
15746        Set<AsecInstallArgs> keys = processCids.keySet();
15747
15748        for (AsecInstallArgs args : keys) {
15749            String codePath = processCids.get(args);
15750            if (DEBUG_SD_INSTALL)
15751                Log.i(TAG, "Loading container : " + args.cid);
15752            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15753            try {
15754                // Make sure there are no container errors first.
15755                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15756                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15757                            + " when installing from sdcard");
15758                    continue;
15759                }
15760                // Check code path here.
15761                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15762                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15763                            + " does not match one in settings " + codePath);
15764                    continue;
15765                }
15766                // Parse package
15767                int parseFlags = mDefParseFlags;
15768                if (args.isExternalAsec()) {
15769                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15770                }
15771                if (args.isFwdLocked()) {
15772                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15773                }
15774
15775                synchronized (mInstallLock) {
15776                    PackageParser.Package pkg = null;
15777                    try {
15778                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15779                    } catch (PackageManagerException e) {
15780                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15781                    }
15782                    // Scan the package
15783                    if (pkg != null) {
15784                        /*
15785                         * TODO why is the lock being held? doPostInstall is
15786                         * called in other places without the lock. This needs
15787                         * to be straightened out.
15788                         */
15789                        // writer
15790                        synchronized (mPackages) {
15791                            retCode = PackageManager.INSTALL_SUCCEEDED;
15792                            pkgList.add(pkg.packageName);
15793                            // Post process args
15794                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15795                                    pkg.applicationInfo.uid);
15796                        }
15797                    } else {
15798                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15799                    }
15800                }
15801
15802            } finally {
15803                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15804                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15805                }
15806            }
15807        }
15808        // writer
15809        synchronized (mPackages) {
15810            // If the platform SDK has changed since the last time we booted,
15811            // we need to re-grant app permission to catch any new ones that
15812            // appear. This is really a hack, and means that apps can in some
15813            // cases get permissions that the user didn't initially explicitly
15814            // allow... it would be nice to have some better way to handle
15815            // this situation.
15816            final VersionInfo ver = mSettings.getExternalVersion();
15817
15818            int updateFlags = UPDATE_PERMISSIONS_ALL;
15819            if (ver.sdkVersion != mSdkVersion) {
15820                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15821                        + mSdkVersion + "; regranting permissions for external");
15822                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15823            }
15824            updatePermissionsLPw(null, null, updateFlags);
15825
15826            // Yay, everything is now upgraded
15827            ver.forceCurrent();
15828
15829            // can downgrade to reader
15830            // Persist settings
15831            mSettings.writeLPr();
15832        }
15833        // Send a broadcast to let everyone know we are done processing
15834        if (pkgList.size() > 0) {
15835            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15836        }
15837    }
15838
15839   /*
15840     * Utility method to unload a list of specified containers
15841     */
15842    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15843        // Just unmount all valid containers.
15844        for (AsecInstallArgs arg : cidArgs) {
15845            synchronized (mInstallLock) {
15846                arg.doPostDeleteLI(false);
15847           }
15848       }
15849   }
15850
15851    /*
15852     * Unload packages mounted on external media. This involves deleting package
15853     * data from internal structures, sending broadcasts about diabled packages,
15854     * gc'ing to free up references, unmounting all secure containers
15855     * corresponding to packages on external media, and posting a
15856     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15857     * that we always have to post this message if status has been requested no
15858     * matter what.
15859     */
15860    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15861            final boolean reportStatus) {
15862        if (DEBUG_SD_INSTALL)
15863            Log.i(TAG, "unloading media packages");
15864        ArrayList<String> pkgList = new ArrayList<String>();
15865        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15866        final Set<AsecInstallArgs> keys = processCids.keySet();
15867        for (AsecInstallArgs args : keys) {
15868            String pkgName = args.getPackageName();
15869            if (DEBUG_SD_INSTALL)
15870                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15871            // Delete package internally
15872            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15873            synchronized (mInstallLock) {
15874                boolean res = deletePackageLI(pkgName, null, false, null, null,
15875                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15876                if (res) {
15877                    pkgList.add(pkgName);
15878                } else {
15879                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15880                    failedList.add(args);
15881                }
15882            }
15883        }
15884
15885        // reader
15886        synchronized (mPackages) {
15887            // We didn't update the settings after removing each package;
15888            // write them now for all packages.
15889            mSettings.writeLPr();
15890        }
15891
15892        // We have to absolutely send UPDATED_MEDIA_STATUS only
15893        // after confirming that all the receivers processed the ordered
15894        // broadcast when packages get disabled, force a gc to clean things up.
15895        // and unload all the containers.
15896        if (pkgList.size() > 0) {
15897            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15898                    new IIntentReceiver.Stub() {
15899                public void performReceive(Intent intent, int resultCode, String data,
15900                        Bundle extras, boolean ordered, boolean sticky,
15901                        int sendingUser) throws RemoteException {
15902                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15903                            reportStatus ? 1 : 0, 1, keys);
15904                    mHandler.sendMessage(msg);
15905                }
15906            });
15907        } else {
15908            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15909                    keys);
15910            mHandler.sendMessage(msg);
15911        }
15912    }
15913
15914    private void loadPrivatePackages(final VolumeInfo vol) {
15915        mHandler.post(new Runnable() {
15916            @Override
15917            public void run() {
15918                loadPrivatePackagesInner(vol);
15919            }
15920        });
15921    }
15922
15923    private void loadPrivatePackagesInner(VolumeInfo vol) {
15924        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15925        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15926
15927        final VersionInfo ver;
15928        final List<PackageSetting> packages;
15929        synchronized (mPackages) {
15930            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15931            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15932        }
15933
15934        for (PackageSetting ps : packages) {
15935            synchronized (mInstallLock) {
15936                final PackageParser.Package pkg;
15937                try {
15938                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15939                    loaded.add(pkg.applicationInfo);
15940                } catch (PackageManagerException e) {
15941                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15942                }
15943
15944                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15945                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15946                }
15947            }
15948        }
15949
15950        synchronized (mPackages) {
15951            int updateFlags = UPDATE_PERMISSIONS_ALL;
15952            if (ver.sdkVersion != mSdkVersion) {
15953                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15954                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15955                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15956            }
15957            updatePermissionsLPw(null, null, updateFlags);
15958
15959            // Yay, everything is now upgraded
15960            ver.forceCurrent();
15961
15962            mSettings.writeLPr();
15963        }
15964
15965        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15966        sendResourcesChangedBroadcast(true, false, loaded, null);
15967    }
15968
15969    private void unloadPrivatePackages(final VolumeInfo vol) {
15970        mHandler.post(new Runnable() {
15971            @Override
15972            public void run() {
15973                unloadPrivatePackagesInner(vol);
15974            }
15975        });
15976    }
15977
15978    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15979        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15980        synchronized (mInstallLock) {
15981        synchronized (mPackages) {
15982            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15983            for (PackageSetting ps : packages) {
15984                if (ps.pkg == null) continue;
15985
15986                final ApplicationInfo info = ps.pkg.applicationInfo;
15987                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15988                if (deletePackageLI(ps.name, null, false, null, null,
15989                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15990                    unloaded.add(info);
15991                } else {
15992                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15993                }
15994            }
15995
15996            mSettings.writeLPr();
15997        }
15998        }
15999
16000        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16001        sendResourcesChangedBroadcast(false, false, unloaded, null);
16002    }
16003
16004    /**
16005     * Examine all users present on given mounted volume, and destroy data
16006     * belonging to users that are no longer valid, or whose user ID has been
16007     * recycled.
16008     */
16009    private void reconcileUsers(String volumeUuid) {
16010        final File[] files = FileUtils
16011                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16012        for (File file : files) {
16013            if (!file.isDirectory()) continue;
16014
16015            final int userId;
16016            final UserInfo info;
16017            try {
16018                userId = Integer.parseInt(file.getName());
16019                info = sUserManager.getUserInfo(userId);
16020            } catch (NumberFormatException e) {
16021                Slog.w(TAG, "Invalid user directory " + file);
16022                continue;
16023            }
16024
16025            boolean destroyUser = false;
16026            if (info == null) {
16027                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16028                        + " because no matching user was found");
16029                destroyUser = true;
16030            } else {
16031                try {
16032                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16033                } catch (IOException e) {
16034                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16035                            + " because we failed to enforce serial number: " + e);
16036                    destroyUser = true;
16037                }
16038            }
16039
16040            if (destroyUser) {
16041                synchronized (mInstallLock) {
16042                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16043                }
16044            }
16045        }
16046
16047        final UserManager um = mContext.getSystemService(UserManager.class);
16048        for (UserInfo user : um.getUsers()) {
16049            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16050            if (userDir.exists()) continue;
16051
16052            try {
16053                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
16054                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16055            } catch (IOException e) {
16056                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16057            }
16058        }
16059    }
16060
16061    /**
16062     * Examine all apps present on given mounted volume, and destroy apps that
16063     * aren't expected, either due to uninstallation or reinstallation on
16064     * another volume.
16065     */
16066    private void reconcileApps(String volumeUuid) {
16067        final File[] files = FileUtils
16068                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16069        for (File file : files) {
16070            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16071                    && !PackageInstallerService.isStageName(file.getName());
16072            if (!isPackage) {
16073                // Ignore entries which are not packages
16074                continue;
16075            }
16076
16077            boolean destroyApp = false;
16078            String packageName = null;
16079            try {
16080                final PackageLite pkg = PackageParser.parsePackageLite(file,
16081                        PackageParser.PARSE_MUST_BE_APK);
16082                packageName = pkg.packageName;
16083
16084                synchronized (mPackages) {
16085                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16086                    if (ps == null) {
16087                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16088                                + volumeUuid + " because we found no install record");
16089                        destroyApp = true;
16090                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16091                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16092                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16093                        destroyApp = true;
16094                    }
16095                }
16096
16097            } catch (PackageParserException e) {
16098                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16099                destroyApp = true;
16100            }
16101
16102            if (destroyApp) {
16103                synchronized (mInstallLock) {
16104                    if (packageName != null) {
16105                        removeDataDirsLI(volumeUuid, packageName);
16106                    }
16107                    if (file.isDirectory()) {
16108                        mInstaller.rmPackageDir(file.getAbsolutePath());
16109                    } else {
16110                        file.delete();
16111                    }
16112                }
16113            }
16114        }
16115    }
16116
16117    private void unfreezePackage(String packageName) {
16118        synchronized (mPackages) {
16119            final PackageSetting ps = mSettings.mPackages.get(packageName);
16120            if (ps != null) {
16121                ps.frozen = false;
16122            }
16123        }
16124    }
16125
16126    @Override
16127    public int movePackage(final String packageName, final String volumeUuid) {
16128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16129
16130        final int moveId = mNextMoveId.getAndIncrement();
16131        try {
16132            movePackageInternal(packageName, volumeUuid, moveId);
16133        } catch (PackageManagerException e) {
16134            Slog.w(TAG, "Failed to move " + packageName, e);
16135            mMoveCallbacks.notifyStatusChanged(moveId,
16136                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16137        }
16138        return moveId;
16139    }
16140
16141    private void movePackageInternal(final String packageName, final String volumeUuid,
16142            final int moveId) throws PackageManagerException {
16143        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16144        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16145        final PackageManager pm = mContext.getPackageManager();
16146
16147        final boolean currentAsec;
16148        final String currentVolumeUuid;
16149        final File codeFile;
16150        final String installerPackageName;
16151        final String packageAbiOverride;
16152        final int appId;
16153        final String seinfo;
16154        final String label;
16155
16156        // reader
16157        synchronized (mPackages) {
16158            final PackageParser.Package pkg = mPackages.get(packageName);
16159            final PackageSetting ps = mSettings.mPackages.get(packageName);
16160            if (pkg == null || ps == null) {
16161                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16162            }
16163
16164            if (pkg.applicationInfo.isSystemApp()) {
16165                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16166                        "Cannot move system application");
16167            }
16168
16169            if (pkg.applicationInfo.isExternalAsec()) {
16170                currentAsec = true;
16171                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16172            } else if (pkg.applicationInfo.isForwardLocked()) {
16173                currentAsec = true;
16174                currentVolumeUuid = "forward_locked";
16175            } else {
16176                currentAsec = false;
16177                currentVolumeUuid = ps.volumeUuid;
16178
16179                final File probe = new File(pkg.codePath);
16180                final File probeOat = new File(probe, "oat");
16181                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16182                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16183                            "Move only supported for modern cluster style installs");
16184                }
16185            }
16186
16187            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16188                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16189                        "Package already moved to " + volumeUuid);
16190            }
16191
16192            if (ps.frozen) {
16193                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16194                        "Failed to move already frozen package");
16195            }
16196            ps.frozen = true;
16197
16198            codeFile = new File(pkg.codePath);
16199            installerPackageName = ps.installerPackageName;
16200            packageAbiOverride = ps.cpuAbiOverrideString;
16201            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16202            seinfo = pkg.applicationInfo.seinfo;
16203            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16204        }
16205
16206        // Now that we're guarded by frozen state, kill app during move
16207        final long token = Binder.clearCallingIdentity();
16208        try {
16209            killApplication(packageName, appId, "move pkg");
16210        } finally {
16211            Binder.restoreCallingIdentity(token);
16212        }
16213
16214        final Bundle extras = new Bundle();
16215        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16216        extras.putString(Intent.EXTRA_TITLE, label);
16217        mMoveCallbacks.notifyCreated(moveId, extras);
16218
16219        int installFlags;
16220        final boolean moveCompleteApp;
16221        final File measurePath;
16222
16223        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16224            installFlags = INSTALL_INTERNAL;
16225            moveCompleteApp = !currentAsec;
16226            measurePath = Environment.getDataAppDirectory(volumeUuid);
16227        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16228            installFlags = INSTALL_EXTERNAL;
16229            moveCompleteApp = false;
16230            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16231        } else {
16232            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16233            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16234                    || !volume.isMountedWritable()) {
16235                unfreezePackage(packageName);
16236                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16237                        "Move location not mounted private volume");
16238            }
16239
16240            Preconditions.checkState(!currentAsec);
16241
16242            installFlags = INSTALL_INTERNAL;
16243            moveCompleteApp = true;
16244            measurePath = Environment.getDataAppDirectory(volumeUuid);
16245        }
16246
16247        final PackageStats stats = new PackageStats(null, -1);
16248        synchronized (mInstaller) {
16249            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16250                unfreezePackage(packageName);
16251                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16252                        "Failed to measure package size");
16253            }
16254        }
16255
16256        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16257                + stats.dataSize);
16258
16259        final long startFreeBytes = measurePath.getFreeSpace();
16260        final long sizeBytes;
16261        if (moveCompleteApp) {
16262            sizeBytes = stats.codeSize + stats.dataSize;
16263        } else {
16264            sizeBytes = stats.codeSize;
16265        }
16266
16267        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16268            unfreezePackage(packageName);
16269            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16270                    "Not enough free space to move");
16271        }
16272
16273        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16274
16275        final CountDownLatch installedLatch = new CountDownLatch(1);
16276        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16277            @Override
16278            public void onUserActionRequired(Intent intent) throws RemoteException {
16279                throw new IllegalStateException();
16280            }
16281
16282            @Override
16283            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16284                    Bundle extras) throws RemoteException {
16285                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16286                        + PackageManager.installStatusToString(returnCode, msg));
16287
16288                installedLatch.countDown();
16289
16290                // Regardless of success or failure of the move operation,
16291                // always unfreeze the package
16292                unfreezePackage(packageName);
16293
16294                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16295                switch (status) {
16296                    case PackageInstaller.STATUS_SUCCESS:
16297                        mMoveCallbacks.notifyStatusChanged(moveId,
16298                                PackageManager.MOVE_SUCCEEDED);
16299                        break;
16300                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16301                        mMoveCallbacks.notifyStatusChanged(moveId,
16302                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16303                        break;
16304                    default:
16305                        mMoveCallbacks.notifyStatusChanged(moveId,
16306                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16307                        break;
16308                }
16309            }
16310        };
16311
16312        final MoveInfo move;
16313        if (moveCompleteApp) {
16314            // Kick off a thread to report progress estimates
16315            new Thread() {
16316                @Override
16317                public void run() {
16318                    while (true) {
16319                        try {
16320                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16321                                break;
16322                            }
16323                        } catch (InterruptedException ignored) {
16324                        }
16325
16326                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16327                        final int progress = 10 + (int) MathUtils.constrain(
16328                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16329                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16330                    }
16331                }
16332            }.start();
16333
16334            final String dataAppName = codeFile.getName();
16335            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16336                    dataAppName, appId, seinfo);
16337        } else {
16338            move = null;
16339        }
16340
16341        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16342
16343        final Message msg = mHandler.obtainMessage(INIT_COPY);
16344        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16345        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16346                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16347        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16348        msg.obj = params;
16349
16350        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16351                System.identityHashCode(msg.obj));
16352        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16353                System.identityHashCode(msg.obj));
16354
16355        mHandler.sendMessage(msg);
16356    }
16357
16358    @Override
16359    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16360        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16361
16362        final int realMoveId = mNextMoveId.getAndIncrement();
16363        final Bundle extras = new Bundle();
16364        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16365        mMoveCallbacks.notifyCreated(realMoveId, extras);
16366
16367        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16368            @Override
16369            public void onCreated(int moveId, Bundle extras) {
16370                // Ignored
16371            }
16372
16373            @Override
16374            public void onStatusChanged(int moveId, int status, long estMillis) {
16375                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16376            }
16377        };
16378
16379        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16380        storage.setPrimaryStorageUuid(volumeUuid, callback);
16381        return realMoveId;
16382    }
16383
16384    @Override
16385    public int getMoveStatus(int moveId) {
16386        mContext.enforceCallingOrSelfPermission(
16387                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16388        return mMoveCallbacks.mLastStatus.get(moveId);
16389    }
16390
16391    @Override
16392    public void registerMoveCallback(IPackageMoveObserver callback) {
16393        mContext.enforceCallingOrSelfPermission(
16394                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16395        mMoveCallbacks.register(callback);
16396    }
16397
16398    @Override
16399    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16400        mContext.enforceCallingOrSelfPermission(
16401                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16402        mMoveCallbacks.unregister(callback);
16403    }
16404
16405    @Override
16406    public boolean setInstallLocation(int loc) {
16407        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16408                null);
16409        if (getInstallLocation() == loc) {
16410            return true;
16411        }
16412        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16413                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16414            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16415                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16416            return true;
16417        }
16418        return false;
16419   }
16420
16421    @Override
16422    public int getInstallLocation() {
16423        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16424                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16425                PackageHelper.APP_INSTALL_AUTO);
16426    }
16427
16428    /** Called by UserManagerService */
16429    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16430        mDirtyUsers.remove(userHandle);
16431        mSettings.removeUserLPw(userHandle);
16432        mPendingBroadcasts.remove(userHandle);
16433        if (mInstaller != null) {
16434            // Technically, we shouldn't be doing this with the package lock
16435            // held.  However, this is very rare, and there is already so much
16436            // other disk I/O going on, that we'll let it slide for now.
16437            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16438            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16439                final String volumeUuid = vol.getFsUuid();
16440                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16441                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16442            }
16443        }
16444        mUserNeedsBadging.delete(userHandle);
16445        removeUnusedPackagesLILPw(userManager, userHandle);
16446    }
16447
16448    /**
16449     * We're removing userHandle and would like to remove any downloaded packages
16450     * that are no longer in use by any other user.
16451     * @param userHandle the user being removed
16452     */
16453    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16454        final boolean DEBUG_CLEAN_APKS = false;
16455        int [] users = userManager.getUserIdsLPr();
16456        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16457        while (psit.hasNext()) {
16458            PackageSetting ps = psit.next();
16459            if (ps.pkg == null) {
16460                continue;
16461            }
16462            final String packageName = ps.pkg.packageName;
16463            // Skip over if system app
16464            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16465                continue;
16466            }
16467            if (DEBUG_CLEAN_APKS) {
16468                Slog.i(TAG, "Checking package " + packageName);
16469            }
16470            boolean keep = false;
16471            for (int i = 0; i < users.length; i++) {
16472                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16473                    keep = true;
16474                    if (DEBUG_CLEAN_APKS) {
16475                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16476                                + users[i]);
16477                    }
16478                    break;
16479                }
16480            }
16481            if (!keep) {
16482                if (DEBUG_CLEAN_APKS) {
16483                    Slog.i(TAG, "  Removing package " + packageName);
16484                }
16485                mHandler.post(new Runnable() {
16486                    public void run() {
16487                        deletePackageX(packageName, userHandle, 0);
16488                    } //end run
16489                });
16490            }
16491        }
16492    }
16493
16494    /** Called by UserManagerService */
16495    void createNewUserLILPw(int userHandle) {
16496        if (mInstaller != null) {
16497            mInstaller.createUserConfig(userHandle);
16498            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16499            applyFactoryDefaultBrowserLPw(userHandle);
16500            primeDomainVerificationsLPw(userHandle);
16501        }
16502    }
16503
16504    void newUserCreated(final int userHandle) {
16505        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16506    }
16507
16508    @Override
16509    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16510        mContext.enforceCallingOrSelfPermission(
16511                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16512                "Only package verification agents can read the verifier device identity");
16513
16514        synchronized (mPackages) {
16515            return mSettings.getVerifierDeviceIdentityLPw();
16516        }
16517    }
16518
16519    @Override
16520    public void setPermissionEnforced(String permission, boolean enforced) {
16521        // TODO: Now that we no longer change GID for storage, this should to away.
16522        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16523                "setPermissionEnforced");
16524        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16525            synchronized (mPackages) {
16526                if (mSettings.mReadExternalStorageEnforced == null
16527                        || mSettings.mReadExternalStorageEnforced != enforced) {
16528                    mSettings.mReadExternalStorageEnforced = enforced;
16529                    mSettings.writeLPr();
16530                }
16531            }
16532            // kill any non-foreground processes so we restart them and
16533            // grant/revoke the GID.
16534            final IActivityManager am = ActivityManagerNative.getDefault();
16535            if (am != null) {
16536                final long token = Binder.clearCallingIdentity();
16537                try {
16538                    am.killProcessesBelowForeground("setPermissionEnforcement");
16539                } catch (RemoteException e) {
16540                } finally {
16541                    Binder.restoreCallingIdentity(token);
16542                }
16543            }
16544        } else {
16545            throw new IllegalArgumentException("No selective enforcement for " + permission);
16546        }
16547    }
16548
16549    @Override
16550    @Deprecated
16551    public boolean isPermissionEnforced(String permission) {
16552        return true;
16553    }
16554
16555    @Override
16556    public boolean isStorageLow() {
16557        final long token = Binder.clearCallingIdentity();
16558        try {
16559            final DeviceStorageMonitorInternal
16560                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16561            if (dsm != null) {
16562                return dsm.isMemoryLow();
16563            } else {
16564                return false;
16565            }
16566        } finally {
16567            Binder.restoreCallingIdentity(token);
16568        }
16569    }
16570
16571    @Override
16572    public IPackageInstaller getPackageInstaller() {
16573        return mInstallerService;
16574    }
16575
16576    private boolean userNeedsBadging(int userId) {
16577        int index = mUserNeedsBadging.indexOfKey(userId);
16578        if (index < 0) {
16579            final UserInfo userInfo;
16580            final long token = Binder.clearCallingIdentity();
16581            try {
16582                userInfo = sUserManager.getUserInfo(userId);
16583            } finally {
16584                Binder.restoreCallingIdentity(token);
16585            }
16586            final boolean b;
16587            if (userInfo != null && userInfo.isManagedProfile()) {
16588                b = true;
16589            } else {
16590                b = false;
16591            }
16592            mUserNeedsBadging.put(userId, b);
16593            return b;
16594        }
16595        return mUserNeedsBadging.valueAt(index);
16596    }
16597
16598    @Override
16599    public KeySet getKeySetByAlias(String packageName, String alias) {
16600        if (packageName == null || alias == null) {
16601            return null;
16602        }
16603        synchronized(mPackages) {
16604            final PackageParser.Package pkg = mPackages.get(packageName);
16605            if (pkg == null) {
16606                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16607                throw new IllegalArgumentException("Unknown package: " + packageName);
16608            }
16609            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16610            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16611        }
16612    }
16613
16614    @Override
16615    public KeySet getSigningKeySet(String packageName) {
16616        if (packageName == null) {
16617            return null;
16618        }
16619        synchronized(mPackages) {
16620            final PackageParser.Package pkg = mPackages.get(packageName);
16621            if (pkg == null) {
16622                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16623                throw new IllegalArgumentException("Unknown package: " + packageName);
16624            }
16625            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16626                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16627                throw new SecurityException("May not access signing KeySet of other apps.");
16628            }
16629            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16630            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16631        }
16632    }
16633
16634    @Override
16635    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16636        if (packageName == null || ks == null) {
16637            return false;
16638        }
16639        synchronized(mPackages) {
16640            final PackageParser.Package pkg = mPackages.get(packageName);
16641            if (pkg == null) {
16642                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16643                throw new IllegalArgumentException("Unknown package: " + packageName);
16644            }
16645            IBinder ksh = ks.getToken();
16646            if (ksh instanceof KeySetHandle) {
16647                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16648                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16649            }
16650            return false;
16651        }
16652    }
16653
16654    @Override
16655    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16656        if (packageName == null || ks == null) {
16657            return false;
16658        }
16659        synchronized(mPackages) {
16660            final PackageParser.Package pkg = mPackages.get(packageName);
16661            if (pkg == null) {
16662                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16663                throw new IllegalArgumentException("Unknown package: " + packageName);
16664            }
16665            IBinder ksh = ks.getToken();
16666            if (ksh instanceof KeySetHandle) {
16667                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16668                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16669            }
16670            return false;
16671        }
16672    }
16673
16674    public void getUsageStatsIfNoPackageUsageInfo() {
16675        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16676            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16677            if (usm == null) {
16678                throw new IllegalStateException("UsageStatsManager must be initialized");
16679            }
16680            long now = System.currentTimeMillis();
16681            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16682            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16683                String packageName = entry.getKey();
16684                PackageParser.Package pkg = mPackages.get(packageName);
16685                if (pkg == null) {
16686                    continue;
16687                }
16688                UsageStats usage = entry.getValue();
16689                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16690                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16691            }
16692        }
16693    }
16694
16695    /**
16696     * Check and throw if the given before/after packages would be considered a
16697     * downgrade.
16698     */
16699    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16700            throws PackageManagerException {
16701        if (after.versionCode < before.mVersionCode) {
16702            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16703                    "Update version code " + after.versionCode + " is older than current "
16704                    + before.mVersionCode);
16705        } else if (after.versionCode == before.mVersionCode) {
16706            if (after.baseRevisionCode < before.baseRevisionCode) {
16707                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16708                        "Update base revision code " + after.baseRevisionCode
16709                        + " is older than current " + before.baseRevisionCode);
16710            }
16711
16712            if (!ArrayUtils.isEmpty(after.splitNames)) {
16713                for (int i = 0; i < after.splitNames.length; i++) {
16714                    final String splitName = after.splitNames[i];
16715                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16716                    if (j != -1) {
16717                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16718                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16719                                    "Update split " + splitName + " revision code "
16720                                    + after.splitRevisionCodes[i] + " is older than current "
16721                                    + before.splitRevisionCodes[j]);
16722                        }
16723                    }
16724                }
16725            }
16726        }
16727    }
16728
16729    private static class MoveCallbacks extends Handler {
16730        private static final int MSG_CREATED = 1;
16731        private static final int MSG_STATUS_CHANGED = 2;
16732
16733        private final RemoteCallbackList<IPackageMoveObserver>
16734                mCallbacks = new RemoteCallbackList<>();
16735
16736        private final SparseIntArray mLastStatus = new SparseIntArray();
16737
16738        public MoveCallbacks(Looper looper) {
16739            super(looper);
16740        }
16741
16742        public void register(IPackageMoveObserver callback) {
16743            mCallbacks.register(callback);
16744        }
16745
16746        public void unregister(IPackageMoveObserver callback) {
16747            mCallbacks.unregister(callback);
16748        }
16749
16750        @Override
16751        public void handleMessage(Message msg) {
16752            final SomeArgs args = (SomeArgs) msg.obj;
16753            final int n = mCallbacks.beginBroadcast();
16754            for (int i = 0; i < n; i++) {
16755                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16756                try {
16757                    invokeCallback(callback, msg.what, args);
16758                } catch (RemoteException ignored) {
16759                }
16760            }
16761            mCallbacks.finishBroadcast();
16762            args.recycle();
16763        }
16764
16765        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16766                throws RemoteException {
16767            switch (what) {
16768                case MSG_CREATED: {
16769                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16770                    break;
16771                }
16772                case MSG_STATUS_CHANGED: {
16773                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16774                    break;
16775                }
16776            }
16777        }
16778
16779        private void notifyCreated(int moveId, Bundle extras) {
16780            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16781
16782            final SomeArgs args = SomeArgs.obtain();
16783            args.argi1 = moveId;
16784            args.arg2 = extras;
16785            obtainMessage(MSG_CREATED, args).sendToTarget();
16786        }
16787
16788        private void notifyStatusChanged(int moveId, int status) {
16789            notifyStatusChanged(moveId, status, -1);
16790        }
16791
16792        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16793            Slog.v(TAG, "Move " + moveId + " status " + status);
16794
16795            final SomeArgs args = SomeArgs.obtain();
16796            args.argi1 = moveId;
16797            args.argi2 = status;
16798            args.arg3 = estMillis;
16799            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16800
16801            synchronized (mLastStatus) {
16802                mLastStatus.put(moveId, status);
16803            }
16804        }
16805    }
16806
16807    private final class OnPermissionChangeListeners extends Handler {
16808        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16809
16810        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16811                new RemoteCallbackList<>();
16812
16813        public OnPermissionChangeListeners(Looper looper) {
16814            super(looper);
16815        }
16816
16817        @Override
16818        public void handleMessage(Message msg) {
16819            switch (msg.what) {
16820                case MSG_ON_PERMISSIONS_CHANGED: {
16821                    final int uid = msg.arg1;
16822                    handleOnPermissionsChanged(uid);
16823                } break;
16824            }
16825        }
16826
16827        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16828            mPermissionListeners.register(listener);
16829
16830        }
16831
16832        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16833            mPermissionListeners.unregister(listener);
16834        }
16835
16836        public void onPermissionsChanged(int uid) {
16837            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16838                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16839            }
16840        }
16841
16842        private void handleOnPermissionsChanged(int uid) {
16843            final int count = mPermissionListeners.beginBroadcast();
16844            try {
16845                for (int i = 0; i < count; i++) {
16846                    IOnPermissionsChangeListener callback = mPermissionListeners
16847                            .getBroadcastItem(i);
16848                    try {
16849                        callback.onPermissionsChanged(uid);
16850                    } catch (RemoteException e) {
16851                        Log.e(TAG, "Permission listener is dead", e);
16852                    }
16853                }
16854            } finally {
16855                mPermissionListeners.finishBroadcast();
16856            }
16857        }
16858    }
16859
16860    private class PackageManagerInternalImpl extends PackageManagerInternal {
16861        @Override
16862        public void setLocationPackagesProvider(PackagesProvider provider) {
16863            synchronized (mPackages) {
16864                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16865            }
16866        }
16867
16868        @Override
16869        public void setImePackagesProvider(PackagesProvider provider) {
16870            synchronized (mPackages) {
16871                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16872            }
16873        }
16874
16875        @Override
16876        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16877            synchronized (mPackages) {
16878                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16879            }
16880        }
16881
16882        @Override
16883        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16884            synchronized (mPackages) {
16885                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16886            }
16887        }
16888
16889        @Override
16890        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16891            synchronized (mPackages) {
16892                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16893            }
16894        }
16895
16896        @Override
16897        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16898            synchronized (mPackages) {
16899                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16900            }
16901        }
16902
16903        @Override
16904        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16905            synchronized (mPackages) {
16906                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16907            }
16908        }
16909
16910        @Override
16911        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16912            synchronized (mPackages) {
16913                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16914                        packageName, userId);
16915            }
16916        }
16917
16918        @Override
16919        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16920            synchronized (mPackages) {
16921                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16922                        packageName, userId);
16923            }
16924        }
16925        @Override
16926        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16927            synchronized (mPackages) {
16928                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16929                        packageName, userId);
16930            }
16931        }
16932    }
16933
16934    @Override
16935    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16936        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16937        synchronized (mPackages) {
16938            final long identity = Binder.clearCallingIdentity();
16939            try {
16940                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16941                        packageNames, userId);
16942            } finally {
16943                Binder.restoreCallingIdentity(identity);
16944            }
16945        }
16946    }
16947
16948    private static void enforceSystemOrPhoneCaller(String tag) {
16949        int callingUid = Binder.getCallingUid();
16950        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16951            throw new SecurityException(
16952                    "Cannot call " + tag + " from UID " + callingUid);
16953        }
16954    }
16955}
16956