PackageManagerService.java revision bf822d39a24b0de8228f5fc96c9ea4fcf320cbdc
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.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.pm.Settings.VersionInfo;
228import com.android.server.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277runtest -c android.content.pm.PackageManagerTests frameworks-core
278 *
279 * {@hide}
280 */
281public class PackageManagerService extends IPackageManager.Stub {
282    static final String TAG = "PackageManager";
283    static final boolean DEBUG_SETTINGS = false;
284    static final boolean DEBUG_PREFERRED = false;
285    static final boolean DEBUG_UPGRADE = false;
286    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
287    private static final boolean DEBUG_BACKUP = false;
288    private static final boolean DEBUG_INSTALL = false;
289    private static final boolean DEBUG_REMOVE = false;
290    private static final boolean DEBUG_BROADCASTS = false;
291    private static final boolean DEBUG_SHOW_INFO = false;
292    private static final boolean DEBUG_PACKAGE_INFO = false;
293    private static final boolean DEBUG_INTENT_MATCHING = false;
294    private static final boolean DEBUG_PACKAGE_SCANNING = false;
295    private static final boolean DEBUG_VERIFY = false;
296    private static final boolean DEBUG_DEXOPT = false;
297    private static final boolean DEBUG_ABI_SELECTION = false;
298
299    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
300
301    private static final int RADIO_UID = Process.PHONE_UID;
302    private static final int LOG_UID = Process.LOG_UID;
303    private static final int NFC_UID = Process.NFC_UID;
304    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
305    private static final int SHELL_UID = Process.SHELL_UID;
306
307    // Cap the size of permission trees that 3rd party apps can define
308    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
309
310    // Suffix used during package installation when copying/moving
311    // package apks to install directory.
312    private static final String INSTALL_PACKAGE_SUFFIX = "-";
313
314    static final int SCAN_NO_DEX = 1<<1;
315    static final int SCAN_FORCE_DEX = 1<<2;
316    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
317    static final int SCAN_NEW_INSTALL = 1<<4;
318    static final int SCAN_NO_PATHS = 1<<5;
319    static final int SCAN_UPDATE_TIME = 1<<6;
320    static final int SCAN_DEFER_DEX = 1<<7;
321    static final int SCAN_BOOTING = 1<<8;
322    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
323    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
324    static final int SCAN_REQUIRE_KNOWN = 1<<12;
325    static final int SCAN_MOVE = 1<<13;
326    static final int SCAN_INITIAL = 1<<14;
327
328    static final int REMOVE_CHATTY = 1<<16;
329
330    private static final int[] EMPTY_INT_ARRAY = new int[0];
331
332    /**
333     * Timeout (in milliseconds) after which the watchdog should declare that
334     * our handler thread is wedged.  The usual default for such things is one
335     * minute but we sometimes do very lengthy I/O operations on this thread,
336     * such as installing multi-gigabyte applications, so ours needs to be longer.
337     */
338    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
339
340    /**
341     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
342     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
343     * settings entry if available, otherwise we use the hardcoded default.  If it's been
344     * more than this long since the last fstrim, we force one during the boot sequence.
345     *
346     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
347     * one gets run at the next available charging+idle time.  This final mandatory
348     * no-fstrim check kicks in only of the other scheduling criteria is never met.
349     */
350    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
351
352    /**
353     * Whether verification is enabled by default.
354     */
355    private static final boolean DEFAULT_VERIFY_ENABLE = true;
356
357    /**
358     * The default maximum time to wait for the verification agent to return in
359     * milliseconds.
360     */
361    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
362
363    /**
364     * The default response for package verification timeout.
365     *
366     * This can be either PackageManager.VERIFICATION_ALLOW or
367     * PackageManager.VERIFICATION_REJECT.
368     */
369    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
370
371    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
372
373    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
374            DEFAULT_CONTAINER_PACKAGE,
375            "com.android.defcontainer.DefaultContainerService");
376
377    private static final String KILL_APP_REASON_GIDS_CHANGED =
378            "permission grant or revoke changed gids";
379
380    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
381            "permissions revoked";
382
383    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
384
385    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
386
387    /** Permission grant: not grant the permission. */
388    private static final int GRANT_DENIED = 1;
389
390    /** Permission grant: grant the permission as an install permission. */
391    private static final int GRANT_INSTALL = 2;
392
393    /** Permission grant: grant the permission as an install permission for a legacy app. */
394    private static final int GRANT_INSTALL_LEGACY = 3;
395
396    /** Permission grant: grant the permission as a runtime one. */
397    private static final int GRANT_RUNTIME = 4;
398
399    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
400    private static final int GRANT_UPGRADE = 5;
401
402    /** Canonical intent used to identify what counts as a "web browser" app */
403    private static final Intent sBrowserIntent;
404    static {
405        sBrowserIntent = new Intent();
406        sBrowserIntent.setAction(Intent.ACTION_VIEW);
407        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
408        sBrowserIntent.setData(Uri.parse("http:"));
409    }
410
411    final ServiceThread mHandlerThread;
412
413    final PackageHandler mHandler;
414
415    /**
416     * Messages for {@link #mHandler} that need to wait for system ready before
417     * being dispatched.
418     */
419    private ArrayList<Message> mPostSystemReadyMessages;
420
421    final int mSdkVersion = Build.VERSION.SDK_INT;
422
423    final Context mContext;
424    final boolean mFactoryTest;
425    final boolean mOnlyCore;
426    final boolean mLazyDexOpt;
427    final long mDexOptLRUThresholdInMills;
428    final DisplayMetrics mMetrics;
429    final int mDefParseFlags;
430    final String[] mSeparateProcesses;
431    final boolean mIsUpgrade;
432
433    // This is where all application persistent data goes.
434    final File mAppDataDir;
435
436    // This is where all application persistent data goes for secondary users.
437    final File mUserAppDataDir;
438
439    /** The location for ASEC container files on internal storage. */
440    final String mAsecInternalPath;
441
442    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
443    // LOCK HELD.  Can be called with mInstallLock held.
444    @GuardedBy("mInstallLock")
445    final Installer mInstaller;
446
447    /** Directory where installed third-party apps stored */
448    final File mAppInstallDir;
449
450    /**
451     * Directory to which applications installed internally have their
452     * 32 bit native libraries copied.
453     */
454    private File mAppLib32InstallDir;
455
456    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
457    // apps.
458    final File mDrmAppPrivateInstallDir;
459
460    // ----------------------------------------------------------------
461
462    // Lock for state used when installing and doing other long running
463    // operations.  Methods that must be called with this lock held have
464    // the suffix "LI".
465    final Object mInstallLock = new Object();
466
467    // ----------------------------------------------------------------
468
469    // Keys are String (package name), values are Package.  This also serves
470    // as the lock for the global state.  Methods that must be called with
471    // this lock held have the prefix "LP".
472    @GuardedBy("mPackages")
473    final ArrayMap<String, PackageParser.Package> mPackages =
474            new ArrayMap<String, PackageParser.Package>();
475
476    // Tracks available target package names -> overlay package paths.
477    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
478        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
479
480    /**
481     * Tracks new system packages [receiving in an OTA] that we expect to
482     * find updated user-installed versions. Keys are package name, values
483     * are package location.
484     */
485    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
486
487    final Settings mSettings;
488    boolean mRestoredSettings;
489
490    // System configuration read by SystemConfig.
491    final int[] mGlobalGids;
492    final SparseArray<ArraySet<String>> mSystemPermissions;
493    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
494
495    // If mac_permissions.xml was found for seinfo labeling.
496    boolean mFoundPolicyFile;
497
498    // If a recursive restorecon of /data/data/<pkg> is needed.
499    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
500
501    public static final class SharedLibraryEntry {
502        public final String path;
503        public final String apk;
504
505        SharedLibraryEntry(String _path, String _apk) {
506            path = _path;
507            apk = _apk;
508        }
509    }
510
511    // Currently known shared libraries.
512    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
513            new ArrayMap<String, SharedLibraryEntry>();
514
515    // All available activities, for your resolving pleasure.
516    final ActivityIntentResolver mActivities =
517            new ActivityIntentResolver();
518
519    // All available receivers, for your resolving pleasure.
520    final ActivityIntentResolver mReceivers =
521            new ActivityIntentResolver();
522
523    // All available services, for your resolving pleasure.
524    final ServiceIntentResolver mServices = new ServiceIntentResolver();
525
526    // All available providers, for your resolving pleasure.
527    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
528
529    // Mapping from provider base names (first directory in content URI codePath)
530    // to the provider information.
531    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
532            new ArrayMap<String, PackageParser.Provider>();
533
534    // Mapping from instrumentation class names to info about them.
535    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
536            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
537
538    // Mapping from permission names to info about them.
539    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
540            new ArrayMap<String, PackageParser.PermissionGroup>();
541
542    // Packages whose data we have transfered into another package, thus
543    // should no longer exist.
544    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
545
546    // Broadcast actions that are only available to the system.
547    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
548
549    /** List of packages waiting for verification. */
550    final SparseArray<PackageVerificationState> mPendingVerification
551            = new SparseArray<PackageVerificationState>();
552
553    /** Set of packages associated with each app op permission. */
554    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
555
556    final PackageInstallerService mInstallerService;
557
558    private final PackageDexOptimizer mPackageDexOptimizer;
559
560    private AtomicInteger mNextMoveId = new AtomicInteger();
561    private final MoveCallbacks mMoveCallbacks;
562
563    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
564
565    // Cache of users who need badging.
566    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
567
568    /** Token for keys in mPendingVerification. */
569    private int mPendingVerificationToken = 0;
570
571    volatile boolean mSystemReady;
572    volatile boolean mSafeMode;
573    volatile boolean mHasSystemUidErrors;
574
575    ApplicationInfo mAndroidApplication;
576    final ActivityInfo mResolveActivity = new ActivityInfo();
577    final ResolveInfo mResolveInfo = new ResolveInfo();
578    ComponentName mResolveComponentName;
579    PackageParser.Package mPlatformPackage;
580    ComponentName mCustomResolverComponentName;
581
582    boolean mResolverReplaced = false;
583
584    private final ComponentName mIntentFilterVerifierComponent;
585    private int mIntentFilterVerificationToken = 0;
586
587    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
588            = new SparseArray<IntentFilterVerificationState>();
589
590    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
591            new DefaultPermissionGrantPolicy(this);
592
593    private static class IFVerificationParams {
594        PackageParser.Package pkg;
595        boolean replacing;
596        int userId;
597        int verifierUid;
598
599        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
600                int _userId, int _verifierUid) {
601            pkg = _pkg;
602            replacing = _replacing;
603            userId = _userId;
604            replacing = _replacing;
605            verifierUid = _verifierUid;
606        }
607    }
608
609    private interface IntentFilterVerifier<T extends IntentFilter> {
610        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
611                                               T filter, String packageName);
612        void startVerifications(int userId);
613        void receiveVerificationResponse(int verificationId);
614    }
615
616    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
617        private Context mContext;
618        private ComponentName mIntentFilterVerifierComponent;
619        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
620
621        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
622            mContext = context;
623            mIntentFilterVerifierComponent = verifierComponent;
624        }
625
626        private String getDefaultScheme() {
627            return IntentFilter.SCHEME_HTTPS;
628        }
629
630        @Override
631        public void startVerifications(int userId) {
632            // Launch verifications requests
633            int count = mCurrentIntentFilterVerifications.size();
634            for (int n=0; n<count; n++) {
635                int verificationId = mCurrentIntentFilterVerifications.get(n);
636                final IntentFilterVerificationState ivs =
637                        mIntentFilterVerificationStates.get(verificationId);
638
639                String packageName = ivs.getPackageName();
640
641                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
642                final int filterCount = filters.size();
643                ArraySet<String> domainsSet = new ArraySet<>();
644                for (int m=0; m<filterCount; m++) {
645                    PackageParser.ActivityIntentInfo filter = filters.get(m);
646                    domainsSet.addAll(filter.getHostsList());
647                }
648                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
649                synchronized (mPackages) {
650                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
651                            packageName, domainsList) != null) {
652                        scheduleWriteSettingsLocked();
653                    }
654                }
655                sendVerificationRequest(userId, verificationId, ivs);
656            }
657            mCurrentIntentFilterVerifications.clear();
658        }
659
660        private void sendVerificationRequest(int userId, int verificationId,
661                IntentFilterVerificationState ivs) {
662
663            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
664            verificationIntent.putExtra(
665                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
666                    verificationId);
667            verificationIntent.putExtra(
668                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
669                    getDefaultScheme());
670            verificationIntent.putExtra(
671                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
672                    ivs.getHostsString());
673            verificationIntent.putExtra(
674                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
675                    ivs.getPackageName());
676            verificationIntent.setComponent(mIntentFilterVerifierComponent);
677            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
678
679            UserHandle user = new UserHandle(userId);
680            mContext.sendBroadcastAsUser(verificationIntent, user);
681            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
682                    "Sending IntentFilter verification broadcast");
683        }
684
685        public void receiveVerificationResponse(int verificationId) {
686            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
687
688            final boolean verified = ivs.isVerified();
689
690            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
691            final int count = filters.size();
692            if (DEBUG_DOMAIN_VERIFICATION) {
693                Slog.i(TAG, "Received verification response " + verificationId
694                        + " for " + count + " filters, verified=" + verified);
695            }
696            for (int n=0; n<count; n++) {
697                PackageParser.ActivityIntentInfo filter = filters.get(n);
698                filter.setVerified(verified);
699
700                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
701                        + " verified with result:" + verified + " and hosts:"
702                        + ivs.getHostsString());
703            }
704
705            mIntentFilterVerificationStates.remove(verificationId);
706
707            final String packageName = ivs.getPackageName();
708            IntentFilterVerificationInfo ivi = null;
709
710            synchronized (mPackages) {
711                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
712            }
713            if (ivi == null) {
714                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
715                        + verificationId + " packageName:" + packageName);
716                return;
717            }
718            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
719                    "Updating IntentFilterVerificationInfo for package " + packageName
720                            +" verificationId:" + verificationId);
721
722            synchronized (mPackages) {
723                if (verified) {
724                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
725                } else {
726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
727                }
728                scheduleWriteSettingsLocked();
729
730                final int userId = ivs.getUserId();
731                if (userId != UserHandle.USER_ALL) {
732                    final int userStatus =
733                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
734
735                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
736                    boolean needUpdate = false;
737
738                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
739                    // already been set by the User thru the Disambiguation dialog
740                    switch (userStatus) {
741                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
742                            if (verified) {
743                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
744                            } else {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
746                            }
747                            needUpdate = true;
748                            break;
749
750                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
751                            if (verified) {
752                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
753                                needUpdate = true;
754                            }
755                            break;
756
757                        default:
758                            // Nothing to do
759                    }
760
761                    if (needUpdate) {
762                        mSettings.updateIntentFilterVerificationStatusLPw(
763                                packageName, updatedStatus, userId);
764                        scheduleWritePackageRestrictionsLocked(userId);
765                    }
766                }
767            }
768        }
769
770        @Override
771        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
772                    ActivityIntentInfo filter, String packageName) {
773            if (!hasValidDomains(filter)) {
774                return false;
775            }
776            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
777            if (ivs == null) {
778                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
779                        packageName);
780            }
781            if (DEBUG_DOMAIN_VERIFICATION) {
782                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
783            }
784            ivs.addFilter(filter);
785            return true;
786        }
787
788        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
789                int userId, int verificationId, String packageName) {
790            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
791                    verifierUid, userId, packageName);
792            ivs.setPendingState();
793            synchronized (mPackages) {
794                mIntentFilterVerificationStates.append(verificationId, ivs);
795                mCurrentIntentFilterVerifications.add(verificationId);
796            }
797            return ivs;
798        }
799    }
800
801    private static boolean hasValidDomains(ActivityIntentInfo filter) {
802        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
803                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
804                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
805    }
806
807    private IntentFilterVerifier mIntentFilterVerifier;
808
809    // Set of pending broadcasts for aggregating enable/disable of components.
810    static class PendingPackageBroadcasts {
811        // for each user id, a map of <package name -> components within that package>
812        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
813
814        public PendingPackageBroadcasts() {
815            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
816        }
817
818        public ArrayList<String> get(int userId, String packageName) {
819            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
820            return packages.get(packageName);
821        }
822
823        public void put(int userId, String packageName, ArrayList<String> components) {
824            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
825            packages.put(packageName, components);
826        }
827
828        public void remove(int userId, String packageName) {
829            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
830            if (packages != null) {
831                packages.remove(packageName);
832            }
833        }
834
835        public void remove(int userId) {
836            mUidMap.remove(userId);
837        }
838
839        public int userIdCount() {
840            return mUidMap.size();
841        }
842
843        public int userIdAt(int n) {
844            return mUidMap.keyAt(n);
845        }
846
847        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
848            return mUidMap.get(userId);
849        }
850
851        public int size() {
852            // total number of pending broadcast entries across all userIds
853            int num = 0;
854            for (int i = 0; i< mUidMap.size(); i++) {
855                num += mUidMap.valueAt(i).size();
856            }
857            return num;
858        }
859
860        public void clear() {
861            mUidMap.clear();
862        }
863
864        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
865            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
866            if (map == null) {
867                map = new ArrayMap<String, ArrayList<String>>();
868                mUidMap.put(userId, map);
869            }
870            return map;
871        }
872    }
873    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
874
875    // Service Connection to remote media container service to copy
876    // package uri's from external media onto secure containers
877    // or internal storage.
878    private IMediaContainerService mContainerService = null;
879
880    static final int SEND_PENDING_BROADCAST = 1;
881    static final int MCS_BOUND = 3;
882    static final int END_COPY = 4;
883    static final int INIT_COPY = 5;
884    static final int MCS_UNBIND = 6;
885    static final int START_CLEANING_PACKAGE = 7;
886    static final int FIND_INSTALL_LOC = 8;
887    static final int POST_INSTALL = 9;
888    static final int MCS_RECONNECT = 10;
889    static final int MCS_GIVE_UP = 11;
890    static final int UPDATED_MEDIA_STATUS = 12;
891    static final int WRITE_SETTINGS = 13;
892    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
893    static final int PACKAGE_VERIFIED = 15;
894    static final int CHECK_PENDING_VERIFICATION = 16;
895    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
896    static final int INTENT_FILTER_VERIFIED = 18;
897
898    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
899
900    // Delay time in millisecs
901    static final int BROADCAST_DELAY = 10 * 1000;
902
903    static UserManagerService sUserManager;
904
905    // Stores a list of users whose package restrictions file needs to be updated
906    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
907
908    final private DefaultContainerConnection mDefContainerConn =
909            new DefaultContainerConnection();
910    class DefaultContainerConnection implements ServiceConnection {
911        public void onServiceConnected(ComponentName name, IBinder service) {
912            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
913            IMediaContainerService imcs =
914                IMediaContainerService.Stub.asInterface(service);
915            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
916        }
917
918        public void onServiceDisconnected(ComponentName name) {
919            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
920        }
921    }
922
923    // Recordkeeping of restore-after-install operations that are currently in flight
924    // between the Package Manager and the Backup Manager
925    class PostInstallData {
926        public InstallArgs args;
927        public PackageInstalledInfo res;
928
929        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
930            args = _a;
931            res = _r;
932        }
933    }
934
935    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
936    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
937
938    // XML tags for backup/restore of various bits of state
939    private static final String TAG_PREFERRED_BACKUP = "pa";
940    private static final String TAG_DEFAULT_APPS = "da";
941    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
942
943    final String mRequiredVerifierPackage;
944    final String mRequiredInstallerPackage;
945
946    private final PackageUsage mPackageUsage = new PackageUsage();
947
948    private class PackageUsage {
949        private static final int WRITE_INTERVAL
950            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
951
952        private final Object mFileLock = new Object();
953        private final AtomicLong mLastWritten = new AtomicLong(0);
954        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
955
956        private boolean mIsHistoricalPackageUsageAvailable = true;
957
958        boolean isHistoricalPackageUsageAvailable() {
959            return mIsHistoricalPackageUsageAvailable;
960        }
961
962        void write(boolean force) {
963            if (force) {
964                writeInternal();
965                return;
966            }
967            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
968                && !DEBUG_DEXOPT) {
969                return;
970            }
971            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
972                new Thread("PackageUsage_DiskWriter") {
973                    @Override
974                    public void run() {
975                        try {
976                            writeInternal();
977                        } finally {
978                            mBackgroundWriteRunning.set(false);
979                        }
980                    }
981                }.start();
982            }
983        }
984
985        private void writeInternal() {
986            synchronized (mPackages) {
987                synchronized (mFileLock) {
988                    AtomicFile file = getFile();
989                    FileOutputStream f = null;
990                    try {
991                        f = file.startWrite();
992                        BufferedOutputStream out = new BufferedOutputStream(f);
993                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
994                        StringBuilder sb = new StringBuilder();
995                        for (PackageParser.Package pkg : mPackages.values()) {
996                            if (pkg.mLastPackageUsageTimeInMills == 0) {
997                                continue;
998                            }
999                            sb.setLength(0);
1000                            sb.append(pkg.packageName);
1001                            sb.append(' ');
1002                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1003                            sb.append('\n');
1004                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1005                        }
1006                        out.flush();
1007                        file.finishWrite(f);
1008                    } catch (IOException e) {
1009                        if (f != null) {
1010                            file.failWrite(f);
1011                        }
1012                        Log.e(TAG, "Failed to write package usage times", e);
1013                    }
1014                }
1015            }
1016            mLastWritten.set(SystemClock.elapsedRealtime());
1017        }
1018
1019        void readLP() {
1020            synchronized (mFileLock) {
1021                AtomicFile file = getFile();
1022                BufferedInputStream in = null;
1023                try {
1024                    in = new BufferedInputStream(file.openRead());
1025                    StringBuffer sb = new StringBuffer();
1026                    while (true) {
1027                        String packageName = readToken(in, sb, ' ');
1028                        if (packageName == null) {
1029                            break;
1030                        }
1031                        String timeInMillisString = readToken(in, sb, '\n');
1032                        if (timeInMillisString == null) {
1033                            throw new IOException("Failed to find last usage time for package "
1034                                                  + packageName);
1035                        }
1036                        PackageParser.Package pkg = mPackages.get(packageName);
1037                        if (pkg == null) {
1038                            continue;
1039                        }
1040                        long timeInMillis;
1041                        try {
1042                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1043                        } catch (NumberFormatException e) {
1044                            throw new IOException("Failed to parse " + timeInMillisString
1045                                                  + " as a long.", e);
1046                        }
1047                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1048                    }
1049                } catch (FileNotFoundException expected) {
1050                    mIsHistoricalPackageUsageAvailable = false;
1051                } catch (IOException e) {
1052                    Log.w(TAG, "Failed to read package usage times", e);
1053                } finally {
1054                    IoUtils.closeQuietly(in);
1055                }
1056            }
1057            mLastWritten.set(SystemClock.elapsedRealtime());
1058        }
1059
1060        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1061                throws IOException {
1062            sb.setLength(0);
1063            while (true) {
1064                int ch = in.read();
1065                if (ch == -1) {
1066                    if (sb.length() == 0) {
1067                        return null;
1068                    }
1069                    throw new IOException("Unexpected EOF");
1070                }
1071                if (ch == endOfToken) {
1072                    return sb.toString();
1073                }
1074                sb.append((char)ch);
1075            }
1076        }
1077
1078        private AtomicFile getFile() {
1079            File dataDir = Environment.getDataDirectory();
1080            File systemDir = new File(dataDir, "system");
1081            File fname = new File(systemDir, "package-usage.list");
1082            return new AtomicFile(fname);
1083        }
1084    }
1085
1086    class PackageHandler extends Handler {
1087        private boolean mBound = false;
1088        final ArrayList<HandlerParams> mPendingInstalls =
1089            new ArrayList<HandlerParams>();
1090
1091        private boolean connectToService() {
1092            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1093                    " DefaultContainerService");
1094            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1095            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1096            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1097                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1098                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1099                mBound = true;
1100                return true;
1101            }
1102            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1103            return false;
1104        }
1105
1106        private void disconnectService() {
1107            mContainerService = null;
1108            mBound = false;
1109            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110            mContext.unbindService(mDefContainerConn);
1111            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112        }
1113
1114        PackageHandler(Looper looper) {
1115            super(looper);
1116        }
1117
1118        public void handleMessage(Message msg) {
1119            try {
1120                doHandleMessage(msg);
1121            } finally {
1122                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1123            }
1124        }
1125
1126        void doHandleMessage(Message msg) {
1127            switch (msg.what) {
1128                case INIT_COPY: {
1129                    HandlerParams params = (HandlerParams) msg.obj;
1130                    int idx = mPendingInstalls.size();
1131                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1132                    // If a bind was already initiated we dont really
1133                    // need to do anything. The pending install
1134                    // will be processed later on.
1135                    if (!mBound) {
1136                        // If this is the only one pending we might
1137                        // have to bind to the service again.
1138                        if (!connectToService()) {
1139                            Slog.e(TAG, "Failed to bind to media container service");
1140                            params.serviceError();
1141                            return;
1142                        } else {
1143                            // Once we bind to the service, the first
1144                            // pending request will be processed.
1145                            mPendingInstalls.add(idx, params);
1146                        }
1147                    } else {
1148                        mPendingInstalls.add(idx, params);
1149                        // Already bound to the service. Just make
1150                        // sure we trigger off processing the first request.
1151                        if (idx == 0) {
1152                            mHandler.sendEmptyMessage(MCS_BOUND);
1153                        }
1154                    }
1155                    break;
1156                }
1157                case MCS_BOUND: {
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1159                    if (msg.obj != null) {
1160                        mContainerService = (IMediaContainerService) msg.obj;
1161                    }
1162                    if (mContainerService == null) {
1163                        if (!mBound) {
1164                            // Something seriously wrong since we are not bound and we are not
1165                            // waiting for connection. Bail out.
1166                            Slog.e(TAG, "Cannot bind to media container service");
1167                            for (HandlerParams params : mPendingInstalls) {
1168                                // Indicate service bind error
1169                                params.serviceError();
1170                            }
1171                            mPendingInstalls.clear();
1172                        } else {
1173                            Slog.w(TAG, "Waiting to connect to media container service");
1174                        }
1175                    } else if (mPendingInstalls.size() > 0) {
1176                        HandlerParams params = mPendingInstalls.get(0);
1177                        if (params != null) {
1178                            if (params.startCopy()) {
1179                                // We are done...  look for more work or to
1180                                // go idle.
1181                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1182                                        "Checking for more work or unbind...");
1183                                // Delete pending install
1184                                if (mPendingInstalls.size() > 0) {
1185                                    mPendingInstalls.remove(0);
1186                                }
1187                                if (mPendingInstalls.size() == 0) {
1188                                    if (mBound) {
1189                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1190                                                "Posting delayed MCS_UNBIND");
1191                                        removeMessages(MCS_UNBIND);
1192                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1193                                        // Unbind after a little delay, to avoid
1194                                        // continual thrashing.
1195                                        sendMessageDelayed(ubmsg, 10000);
1196                                    }
1197                                } else {
1198                                    // There are more pending requests in queue.
1199                                    // Just post MCS_BOUND message to trigger processing
1200                                    // of next pending install.
1201                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1202                                            "Posting MCS_BOUND for next work");
1203                                    mHandler.sendEmptyMessage(MCS_BOUND);
1204                                }
1205                            }
1206                        }
1207                    } else {
1208                        // Should never happen ideally.
1209                        Slog.w(TAG, "Empty queue");
1210                    }
1211                    break;
1212                }
1213                case MCS_RECONNECT: {
1214                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1215                    if (mPendingInstalls.size() > 0) {
1216                        if (mBound) {
1217                            disconnectService();
1218                        }
1219                        if (!connectToService()) {
1220                            Slog.e(TAG, "Failed to bind to media container service");
1221                            for (HandlerParams params : mPendingInstalls) {
1222                                // Indicate service bind error
1223                                params.serviceError();
1224                            }
1225                            mPendingInstalls.clear();
1226                        }
1227                    }
1228                    break;
1229                }
1230                case MCS_UNBIND: {
1231                    // If there is no actual work left, then time to unbind.
1232                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1233
1234                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1235                        if (mBound) {
1236                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1237
1238                            disconnectService();
1239                        }
1240                    } else if (mPendingInstalls.size() > 0) {
1241                        // There are more pending requests in queue.
1242                        // Just post MCS_BOUND message to trigger processing
1243                        // of next pending install.
1244                        mHandler.sendEmptyMessage(MCS_BOUND);
1245                    }
1246
1247                    break;
1248                }
1249                case MCS_GIVE_UP: {
1250                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1251                    mPendingInstalls.remove(0);
1252                    break;
1253                }
1254                case SEND_PENDING_BROADCAST: {
1255                    String packages[];
1256                    ArrayList<String> components[];
1257                    int size = 0;
1258                    int uids[];
1259                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1260                    synchronized (mPackages) {
1261                        if (mPendingBroadcasts == null) {
1262                            return;
1263                        }
1264                        size = mPendingBroadcasts.size();
1265                        if (size <= 0) {
1266                            // Nothing to be done. Just return
1267                            return;
1268                        }
1269                        packages = new String[size];
1270                        components = new ArrayList[size];
1271                        uids = new int[size];
1272                        int i = 0;  // filling out the above arrays
1273
1274                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1275                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1276                            Iterator<Map.Entry<String, ArrayList<String>>> it
1277                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1278                                            .entrySet().iterator();
1279                            while (it.hasNext() && i < size) {
1280                                Map.Entry<String, ArrayList<String>> ent = it.next();
1281                                packages[i] = ent.getKey();
1282                                components[i] = ent.getValue();
1283                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1284                                uids[i] = (ps != null)
1285                                        ? UserHandle.getUid(packageUserId, ps.appId)
1286                                        : -1;
1287                                i++;
1288                            }
1289                        }
1290                        size = i;
1291                        mPendingBroadcasts.clear();
1292                    }
1293                    // Send broadcasts
1294                    for (int i = 0; i < size; i++) {
1295                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1296                    }
1297                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1298                    break;
1299                }
1300                case START_CLEANING_PACKAGE: {
1301                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1302                    final String packageName = (String)msg.obj;
1303                    final int userId = msg.arg1;
1304                    final boolean andCode = msg.arg2 != 0;
1305                    synchronized (mPackages) {
1306                        if (userId == UserHandle.USER_ALL) {
1307                            int[] users = sUserManager.getUserIds();
1308                            for (int user : users) {
1309                                mSettings.addPackageToCleanLPw(
1310                                        new PackageCleanItem(user, packageName, andCode));
1311                            }
1312                        } else {
1313                            mSettings.addPackageToCleanLPw(
1314                                    new PackageCleanItem(userId, packageName, andCode));
1315                        }
1316                    }
1317                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1318                    startCleaningPackages();
1319                } break;
1320                case POST_INSTALL: {
1321                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1322                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1323                    mRunningInstalls.delete(msg.arg1);
1324                    boolean deleteOld = false;
1325
1326                    if (data != null) {
1327                        InstallArgs args = data.args;
1328                        PackageInstalledInfo res = data.res;
1329
1330                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1331                            final String packageName = res.pkg.applicationInfo.packageName;
1332                            res.removedInfo.sendBroadcast(false, true, false);
1333                            Bundle extras = new Bundle(1);
1334                            extras.putInt(Intent.EXTRA_UID, res.uid);
1335
1336                            // Now that we successfully installed the package, grant runtime
1337                            // permissions if requested before broadcasting the install.
1338                            if ((args.installFlags
1339                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1340                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1341                                        args.installGrantPermissions);
1342                            }
1343
1344                            // Determine the set of users who are adding this
1345                            // package for the first time vs. those who are seeing
1346                            // an update.
1347                            int[] firstUsers;
1348                            int[] updateUsers = new int[0];
1349                            if (res.origUsers == null || res.origUsers.length == 0) {
1350                                firstUsers = res.newUsers;
1351                            } else {
1352                                firstUsers = new int[0];
1353                                for (int i=0; i<res.newUsers.length; i++) {
1354                                    int user = res.newUsers[i];
1355                                    boolean isNew = true;
1356                                    for (int j=0; j<res.origUsers.length; j++) {
1357                                        if (res.origUsers[j] == user) {
1358                                            isNew = false;
1359                                            break;
1360                                        }
1361                                    }
1362                                    if (isNew) {
1363                                        int[] newFirst = new int[firstUsers.length+1];
1364                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1365                                                firstUsers.length);
1366                                        newFirst[firstUsers.length] = user;
1367                                        firstUsers = newFirst;
1368                                    } else {
1369                                        int[] newUpdate = new int[updateUsers.length+1];
1370                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1371                                                updateUsers.length);
1372                                        newUpdate[updateUsers.length] = user;
1373                                        updateUsers = newUpdate;
1374                                    }
1375                                }
1376                            }
1377                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1378                                    packageName, extras, null, null, firstUsers);
1379                            final boolean update = res.removedInfo.removedPackage != null;
1380                            if (update) {
1381                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1382                            }
1383                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1384                                    packageName, extras, null, null, updateUsers);
1385                            if (update) {
1386                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1387                                        packageName, extras, null, null, updateUsers);
1388                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1389                                        null, null, packageName, null, updateUsers);
1390
1391                                // treat asec-hosted packages like removable media on upgrade
1392                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1393                                    if (DEBUG_INSTALL) {
1394                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1395                                                + " is ASEC-hosted -> AVAILABLE");
1396                                    }
1397                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1398                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1399                                    pkgList.add(packageName);
1400                                    sendResourcesChangedBroadcast(true, true,
1401                                            pkgList,uidArray, null);
1402                                }
1403                            }
1404                            if (res.removedInfo.args != null) {
1405                                // Remove the replaced package's older resources safely now
1406                                deleteOld = true;
1407                            }
1408
1409                            // If this app is a browser and it's newly-installed for some
1410                            // users, clear any default-browser state in those users
1411                            if (firstUsers.length > 0) {
1412                                // the app's nature doesn't depend on the user, so we can just
1413                                // check its browser nature in any user and generalize.
1414                                if (packageIsBrowser(packageName, firstUsers[0])) {
1415                                    synchronized (mPackages) {
1416                                        for (int userId : firstUsers) {
1417                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1418                                        }
1419                                    }
1420                                }
1421                            }
1422                            // Log current value of "unknown sources" setting
1423                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1424                                getUnknownSourcesSettings());
1425                        }
1426                        // Force a gc to clear up things
1427                        Runtime.getRuntime().gc();
1428                        // We delete after a gc for applications  on sdcard.
1429                        if (deleteOld) {
1430                            synchronized (mInstallLock) {
1431                                res.removedInfo.args.doPostDeleteLI(true);
1432                            }
1433                        }
1434                        if (args.observer != null) {
1435                            try {
1436                                Bundle extras = extrasForInstallResult(res);
1437                                args.observer.onPackageInstalled(res.name, res.returnCode,
1438                                        res.returnMsg, extras);
1439                            } catch (RemoteException e) {
1440                                Slog.i(TAG, "Observer no longer exists.");
1441                            }
1442                        }
1443                    } else {
1444                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1445                    }
1446                } break;
1447                case UPDATED_MEDIA_STATUS: {
1448                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1449                    boolean reportStatus = msg.arg1 == 1;
1450                    boolean doGc = msg.arg2 == 1;
1451                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1452                    if (doGc) {
1453                        // Force a gc to clear up stale containers.
1454                        Runtime.getRuntime().gc();
1455                    }
1456                    if (msg.obj != null) {
1457                        @SuppressWarnings("unchecked")
1458                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1459                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1460                        // Unload containers
1461                        unloadAllContainers(args);
1462                    }
1463                    if (reportStatus) {
1464                        try {
1465                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1466                            PackageHelper.getMountService().finishMediaUpdate();
1467                        } catch (RemoteException e) {
1468                            Log.e(TAG, "MountService not running?");
1469                        }
1470                    }
1471                } break;
1472                case WRITE_SETTINGS: {
1473                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1474                    synchronized (mPackages) {
1475                        removeMessages(WRITE_SETTINGS);
1476                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1477                        mSettings.writeLPr();
1478                        mDirtyUsers.clear();
1479                    }
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1481                } break;
1482                case WRITE_PACKAGE_RESTRICTIONS: {
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1484                    synchronized (mPackages) {
1485                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1486                        for (int userId : mDirtyUsers) {
1487                            mSettings.writePackageRestrictionsLPr(userId);
1488                        }
1489                        mDirtyUsers.clear();
1490                    }
1491                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1492                } break;
1493                case CHECK_PENDING_VERIFICATION: {
1494                    final int verificationId = msg.arg1;
1495                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1496
1497                    if ((state != null) && !state.timeoutExtended()) {
1498                        final InstallArgs args = state.getInstallArgs();
1499                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1500
1501                        Slog.i(TAG, "Verification timed out for " + originUri);
1502                        mPendingVerification.remove(verificationId);
1503
1504                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1505
1506                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1507                            Slog.i(TAG, "Continuing with installation of " + originUri);
1508                            state.setVerifierResponse(Binder.getCallingUid(),
1509                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1510                            broadcastPackageVerified(verificationId, originUri,
1511                                    PackageManager.VERIFICATION_ALLOW,
1512                                    state.getInstallArgs().getUser());
1513                            try {
1514                                ret = args.copyApk(mContainerService, true);
1515                            } catch (RemoteException e) {
1516                                Slog.e(TAG, "Could not contact the ContainerService");
1517                            }
1518                        } else {
1519                            broadcastPackageVerified(verificationId, originUri,
1520                                    PackageManager.VERIFICATION_REJECT,
1521                                    state.getInstallArgs().getUser());
1522                        }
1523
1524                        processPendingInstall(args, ret);
1525                        mHandler.sendEmptyMessage(MCS_UNBIND);
1526                    }
1527                    break;
1528                }
1529                case PACKAGE_VERIFIED: {
1530                    final int verificationId = msg.arg1;
1531
1532                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1533                    if (state == null) {
1534                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1535                        break;
1536                    }
1537
1538                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1539
1540                    state.setVerifierResponse(response.callerUid, response.code);
1541
1542                    if (state.isVerificationComplete()) {
1543                        mPendingVerification.remove(verificationId);
1544
1545                        final InstallArgs args = state.getInstallArgs();
1546                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1547
1548                        int ret;
1549                        if (state.isInstallAllowed()) {
1550                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1551                            broadcastPackageVerified(verificationId, originUri,
1552                                    response.code, state.getInstallArgs().getUser());
1553                            try {
1554                                ret = args.copyApk(mContainerService, true);
1555                            } catch (RemoteException e) {
1556                                Slog.e(TAG, "Could not contact the ContainerService");
1557                            }
1558                        } else {
1559                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1560                        }
1561
1562                        processPendingInstall(args, ret);
1563
1564                        mHandler.sendEmptyMessage(MCS_UNBIND);
1565                    }
1566
1567                    break;
1568                }
1569                case START_INTENT_FILTER_VERIFICATIONS: {
1570                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1571                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1572                            params.replacing, params.pkg);
1573                    break;
1574                }
1575                case INTENT_FILTER_VERIFIED: {
1576                    final int verificationId = msg.arg1;
1577
1578                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1579                            verificationId);
1580                    if (state == null) {
1581                        Slog.w(TAG, "Invalid IntentFilter verification token "
1582                                + verificationId + " received");
1583                        break;
1584                    }
1585
1586                    final int userId = state.getUserId();
1587
1588                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1589                            "Processing IntentFilter verification with token:"
1590                            + verificationId + " and userId:" + userId);
1591
1592                    final IntentFilterVerificationResponse response =
1593                            (IntentFilterVerificationResponse) msg.obj;
1594
1595                    state.setVerifierResponse(response.callerUid, response.code);
1596
1597                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598                            "IntentFilter verification with token:" + verificationId
1599                            + " and userId:" + userId
1600                            + " is settings verifier response with response code:"
1601                            + response.code);
1602
1603                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1604                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1605                                + response.getFailedDomainsString());
1606                    }
1607
1608                    if (state.isVerificationComplete()) {
1609                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1610                    } else {
1611                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                                "IntentFilter verification with token:" + verificationId
1613                                + " was not said to be complete");
1614                    }
1615
1616                    break;
1617                }
1618            }
1619        }
1620    }
1621
1622    private StorageEventListener mStorageListener = new StorageEventListener() {
1623        @Override
1624        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1625            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1626                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1627                    final String volumeUuid = vol.getFsUuid();
1628
1629                    // Clean up any users or apps that were removed or recreated
1630                    // while this volume was missing
1631                    reconcileUsers(volumeUuid);
1632                    reconcileApps(volumeUuid);
1633
1634                    // Clean up any install sessions that expired or were
1635                    // cancelled while this volume was missing
1636                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1637
1638                    loadPrivatePackages(vol);
1639
1640                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1641                    unloadPrivatePackages(vol);
1642                }
1643            }
1644
1645            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1646                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1647                    updateExternalMediaStatus(true, false);
1648                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1649                    updateExternalMediaStatus(false, false);
1650                }
1651            }
1652        }
1653
1654        @Override
1655        public void onVolumeForgotten(String fsUuid) {
1656            if (TextUtils.isEmpty(fsUuid)) {
1657                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1658                return;
1659            }
1660
1661            // Remove any apps installed on the forgotten volume
1662            synchronized (mPackages) {
1663                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1664                for (PackageSetting ps : packages) {
1665                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1666                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1667                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1668                }
1669
1670                mSettings.onVolumeForgotten(fsUuid);
1671                mSettings.writeLPr();
1672            }
1673        }
1674    };
1675
1676    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1677            String[] grantedPermissions) {
1678        if (userId >= UserHandle.USER_OWNER) {
1679            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1680        } else if (userId == UserHandle.USER_ALL) {
1681            final int[] userIds;
1682            synchronized (mPackages) {
1683                userIds = UserManagerService.getInstance().getUserIds();
1684            }
1685            for (int someUserId : userIds) {
1686                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1687            }
1688        }
1689
1690        // We could have touched GID membership, so flush out packages.list
1691        synchronized (mPackages) {
1692            mSettings.writePackageListLPr();
1693        }
1694    }
1695
1696    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1697            String[] grantedPermissions) {
1698        SettingBase sb = (SettingBase) pkg.mExtras;
1699        if (sb == null) {
1700            return;
1701        }
1702
1703        PermissionsState permissionsState = sb.getPermissionsState();
1704
1705        for (String permission : pkg.requestedPermissions) {
1706            BasePermission bp = mSettings.mPermissions.get(permission);
1707            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1708                    || ArrayUtils.contains(grantedPermissions, permission))) {
1709                permissionsState.grantRuntimePermission(bp, userId);
1710            }
1711        }
1712    }
1713
1714    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1715        Bundle extras = null;
1716        switch (res.returnCode) {
1717            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1718                extras = new Bundle();
1719                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1720                        res.origPermission);
1721                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1722                        res.origPackage);
1723                break;
1724            }
1725            case PackageManager.INSTALL_SUCCEEDED: {
1726                extras = new Bundle();
1727                extras.putBoolean(Intent.EXTRA_REPLACING,
1728                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1729                break;
1730            }
1731        }
1732        return extras;
1733    }
1734
1735    void scheduleWriteSettingsLocked() {
1736        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1737            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1738        }
1739    }
1740
1741    void scheduleWritePackageRestrictionsLocked(int userId) {
1742        if (!sUserManager.exists(userId)) return;
1743        mDirtyUsers.add(userId);
1744        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1745            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1746        }
1747    }
1748
1749    public static PackageManagerService main(Context context, Installer installer,
1750            boolean factoryTest, boolean onlyCore) {
1751        PackageManagerService m = new PackageManagerService(context, installer,
1752                factoryTest, onlyCore);
1753        ServiceManager.addService("package", m);
1754        return m;
1755    }
1756
1757    static String[] splitString(String str, char sep) {
1758        int count = 1;
1759        int i = 0;
1760        while ((i=str.indexOf(sep, i)) >= 0) {
1761            count++;
1762            i++;
1763        }
1764
1765        String[] res = new String[count];
1766        i=0;
1767        count = 0;
1768        int lastI=0;
1769        while ((i=str.indexOf(sep, i)) >= 0) {
1770            res[count] = str.substring(lastI, i);
1771            count++;
1772            i++;
1773            lastI = i;
1774        }
1775        res[count] = str.substring(lastI, str.length());
1776        return res;
1777    }
1778
1779    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1780        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1781                Context.DISPLAY_SERVICE);
1782        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1783    }
1784
1785    public PackageManagerService(Context context, Installer installer,
1786            boolean factoryTest, boolean onlyCore) {
1787        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1788                SystemClock.uptimeMillis());
1789
1790        if (mSdkVersion <= 0) {
1791            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1792        }
1793
1794        mContext = context;
1795        mFactoryTest = factoryTest;
1796        mOnlyCore = onlyCore;
1797        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1798        mMetrics = new DisplayMetrics();
1799        mSettings = new Settings(mPackages);
1800        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1801                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1802        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1803                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1804        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1805                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1806        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1807                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1808        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1809                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1810        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1811                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1812
1813        // TODO: add a property to control this?
1814        long dexOptLRUThresholdInMinutes;
1815        if (mLazyDexOpt) {
1816            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1817        } else {
1818            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1819        }
1820        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1821
1822        String separateProcesses = SystemProperties.get("debug.separate_processes");
1823        if (separateProcesses != null && separateProcesses.length() > 0) {
1824            if ("*".equals(separateProcesses)) {
1825                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1826                mSeparateProcesses = null;
1827                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1828            } else {
1829                mDefParseFlags = 0;
1830                mSeparateProcesses = separateProcesses.split(",");
1831                Slog.w(TAG, "Running with debug.separate_processes: "
1832                        + separateProcesses);
1833            }
1834        } else {
1835            mDefParseFlags = 0;
1836            mSeparateProcesses = null;
1837        }
1838
1839        mInstaller = installer;
1840        mPackageDexOptimizer = new PackageDexOptimizer(this);
1841        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1842
1843        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1844                FgThread.get().getLooper());
1845
1846        getDefaultDisplayMetrics(context, mMetrics);
1847
1848        SystemConfig systemConfig = SystemConfig.getInstance();
1849        mGlobalGids = systemConfig.getGlobalGids();
1850        mSystemPermissions = systemConfig.getSystemPermissions();
1851        mAvailableFeatures = systemConfig.getAvailableFeatures();
1852
1853        synchronized (mInstallLock) {
1854        // writer
1855        synchronized (mPackages) {
1856            mHandlerThread = new ServiceThread(TAG,
1857                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1858            mHandlerThread.start();
1859            mHandler = new PackageHandler(mHandlerThread.getLooper());
1860            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1861
1862            File dataDir = Environment.getDataDirectory();
1863            mAppDataDir = new File(dataDir, "data");
1864            mAppInstallDir = new File(dataDir, "app");
1865            mAppLib32InstallDir = new File(dataDir, "app-lib");
1866            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1867            mUserAppDataDir = new File(dataDir, "user");
1868            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1869
1870            sUserManager = new UserManagerService(context, this,
1871                    mInstallLock, mPackages);
1872
1873            // Propagate permission configuration in to package manager.
1874            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1875                    = systemConfig.getPermissions();
1876            for (int i=0; i<permConfig.size(); i++) {
1877                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1878                BasePermission bp = mSettings.mPermissions.get(perm.name);
1879                if (bp == null) {
1880                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1881                    mSettings.mPermissions.put(perm.name, bp);
1882                }
1883                if (perm.gids != null) {
1884                    bp.setGids(perm.gids, perm.perUser);
1885                }
1886            }
1887
1888            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1889            for (int i=0; i<libConfig.size(); i++) {
1890                mSharedLibraries.put(libConfig.keyAt(i),
1891                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1892            }
1893
1894            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1895
1896            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1897                    mSdkVersion, mOnlyCore);
1898
1899            String customResolverActivity = Resources.getSystem().getString(
1900                    R.string.config_customResolverActivity);
1901            if (TextUtils.isEmpty(customResolverActivity)) {
1902                customResolverActivity = null;
1903            } else {
1904                mCustomResolverComponentName = ComponentName.unflattenFromString(
1905                        customResolverActivity);
1906            }
1907
1908            long startTime = SystemClock.uptimeMillis();
1909
1910            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1911                    startTime);
1912
1913            // Set flag to monitor and not change apk file paths when
1914            // scanning install directories.
1915            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1916
1917            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1918
1919            /**
1920             * Add everything in the in the boot class path to the
1921             * list of process files because dexopt will have been run
1922             * if necessary during zygote startup.
1923             */
1924            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1925            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1926
1927            if (bootClassPath != null) {
1928                String[] bootClassPathElements = splitString(bootClassPath, ':');
1929                for (String element : bootClassPathElements) {
1930                    alreadyDexOpted.add(element);
1931                }
1932            } else {
1933                Slog.w(TAG, "No BOOTCLASSPATH found!");
1934            }
1935
1936            if (systemServerClassPath != null) {
1937                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1938                for (String element : systemServerClassPathElements) {
1939                    alreadyDexOpted.add(element);
1940                }
1941            } else {
1942                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1943            }
1944
1945            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1946            final String[] dexCodeInstructionSets =
1947                    getDexCodeInstructionSets(
1948                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1949
1950            /**
1951             * Ensure all external libraries have had dexopt run on them.
1952             */
1953            if (mSharedLibraries.size() > 0) {
1954                // NOTE: For now, we're compiling these system "shared libraries"
1955                // (and framework jars) into all available architectures. It's possible
1956                // to compile them only when we come across an app that uses them (there's
1957                // already logic for that in scanPackageLI) but that adds some complexity.
1958                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1959                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1960                        final String lib = libEntry.path;
1961                        if (lib == null) {
1962                            continue;
1963                        }
1964
1965                        try {
1966                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1967                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1968                                alreadyDexOpted.add(lib);
1969                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1970                            }
1971                        } catch (FileNotFoundException e) {
1972                            Slog.w(TAG, "Library not found: " + lib);
1973                        } catch (IOException e) {
1974                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1975                                    + e.getMessage());
1976                        }
1977                    }
1978                }
1979            }
1980
1981            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1982
1983            // Gross hack for now: we know this file doesn't contain any
1984            // code, so don't dexopt it to avoid the resulting log spew.
1985            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1986
1987            // Gross hack for now: we know this file is only part of
1988            // the boot class path for art, so don't dexopt it to
1989            // avoid the resulting log spew.
1990            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1991
1992            /**
1993             * There are a number of commands implemented in Java, which
1994             * we currently need to do the dexopt on so that they can be
1995             * run from a non-root shell.
1996             */
1997            String[] frameworkFiles = frameworkDir.list();
1998            if (frameworkFiles != null) {
1999                // TODO: We could compile these only for the most preferred ABI. We should
2000                // first double check that the dex files for these commands are not referenced
2001                // by other system apps.
2002                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2003                    for (int i=0; i<frameworkFiles.length; i++) {
2004                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2005                        String path = libPath.getPath();
2006                        // Skip the file if we already did it.
2007                        if (alreadyDexOpted.contains(path)) {
2008                            continue;
2009                        }
2010                        // Skip the file if it is not a type we want to dexopt.
2011                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2012                            continue;
2013                        }
2014                        try {
2015                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2016                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2017                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2018                            }
2019                        } catch (FileNotFoundException e) {
2020                            Slog.w(TAG, "Jar not found: " + path);
2021                        } catch (IOException e) {
2022                            Slog.w(TAG, "Exception reading jar: " + path, e);
2023                        }
2024                    }
2025                }
2026            }
2027
2028            // Collect vendor overlay packages.
2029            // (Do this before scanning any apps.)
2030            // For security and version matching reason, only consider
2031            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2032            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2033            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2034                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2035
2036            // Find base frameworks (resource packages without code).
2037            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2038                    | PackageParser.PARSE_IS_SYSTEM_DIR
2039                    | PackageParser.PARSE_IS_PRIVILEGED,
2040                    scanFlags | SCAN_NO_DEX, 0);
2041
2042            // Collected privileged system packages.
2043            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2044            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2045                    | PackageParser.PARSE_IS_SYSTEM_DIR
2046                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2047
2048            // Collect ordinary system packages.
2049            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2050            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2051                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2052
2053            // Collect all vendor packages.
2054            File vendorAppDir = new File("/vendor/app");
2055            try {
2056                vendorAppDir = vendorAppDir.getCanonicalFile();
2057            } catch (IOException e) {
2058                // failed to look up canonical path, continue with original one
2059            }
2060            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2061                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2062
2063            // Collect all OEM packages.
2064            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2065            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2066                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2067
2068            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2069            mInstaller.moveFiles();
2070
2071            // Prune any system packages that no longer exist.
2072            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2073            if (!mOnlyCore) {
2074                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2075                while (psit.hasNext()) {
2076                    PackageSetting ps = psit.next();
2077
2078                    /*
2079                     * If this is not a system app, it can't be a
2080                     * disable system app.
2081                     */
2082                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2083                        continue;
2084                    }
2085
2086                    /*
2087                     * If the package is scanned, it's not erased.
2088                     */
2089                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2090                    if (scannedPkg != null) {
2091                        /*
2092                         * If the system app is both scanned and in the
2093                         * disabled packages list, then it must have been
2094                         * added via OTA. Remove it from the currently
2095                         * scanned package so the previously user-installed
2096                         * application can be scanned.
2097                         */
2098                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2099                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2100                                    + ps.name + "; removing system app.  Last known codePath="
2101                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2102                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2103                                    + scannedPkg.mVersionCode);
2104                            removePackageLI(ps, true);
2105                            mExpectingBetter.put(ps.name, ps.codePath);
2106                        }
2107
2108                        continue;
2109                    }
2110
2111                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2112                        psit.remove();
2113                        logCriticalInfo(Log.WARN, "System package " + ps.name
2114                                + " no longer exists; wiping its data");
2115                        removeDataDirsLI(null, ps.name);
2116                    } else {
2117                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2118                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2119                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2120                        }
2121                    }
2122                }
2123            }
2124
2125            //look for any incomplete package installations
2126            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2127            //clean up list
2128            for(int i = 0; i < deletePkgsList.size(); i++) {
2129                //clean up here
2130                cleanupInstallFailedPackage(deletePkgsList.get(i));
2131            }
2132            //delete tmp files
2133            deleteTempPackageFiles();
2134
2135            // Remove any shared userIDs that have no associated packages
2136            mSettings.pruneSharedUsersLPw();
2137
2138            if (!mOnlyCore) {
2139                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2140                        SystemClock.uptimeMillis());
2141                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2142
2143                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2144                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2145
2146                /**
2147                 * Remove disable package settings for any updated system
2148                 * apps that were removed via an OTA. If they're not a
2149                 * previously-updated app, remove them completely.
2150                 * Otherwise, just revoke their system-level permissions.
2151                 */
2152                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2153                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2154                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2155
2156                    String msg;
2157                    if (deletedPkg == null) {
2158                        msg = "Updated system package " + deletedAppName
2159                                + " no longer exists; wiping its data";
2160                        removeDataDirsLI(null, deletedAppName);
2161                    } else {
2162                        msg = "Updated system app + " + deletedAppName
2163                                + " no longer present; removing system privileges for "
2164                                + deletedAppName;
2165
2166                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2167
2168                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2169                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2170                    }
2171                    logCriticalInfo(Log.WARN, msg);
2172                }
2173
2174                /**
2175                 * Make sure all system apps that we expected to appear on
2176                 * the userdata partition actually showed up. If they never
2177                 * appeared, crawl back and revive the system version.
2178                 */
2179                for (int i = 0; i < mExpectingBetter.size(); i++) {
2180                    final String packageName = mExpectingBetter.keyAt(i);
2181                    if (!mPackages.containsKey(packageName)) {
2182                        final File scanFile = mExpectingBetter.valueAt(i);
2183
2184                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2185                                + " but never showed up; reverting to system");
2186
2187                        final int reparseFlags;
2188                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2189                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2190                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2191                                    | PackageParser.PARSE_IS_PRIVILEGED;
2192                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2193                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2194                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2195                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2196                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2197                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2198                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2199                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2200                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2201                        } else {
2202                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2203                            continue;
2204                        }
2205
2206                        mSettings.enableSystemPackageLPw(packageName);
2207
2208                        try {
2209                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2210                        } catch (PackageManagerException e) {
2211                            Slog.e(TAG, "Failed to parse original system package: "
2212                                    + e.getMessage());
2213                        }
2214                    }
2215                }
2216            }
2217            mExpectingBetter.clear();
2218
2219            // Now that we know all of the shared libraries, update all clients to have
2220            // the correct library paths.
2221            updateAllSharedLibrariesLPw();
2222
2223            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2224                // NOTE: We ignore potential failures here during a system scan (like
2225                // the rest of the commands above) because there's precious little we
2226                // can do about it. A settings error is reported, though.
2227                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2228                        false /* force dexopt */, false /* defer dexopt */);
2229            }
2230
2231            // Now that we know all the packages we are keeping,
2232            // read and update their last usage times.
2233            mPackageUsage.readLP();
2234
2235            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2236                    SystemClock.uptimeMillis());
2237            Slog.i(TAG, "Time to scan packages: "
2238                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2239                    + " seconds");
2240
2241            // If the platform SDK has changed since the last time we booted,
2242            // we need to re-grant app permission to catch any new ones that
2243            // appear.  This is really a hack, and means that apps can in some
2244            // cases get permissions that the user didn't initially explicitly
2245            // allow...  it would be nice to have some better way to handle
2246            // this situation.
2247            final VersionInfo ver = mSettings.getInternalVersion();
2248
2249            int updateFlags = UPDATE_PERMISSIONS_ALL;
2250            if (ver.sdkVersion != mSdkVersion) {
2251                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2252                        + mSdkVersion + "; regranting permissions for internal storage");
2253                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2254            }
2255            updatePermissionsLPw(null, null, updateFlags);
2256            ver.sdkVersion = mSdkVersion;
2257
2258            // If this is the first boot, and it is a normal boot, then
2259            // we need to initialize the default preferred apps.
2260            if (!mRestoredSettings && !onlyCore) {
2261                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2262                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2263                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2264            }
2265
2266            // If this is first boot after an OTA, and a normal boot, then
2267            // we need to clear code cache directories.
2268            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2269            if (mIsUpgrade && !onlyCore) {
2270                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2271                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2272                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2273                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2274                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2275                    }
2276                }
2277                ver.fingerprint = Build.FINGERPRINT;
2278            }
2279
2280            checkDefaultBrowser();
2281
2282            // All the changes are done during package scanning.
2283            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2284
2285            // can downgrade to reader
2286            mSettings.writeLPr();
2287
2288            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2289                    SystemClock.uptimeMillis());
2290
2291            mRequiredVerifierPackage = getRequiredVerifierLPr();
2292            mRequiredInstallerPackage = getRequiredInstallerLPr();
2293
2294            mInstallerService = new PackageInstallerService(context, this);
2295
2296            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2297            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2298                    mIntentFilterVerifierComponent);
2299
2300        } // synchronized (mPackages)
2301        } // synchronized (mInstallLock)
2302
2303        // Now after opening every single application zip, make sure they
2304        // are all flushed.  Not really needed, but keeps things nice and
2305        // tidy.
2306        Runtime.getRuntime().gc();
2307
2308        // Expose private service for system components to use.
2309        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2310    }
2311
2312    @Override
2313    public boolean isFirstBoot() {
2314        return !mRestoredSettings;
2315    }
2316
2317    @Override
2318    public boolean isOnlyCoreApps() {
2319        return mOnlyCore;
2320    }
2321
2322    @Override
2323    public boolean isUpgrade() {
2324        return mIsUpgrade;
2325    }
2326
2327    private String getRequiredVerifierLPr() {
2328        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2329        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2330                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2331
2332        String requiredVerifier = null;
2333
2334        final int N = receivers.size();
2335        for (int i = 0; i < N; i++) {
2336            final ResolveInfo info = receivers.get(i);
2337
2338            if (info.activityInfo == null) {
2339                continue;
2340            }
2341
2342            final String packageName = info.activityInfo.packageName;
2343
2344            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2345                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2346                continue;
2347            }
2348
2349            if (requiredVerifier != null) {
2350                throw new RuntimeException("There can be only one required verifier");
2351            }
2352
2353            requiredVerifier = packageName;
2354        }
2355
2356        return requiredVerifier;
2357    }
2358
2359    private String getRequiredInstallerLPr() {
2360        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2361        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2362        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2363
2364        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2365                PACKAGE_MIME_TYPE, 0, 0);
2366
2367        String requiredInstaller = null;
2368
2369        final int N = installers.size();
2370        for (int i = 0; i < N; i++) {
2371            final ResolveInfo info = installers.get(i);
2372            final String packageName = info.activityInfo.packageName;
2373
2374            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2375                continue;
2376            }
2377
2378            if (requiredInstaller != null) {
2379                throw new RuntimeException("There must be one required installer");
2380            }
2381
2382            requiredInstaller = packageName;
2383        }
2384
2385        if (requiredInstaller == null) {
2386            throw new RuntimeException("There must be one required installer");
2387        }
2388
2389        return requiredInstaller;
2390    }
2391
2392    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2393        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2394        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2395                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2396
2397        ComponentName verifierComponentName = null;
2398
2399        int priority = -1000;
2400        final int N = receivers.size();
2401        for (int i = 0; i < N; i++) {
2402            final ResolveInfo info = receivers.get(i);
2403
2404            if (info.activityInfo == null) {
2405                continue;
2406            }
2407
2408            final String packageName = info.activityInfo.packageName;
2409
2410            final PackageSetting ps = mSettings.mPackages.get(packageName);
2411            if (ps == null) {
2412                continue;
2413            }
2414
2415            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2416                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2417                continue;
2418            }
2419
2420            // Select the IntentFilterVerifier with the highest priority
2421            if (priority < info.priority) {
2422                priority = info.priority;
2423                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2424                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2425                        + verifierComponentName + " with priority: " + info.priority);
2426            }
2427        }
2428
2429        return verifierComponentName;
2430    }
2431
2432    private void primeDomainVerificationsLPw(int userId) {
2433        if (DEBUG_DOMAIN_VERIFICATION) {
2434            Slog.d(TAG, "Priming domain verifications in user " + userId);
2435        }
2436
2437        SystemConfig systemConfig = SystemConfig.getInstance();
2438        ArraySet<String> packages = systemConfig.getLinkedApps();
2439        ArraySet<String> domains = new ArraySet<String>();
2440
2441        for (String packageName : packages) {
2442            PackageParser.Package pkg = mPackages.get(packageName);
2443            if (pkg != null) {
2444                if (!pkg.isSystemApp()) {
2445                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2446                    continue;
2447                }
2448
2449                domains.clear();
2450                for (PackageParser.Activity a : pkg.activities) {
2451                    for (ActivityIntentInfo filter : a.intents) {
2452                        if (hasValidDomains(filter)) {
2453                            domains.addAll(filter.getHostsList());
2454                        }
2455                    }
2456                }
2457
2458                if (domains.size() > 0) {
2459                    if (DEBUG_DOMAIN_VERIFICATION) {
2460                        Slog.v(TAG, "      + " + packageName);
2461                    }
2462                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2463                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2464                    // and then 'always' in the per-user state actually used for intent resolution.
2465                    final IntentFilterVerificationInfo ivi;
2466                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2467                            new ArrayList<String>(domains));
2468                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2469                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2470                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2471                } else {
2472                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2473                            + "' does not handle web links");
2474                }
2475            } else {
2476                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2477            }
2478        }
2479
2480        scheduleWritePackageRestrictionsLocked(userId);
2481        scheduleWriteSettingsLocked();
2482    }
2483
2484    private void applyFactoryDefaultBrowserLPw(int userId) {
2485        // The default browser app's package name is stored in a string resource,
2486        // with a product-specific overlay used for vendor customization.
2487        String browserPkg = mContext.getResources().getString(
2488                com.android.internal.R.string.default_browser);
2489        if (!TextUtils.isEmpty(browserPkg)) {
2490            // non-empty string => required to be a known package
2491            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2492            if (ps == null) {
2493                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2494                browserPkg = null;
2495            } else {
2496                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2497            }
2498        }
2499
2500        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2501        // default.  If there's more than one, just leave everything alone.
2502        if (browserPkg == null) {
2503            calculateDefaultBrowserLPw(userId);
2504        }
2505    }
2506
2507    private void calculateDefaultBrowserLPw(int userId) {
2508        List<String> allBrowsers = resolveAllBrowserApps(userId);
2509        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2510        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2511    }
2512
2513    private List<String> resolveAllBrowserApps(int userId) {
2514        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2515        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2516                PackageManager.MATCH_ALL, userId);
2517
2518        final int count = list.size();
2519        List<String> result = new ArrayList<String>(count);
2520        for (int i=0; i<count; i++) {
2521            ResolveInfo info = list.get(i);
2522            if (info.activityInfo == null
2523                    || !info.handleAllWebDataURI
2524                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2525                    || result.contains(info.activityInfo.packageName)) {
2526                continue;
2527            }
2528            result.add(info.activityInfo.packageName);
2529        }
2530
2531        return result;
2532    }
2533
2534    private boolean packageIsBrowser(String packageName, int userId) {
2535        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2536                PackageManager.MATCH_ALL, userId);
2537        final int N = list.size();
2538        for (int i = 0; i < N; i++) {
2539            ResolveInfo info = list.get(i);
2540            if (packageName.equals(info.activityInfo.packageName)) {
2541                return true;
2542            }
2543        }
2544        return false;
2545    }
2546
2547    private void checkDefaultBrowser() {
2548        final int myUserId = UserHandle.myUserId();
2549        final String packageName = getDefaultBrowserPackageName(myUserId);
2550        if (packageName != null) {
2551            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2552            if (info == null) {
2553                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2554                synchronized (mPackages) {
2555                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2556                }
2557            }
2558        }
2559    }
2560
2561    @Override
2562    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2563            throws RemoteException {
2564        try {
2565            return super.onTransact(code, data, reply, flags);
2566        } catch (RuntimeException e) {
2567            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2568                Slog.wtf(TAG, "Package Manager Crash", e);
2569            }
2570            throw e;
2571        }
2572    }
2573
2574    void cleanupInstallFailedPackage(PackageSetting ps) {
2575        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2576
2577        removeDataDirsLI(ps.volumeUuid, ps.name);
2578        if (ps.codePath != null) {
2579            if (ps.codePath.isDirectory()) {
2580                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2581            } else {
2582                ps.codePath.delete();
2583            }
2584        }
2585        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2586            if (ps.resourcePath.isDirectory()) {
2587                FileUtils.deleteContents(ps.resourcePath);
2588            }
2589            ps.resourcePath.delete();
2590        }
2591        mSettings.removePackageLPw(ps.name);
2592    }
2593
2594    static int[] appendInts(int[] cur, int[] add) {
2595        if (add == null) return cur;
2596        if (cur == null) return add;
2597        final int N = add.length;
2598        for (int i=0; i<N; i++) {
2599            cur = appendInt(cur, add[i]);
2600        }
2601        return cur;
2602    }
2603
2604    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2605        if (!sUserManager.exists(userId)) return null;
2606        final PackageSetting ps = (PackageSetting) p.mExtras;
2607        if (ps == null) {
2608            return null;
2609        }
2610
2611        final PermissionsState permissionsState = ps.getPermissionsState();
2612
2613        final int[] gids = permissionsState.computeGids(userId);
2614        final Set<String> permissions = permissionsState.getPermissions(userId);
2615        final PackageUserState state = ps.readUserState(userId);
2616
2617        return PackageParser.generatePackageInfo(p, gids, flags,
2618                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2619    }
2620
2621    @Override
2622    public boolean isPackageFrozen(String packageName) {
2623        synchronized (mPackages) {
2624            final PackageSetting ps = mSettings.mPackages.get(packageName);
2625            if (ps != null) {
2626                return ps.frozen;
2627            }
2628        }
2629        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2630        return true;
2631    }
2632
2633    @Override
2634    public boolean isPackageAvailable(String packageName, int userId) {
2635        if (!sUserManager.exists(userId)) return false;
2636        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2637        synchronized (mPackages) {
2638            PackageParser.Package p = mPackages.get(packageName);
2639            if (p != null) {
2640                final PackageSetting ps = (PackageSetting) p.mExtras;
2641                if (ps != null) {
2642                    final PackageUserState state = ps.readUserState(userId);
2643                    if (state != null) {
2644                        return PackageParser.isAvailable(state);
2645                    }
2646                }
2647            }
2648        }
2649        return false;
2650    }
2651
2652    @Override
2653    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2654        if (!sUserManager.exists(userId)) return null;
2655        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2656        // reader
2657        synchronized (mPackages) {
2658            PackageParser.Package p = mPackages.get(packageName);
2659            if (DEBUG_PACKAGE_INFO)
2660                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2661            if (p != null) {
2662                return generatePackageInfo(p, flags, userId);
2663            }
2664            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2665                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2666            }
2667        }
2668        return null;
2669    }
2670
2671    @Override
2672    public String[] currentToCanonicalPackageNames(String[] names) {
2673        String[] out = new String[names.length];
2674        // reader
2675        synchronized (mPackages) {
2676            for (int i=names.length-1; i>=0; i--) {
2677                PackageSetting ps = mSettings.mPackages.get(names[i]);
2678                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2679            }
2680        }
2681        return out;
2682    }
2683
2684    @Override
2685    public String[] canonicalToCurrentPackageNames(String[] names) {
2686        String[] out = new String[names.length];
2687        // reader
2688        synchronized (mPackages) {
2689            for (int i=names.length-1; i>=0; i--) {
2690                String cur = mSettings.mRenamedPackages.get(names[i]);
2691                out[i] = cur != null ? cur : names[i];
2692            }
2693        }
2694        return out;
2695    }
2696
2697    @Override
2698    public int getPackageUid(String packageName, int userId) {
2699        if (!sUserManager.exists(userId)) return -1;
2700        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2701
2702        // reader
2703        synchronized (mPackages) {
2704            PackageParser.Package p = mPackages.get(packageName);
2705            if(p != null) {
2706                return UserHandle.getUid(userId, p.applicationInfo.uid);
2707            }
2708            PackageSetting ps = mSettings.mPackages.get(packageName);
2709            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2710                return -1;
2711            }
2712            p = ps.pkg;
2713            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2714        }
2715    }
2716
2717    @Override
2718    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2719        if (!sUserManager.exists(userId)) {
2720            return null;
2721        }
2722
2723        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2724                "getPackageGids");
2725
2726        // reader
2727        synchronized (mPackages) {
2728            PackageParser.Package p = mPackages.get(packageName);
2729            if (DEBUG_PACKAGE_INFO) {
2730                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2731            }
2732            if (p != null) {
2733                PackageSetting ps = (PackageSetting) p.mExtras;
2734                return ps.getPermissionsState().computeGids(userId);
2735            }
2736        }
2737
2738        return null;
2739    }
2740
2741    static PermissionInfo generatePermissionInfo(
2742            BasePermission bp, int flags) {
2743        if (bp.perm != null) {
2744            return PackageParser.generatePermissionInfo(bp.perm, flags);
2745        }
2746        PermissionInfo pi = new PermissionInfo();
2747        pi.name = bp.name;
2748        pi.packageName = bp.sourcePackage;
2749        pi.nonLocalizedLabel = bp.name;
2750        pi.protectionLevel = bp.protectionLevel;
2751        return pi;
2752    }
2753
2754    @Override
2755    public PermissionInfo getPermissionInfo(String name, int flags) {
2756        // reader
2757        synchronized (mPackages) {
2758            final BasePermission p = mSettings.mPermissions.get(name);
2759            if (p != null) {
2760                return generatePermissionInfo(p, flags);
2761            }
2762            return null;
2763        }
2764    }
2765
2766    @Override
2767    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2768        // reader
2769        synchronized (mPackages) {
2770            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2771            for (BasePermission p : mSettings.mPermissions.values()) {
2772                if (group == null) {
2773                    if (p.perm == null || p.perm.info.group == null) {
2774                        out.add(generatePermissionInfo(p, flags));
2775                    }
2776                } else {
2777                    if (p.perm != null && group.equals(p.perm.info.group)) {
2778                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2779                    }
2780                }
2781            }
2782
2783            if (out.size() > 0) {
2784                return out;
2785            }
2786            return mPermissionGroups.containsKey(group) ? out : null;
2787        }
2788    }
2789
2790    @Override
2791    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2792        // reader
2793        synchronized (mPackages) {
2794            return PackageParser.generatePermissionGroupInfo(
2795                    mPermissionGroups.get(name), flags);
2796        }
2797    }
2798
2799    @Override
2800    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2801        // reader
2802        synchronized (mPackages) {
2803            final int N = mPermissionGroups.size();
2804            ArrayList<PermissionGroupInfo> out
2805                    = new ArrayList<PermissionGroupInfo>(N);
2806            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2807                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2808            }
2809            return out;
2810        }
2811    }
2812
2813    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2814            int userId) {
2815        if (!sUserManager.exists(userId)) return null;
2816        PackageSetting ps = mSettings.mPackages.get(packageName);
2817        if (ps != null) {
2818            if (ps.pkg == null) {
2819                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2820                        flags, userId);
2821                if (pInfo != null) {
2822                    return pInfo.applicationInfo;
2823                }
2824                return null;
2825            }
2826            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2827                    ps.readUserState(userId), userId);
2828        }
2829        return null;
2830    }
2831
2832    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2833            int userId) {
2834        if (!sUserManager.exists(userId)) return null;
2835        PackageSetting ps = mSettings.mPackages.get(packageName);
2836        if (ps != null) {
2837            PackageParser.Package pkg = ps.pkg;
2838            if (pkg == null) {
2839                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2840                    return null;
2841                }
2842                // Only data remains, so we aren't worried about code paths
2843                pkg = new PackageParser.Package(packageName);
2844                pkg.applicationInfo.packageName = packageName;
2845                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2846                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2847                pkg.applicationInfo.dataDir = Environment
2848                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2849                        .getAbsolutePath();
2850                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2851                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2852            }
2853            return generatePackageInfo(pkg, flags, userId);
2854        }
2855        return null;
2856    }
2857
2858    @Override
2859    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2860        if (!sUserManager.exists(userId)) return null;
2861        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2862        // writer
2863        synchronized (mPackages) {
2864            PackageParser.Package p = mPackages.get(packageName);
2865            if (DEBUG_PACKAGE_INFO) Log.v(
2866                    TAG, "getApplicationInfo " + packageName
2867                    + ": " + p);
2868            if (p != null) {
2869                PackageSetting ps = mSettings.mPackages.get(packageName);
2870                if (ps == null) return null;
2871                // Note: isEnabledLP() does not apply here - always return info
2872                return PackageParser.generateApplicationInfo(
2873                        p, flags, ps.readUserState(userId), userId);
2874            }
2875            if ("android".equals(packageName)||"system".equals(packageName)) {
2876                return mAndroidApplication;
2877            }
2878            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2879                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2880            }
2881        }
2882        return null;
2883    }
2884
2885    @Override
2886    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2887            final IPackageDataObserver observer) {
2888        mContext.enforceCallingOrSelfPermission(
2889                android.Manifest.permission.CLEAR_APP_CACHE, null);
2890        // Queue up an async operation since clearing cache may take a little while.
2891        mHandler.post(new Runnable() {
2892            public void run() {
2893                mHandler.removeCallbacks(this);
2894                int retCode = -1;
2895                synchronized (mInstallLock) {
2896                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2897                    if (retCode < 0) {
2898                        Slog.w(TAG, "Couldn't clear application caches");
2899                    }
2900                }
2901                if (observer != null) {
2902                    try {
2903                        observer.onRemoveCompleted(null, (retCode >= 0));
2904                    } catch (RemoteException e) {
2905                        Slog.w(TAG, "RemoveException when invoking call back");
2906                    }
2907                }
2908            }
2909        });
2910    }
2911
2912    @Override
2913    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2914            final IntentSender pi) {
2915        mContext.enforceCallingOrSelfPermission(
2916                android.Manifest.permission.CLEAR_APP_CACHE, null);
2917        // Queue up an async operation since clearing cache may take a little while.
2918        mHandler.post(new Runnable() {
2919            public void run() {
2920                mHandler.removeCallbacks(this);
2921                int retCode = -1;
2922                synchronized (mInstallLock) {
2923                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2924                    if (retCode < 0) {
2925                        Slog.w(TAG, "Couldn't clear application caches");
2926                    }
2927                }
2928                if(pi != null) {
2929                    try {
2930                        // Callback via pending intent
2931                        int code = (retCode >= 0) ? 1 : 0;
2932                        pi.sendIntent(null, code, null,
2933                                null, null);
2934                    } catch (SendIntentException e1) {
2935                        Slog.i(TAG, "Failed to send pending intent");
2936                    }
2937                }
2938            }
2939        });
2940    }
2941
2942    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2943        synchronized (mInstallLock) {
2944            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2945                throw new IOException("Failed to free enough space");
2946            }
2947        }
2948    }
2949
2950    @Override
2951    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2952        if (!sUserManager.exists(userId)) return null;
2953        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2954        synchronized (mPackages) {
2955            PackageParser.Activity a = mActivities.mActivities.get(component);
2956
2957            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2958            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2959                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2960                if (ps == null) return null;
2961                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2962                        userId);
2963            }
2964            if (mResolveComponentName.equals(component)) {
2965                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2966                        new PackageUserState(), userId);
2967            }
2968        }
2969        return null;
2970    }
2971
2972    @Override
2973    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2974            String resolvedType) {
2975        synchronized (mPackages) {
2976            if (component.equals(mResolveComponentName)) {
2977                // The resolver supports EVERYTHING!
2978                return true;
2979            }
2980            PackageParser.Activity a = mActivities.mActivities.get(component);
2981            if (a == null) {
2982                return false;
2983            }
2984            for (int i=0; i<a.intents.size(); i++) {
2985                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2986                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2987                    return true;
2988                }
2989            }
2990            return false;
2991        }
2992    }
2993
2994    @Override
2995    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2996        if (!sUserManager.exists(userId)) return null;
2997        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2998        synchronized (mPackages) {
2999            PackageParser.Activity a = mReceivers.mActivities.get(component);
3000            if (DEBUG_PACKAGE_INFO) Log.v(
3001                TAG, "getReceiverInfo " + component + ": " + a);
3002            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3003                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3004                if (ps == null) return null;
3005                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3006                        userId);
3007            }
3008        }
3009        return null;
3010    }
3011
3012    @Override
3013    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3014        if (!sUserManager.exists(userId)) return null;
3015        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3016        synchronized (mPackages) {
3017            PackageParser.Service s = mServices.mServices.get(component);
3018            if (DEBUG_PACKAGE_INFO) Log.v(
3019                TAG, "getServiceInfo " + component + ": " + s);
3020            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3021                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3022                if (ps == null) return null;
3023                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3024                        userId);
3025            }
3026        }
3027        return null;
3028    }
3029
3030    @Override
3031    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3032        if (!sUserManager.exists(userId)) return null;
3033        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3034        synchronized (mPackages) {
3035            PackageParser.Provider p = mProviders.mProviders.get(component);
3036            if (DEBUG_PACKAGE_INFO) Log.v(
3037                TAG, "getProviderInfo " + component + ": " + p);
3038            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3039                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3040                if (ps == null) return null;
3041                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3042                        userId);
3043            }
3044        }
3045        return null;
3046    }
3047
3048    @Override
3049    public String[] getSystemSharedLibraryNames() {
3050        Set<String> libSet;
3051        synchronized (mPackages) {
3052            libSet = mSharedLibraries.keySet();
3053            int size = libSet.size();
3054            if (size > 0) {
3055                String[] libs = new String[size];
3056                libSet.toArray(libs);
3057                return libs;
3058            }
3059        }
3060        return null;
3061    }
3062
3063    /**
3064     * @hide
3065     */
3066    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3067        synchronized (mPackages) {
3068            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3069            if (lib != null && lib.apk != null) {
3070                return mPackages.get(lib.apk);
3071            }
3072        }
3073        return null;
3074    }
3075
3076    @Override
3077    public FeatureInfo[] getSystemAvailableFeatures() {
3078        Collection<FeatureInfo> featSet;
3079        synchronized (mPackages) {
3080            featSet = mAvailableFeatures.values();
3081            int size = featSet.size();
3082            if (size > 0) {
3083                FeatureInfo[] features = new FeatureInfo[size+1];
3084                featSet.toArray(features);
3085                FeatureInfo fi = new FeatureInfo();
3086                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3087                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3088                features[size] = fi;
3089                return features;
3090            }
3091        }
3092        return null;
3093    }
3094
3095    @Override
3096    public boolean hasSystemFeature(String name) {
3097        synchronized (mPackages) {
3098            return mAvailableFeatures.containsKey(name);
3099        }
3100    }
3101
3102    private void checkValidCaller(int uid, int userId) {
3103        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3104            return;
3105
3106        throw new SecurityException("Caller uid=" + uid
3107                + " is not privileged to communicate with user=" + userId);
3108    }
3109
3110    @Override
3111    public int checkPermission(String permName, String pkgName, int userId) {
3112        if (!sUserManager.exists(userId)) {
3113            return PackageManager.PERMISSION_DENIED;
3114        }
3115
3116        synchronized (mPackages) {
3117            final PackageParser.Package p = mPackages.get(pkgName);
3118            if (p != null && p.mExtras != null) {
3119                final PackageSetting ps = (PackageSetting) p.mExtras;
3120                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3121                    return PackageManager.PERMISSION_GRANTED;
3122                }
3123            }
3124        }
3125
3126        return PackageManager.PERMISSION_DENIED;
3127    }
3128
3129    @Override
3130    public int checkUidPermission(String permName, int uid) {
3131        final int userId = UserHandle.getUserId(uid);
3132
3133        if (!sUserManager.exists(userId)) {
3134            return PackageManager.PERMISSION_DENIED;
3135        }
3136
3137        synchronized (mPackages) {
3138            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3139            if (obj != null) {
3140                final SettingBase ps = (SettingBase) obj;
3141                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3142                    return PackageManager.PERMISSION_GRANTED;
3143                }
3144            } else {
3145                ArraySet<String> perms = mSystemPermissions.get(uid);
3146                if (perms != null && perms.contains(permName)) {
3147                    return PackageManager.PERMISSION_GRANTED;
3148                }
3149            }
3150        }
3151
3152        return PackageManager.PERMISSION_DENIED;
3153    }
3154
3155    @Override
3156    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3157        if (UserHandle.getCallingUserId() != userId) {
3158            mContext.enforceCallingPermission(
3159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3160                    "isPermissionRevokedByPolicy for user " + userId);
3161        }
3162
3163        if (checkPermission(permission, packageName, userId)
3164                == PackageManager.PERMISSION_GRANTED) {
3165            return false;
3166        }
3167
3168        final long identity = Binder.clearCallingIdentity();
3169        try {
3170            final int flags = getPermissionFlags(permission, packageName, userId);
3171            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3172        } finally {
3173            Binder.restoreCallingIdentity(identity);
3174        }
3175    }
3176
3177    /**
3178     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3179     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3180     * @param checkShell TODO(yamasani):
3181     * @param message the message to log on security exception
3182     */
3183    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3184            boolean checkShell, String message) {
3185        if (userId < 0) {
3186            throw new IllegalArgumentException("Invalid userId " + userId);
3187        }
3188        if (checkShell) {
3189            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3190        }
3191        if (userId == UserHandle.getUserId(callingUid)) return;
3192        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3193            if (requireFullPermission) {
3194                mContext.enforceCallingOrSelfPermission(
3195                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3196            } else {
3197                try {
3198                    mContext.enforceCallingOrSelfPermission(
3199                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3200                } catch (SecurityException se) {
3201                    mContext.enforceCallingOrSelfPermission(
3202                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3203                }
3204            }
3205        }
3206    }
3207
3208    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3209        if (callingUid == Process.SHELL_UID) {
3210            if (userHandle >= 0
3211                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3212                throw new SecurityException("Shell does not have permission to access user "
3213                        + userHandle);
3214            } else if (userHandle < 0) {
3215                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3216                        + Debug.getCallers(3));
3217            }
3218        }
3219    }
3220
3221    private BasePermission findPermissionTreeLP(String permName) {
3222        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3223            if (permName.startsWith(bp.name) &&
3224                    permName.length() > bp.name.length() &&
3225                    permName.charAt(bp.name.length()) == '.') {
3226                return bp;
3227            }
3228        }
3229        return null;
3230    }
3231
3232    private BasePermission checkPermissionTreeLP(String permName) {
3233        if (permName != null) {
3234            BasePermission bp = findPermissionTreeLP(permName);
3235            if (bp != null) {
3236                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3237                    return bp;
3238                }
3239                throw new SecurityException("Calling uid "
3240                        + Binder.getCallingUid()
3241                        + " is not allowed to add to permission tree "
3242                        + bp.name + " owned by uid " + bp.uid);
3243            }
3244        }
3245        throw new SecurityException("No permission tree found for " + permName);
3246    }
3247
3248    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3249        if (s1 == null) {
3250            return s2 == null;
3251        }
3252        if (s2 == null) {
3253            return false;
3254        }
3255        if (s1.getClass() != s2.getClass()) {
3256            return false;
3257        }
3258        return s1.equals(s2);
3259    }
3260
3261    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3262        if (pi1.icon != pi2.icon) return false;
3263        if (pi1.logo != pi2.logo) return false;
3264        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3265        if (!compareStrings(pi1.name, pi2.name)) return false;
3266        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3267        // We'll take care of setting this one.
3268        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3269        // These are not currently stored in settings.
3270        //if (!compareStrings(pi1.group, pi2.group)) return false;
3271        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3272        //if (pi1.labelRes != pi2.labelRes) return false;
3273        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3274        return true;
3275    }
3276
3277    int permissionInfoFootprint(PermissionInfo info) {
3278        int size = info.name.length();
3279        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3280        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3281        return size;
3282    }
3283
3284    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3285        int size = 0;
3286        for (BasePermission perm : mSettings.mPermissions.values()) {
3287            if (perm.uid == tree.uid) {
3288                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3289            }
3290        }
3291        return size;
3292    }
3293
3294    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3295        // We calculate the max size of permissions defined by this uid and throw
3296        // if that plus the size of 'info' would exceed our stated maximum.
3297        if (tree.uid != Process.SYSTEM_UID) {
3298            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3299            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3300                throw new SecurityException("Permission tree size cap exceeded");
3301            }
3302        }
3303    }
3304
3305    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3306        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3307            throw new SecurityException("Label must be specified in permission");
3308        }
3309        BasePermission tree = checkPermissionTreeLP(info.name);
3310        BasePermission bp = mSettings.mPermissions.get(info.name);
3311        boolean added = bp == null;
3312        boolean changed = true;
3313        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3314        if (added) {
3315            enforcePermissionCapLocked(info, tree);
3316            bp = new BasePermission(info.name, tree.sourcePackage,
3317                    BasePermission.TYPE_DYNAMIC);
3318        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3319            throw new SecurityException(
3320                    "Not allowed to modify non-dynamic permission "
3321                    + info.name);
3322        } else {
3323            if (bp.protectionLevel == fixedLevel
3324                    && bp.perm.owner.equals(tree.perm.owner)
3325                    && bp.uid == tree.uid
3326                    && comparePermissionInfos(bp.perm.info, info)) {
3327                changed = false;
3328            }
3329        }
3330        bp.protectionLevel = fixedLevel;
3331        info = new PermissionInfo(info);
3332        info.protectionLevel = fixedLevel;
3333        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3334        bp.perm.info.packageName = tree.perm.info.packageName;
3335        bp.uid = tree.uid;
3336        if (added) {
3337            mSettings.mPermissions.put(info.name, bp);
3338        }
3339        if (changed) {
3340            if (!async) {
3341                mSettings.writeLPr();
3342            } else {
3343                scheduleWriteSettingsLocked();
3344            }
3345        }
3346        return added;
3347    }
3348
3349    @Override
3350    public boolean addPermission(PermissionInfo info) {
3351        synchronized (mPackages) {
3352            return addPermissionLocked(info, false);
3353        }
3354    }
3355
3356    @Override
3357    public boolean addPermissionAsync(PermissionInfo info) {
3358        synchronized (mPackages) {
3359            return addPermissionLocked(info, true);
3360        }
3361    }
3362
3363    @Override
3364    public void removePermission(String name) {
3365        synchronized (mPackages) {
3366            checkPermissionTreeLP(name);
3367            BasePermission bp = mSettings.mPermissions.get(name);
3368            if (bp != null) {
3369                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3370                    throw new SecurityException(
3371                            "Not allowed to modify non-dynamic permission "
3372                            + name);
3373                }
3374                mSettings.mPermissions.remove(name);
3375                mSettings.writeLPr();
3376            }
3377        }
3378    }
3379
3380    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3381            BasePermission bp) {
3382        int index = pkg.requestedPermissions.indexOf(bp.name);
3383        if (index == -1) {
3384            throw new SecurityException("Package " + pkg.packageName
3385                    + " has not requested permission " + bp.name);
3386        }
3387        if (!bp.isRuntime()) {
3388            throw new SecurityException("Permission " + bp.name
3389                    + " is not a changeable permission type");
3390        }
3391    }
3392
3393    @Override
3394    public void grantRuntimePermission(String packageName, String name, final int userId) {
3395        if (!sUserManager.exists(userId)) {
3396            Log.e(TAG, "No such user:" + userId);
3397            return;
3398        }
3399
3400        mContext.enforceCallingOrSelfPermission(
3401                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3402                "grantRuntimePermission");
3403
3404        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3405                "grantRuntimePermission");
3406
3407        final int uid;
3408        final SettingBase sb;
3409
3410        synchronized (mPackages) {
3411            final PackageParser.Package pkg = mPackages.get(packageName);
3412            if (pkg == null) {
3413                throw new IllegalArgumentException("Unknown package: " + packageName);
3414            }
3415
3416            final BasePermission bp = mSettings.mPermissions.get(name);
3417            if (bp == null) {
3418                throw new IllegalArgumentException("Unknown permission: " + name);
3419            }
3420
3421            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3422
3423            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3424            sb = (SettingBase) pkg.mExtras;
3425            if (sb == null) {
3426                throw new IllegalArgumentException("Unknown package: " + packageName);
3427            }
3428
3429            final PermissionsState permissionsState = sb.getPermissionsState();
3430
3431            final int flags = permissionsState.getPermissionFlags(name, userId);
3432            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3433                throw new SecurityException("Cannot grant system fixed permission: "
3434                        + name + " for package: " + packageName);
3435            }
3436
3437            final int result = permissionsState.grantRuntimePermission(bp, userId);
3438            switch (result) {
3439                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3440                    return;
3441                }
3442
3443                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3444                    mHandler.post(new Runnable() {
3445                        @Override
3446                        public void run() {
3447                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3448                        }
3449                    });
3450                } break;
3451            }
3452
3453            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3454
3455            // Not critical if that is lost - app has to request again.
3456            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3457        }
3458
3459        // Only need to do this if user is initialized. Otherwise it's a new user
3460        // and there are no processes running as the user yet and there's no need
3461        // to make an expensive call to remount processes for the changed permissions.
3462        if (READ_EXTERNAL_STORAGE.equals(name)
3463                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3464            final long token = Binder.clearCallingIdentity();
3465            try {
3466                if (sUserManager.isInitialized(userId)) {
3467                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3468                            MountServiceInternal.class);
3469                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3470                }
3471            } finally {
3472                Binder.restoreCallingIdentity(token);
3473            }
3474        }
3475    }
3476
3477    @Override
3478    public void revokeRuntimePermission(String packageName, String name, int userId) {
3479        if (!sUserManager.exists(userId)) {
3480            Log.e(TAG, "No such user:" + userId);
3481            return;
3482        }
3483
3484        mContext.enforceCallingOrSelfPermission(
3485                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3486                "revokeRuntimePermission");
3487
3488        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3489                "revokeRuntimePermission");
3490
3491        final SettingBase sb;
3492
3493        synchronized (mPackages) {
3494            final PackageParser.Package pkg = mPackages.get(packageName);
3495            if (pkg == null) {
3496                throw new IllegalArgumentException("Unknown package: " + packageName);
3497            }
3498
3499            final BasePermission bp = mSettings.mPermissions.get(name);
3500            if (bp == null) {
3501                throw new IllegalArgumentException("Unknown permission: " + name);
3502            }
3503
3504            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3505
3506            sb = (SettingBase) pkg.mExtras;
3507            if (sb == null) {
3508                throw new IllegalArgumentException("Unknown package: " + packageName);
3509            }
3510
3511            final PermissionsState permissionsState = sb.getPermissionsState();
3512
3513            final int flags = permissionsState.getPermissionFlags(name, userId);
3514            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3515                throw new SecurityException("Cannot revoke system fixed permission: "
3516                        + name + " for package: " + packageName);
3517            }
3518
3519            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3520                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3521                return;
3522            }
3523
3524            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3525
3526            // Critical, after this call app should never have the permission.
3527            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3528        }
3529
3530        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3531    }
3532
3533    @Override
3534    public void resetRuntimePermissions() {
3535        mContext.enforceCallingOrSelfPermission(
3536                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3537                "revokeRuntimePermission");
3538
3539        int callingUid = Binder.getCallingUid();
3540        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3541            mContext.enforceCallingOrSelfPermission(
3542                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3543                    "resetRuntimePermissions");
3544        }
3545
3546        synchronized (mPackages) {
3547            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3548            for (int userId : UserManagerService.getInstance().getUserIds()) {
3549                final int packageCount = mPackages.size();
3550                for (int i = 0; i < packageCount; i++) {
3551                    PackageParser.Package pkg = mPackages.valueAt(i);
3552                    if (!(pkg.mExtras instanceof PackageSetting)) {
3553                        continue;
3554                    }
3555                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3556                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
3557                }
3558            }
3559        }
3560    }
3561
3562    @Override
3563    public int getPermissionFlags(String name, String packageName, int userId) {
3564        if (!sUserManager.exists(userId)) {
3565            return 0;
3566        }
3567
3568        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3569
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3571                "getPermissionFlags");
3572
3573        synchronized (mPackages) {
3574            final PackageParser.Package pkg = mPackages.get(packageName);
3575            if (pkg == null) {
3576                throw new IllegalArgumentException("Unknown package: " + packageName);
3577            }
3578
3579            final BasePermission bp = mSettings.mPermissions.get(name);
3580            if (bp == null) {
3581                throw new IllegalArgumentException("Unknown permission: " + name);
3582            }
3583
3584            SettingBase sb = (SettingBase) pkg.mExtras;
3585            if (sb == null) {
3586                throw new IllegalArgumentException("Unknown package: " + packageName);
3587            }
3588
3589            PermissionsState permissionsState = sb.getPermissionsState();
3590            return permissionsState.getPermissionFlags(name, userId);
3591        }
3592    }
3593
3594    @Override
3595    public void updatePermissionFlags(String name, String packageName, int flagMask,
3596            int flagValues, int userId) {
3597        if (!sUserManager.exists(userId)) {
3598            return;
3599        }
3600
3601        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3602
3603        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3604                "updatePermissionFlags");
3605
3606        // Only the system can change system fixed flags.
3607        if (getCallingUid() != Process.SYSTEM_UID) {
3608            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3609            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3610        }
3611
3612        synchronized (mPackages) {
3613            final PackageParser.Package pkg = mPackages.get(packageName);
3614            if (pkg == null) {
3615                throw new IllegalArgumentException("Unknown package: " + packageName);
3616            }
3617
3618            final BasePermission bp = mSettings.mPermissions.get(name);
3619            if (bp == null) {
3620                throw new IllegalArgumentException("Unknown permission: " + name);
3621            }
3622
3623            SettingBase sb = (SettingBase) pkg.mExtras;
3624            if (sb == null) {
3625                throw new IllegalArgumentException("Unknown package: " + packageName);
3626            }
3627
3628            PermissionsState permissionsState = sb.getPermissionsState();
3629
3630            // Only the package manager can change flags for system component permissions.
3631            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3632            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3633                return;
3634            }
3635
3636            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3637
3638            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3639                // Install and runtime permissions are stored in different places,
3640                // so figure out what permission changed and persist the change.
3641                if (permissionsState.getInstallPermissionState(name) != null) {
3642                    scheduleWriteSettingsLocked();
3643                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3644                        || hadState) {
3645                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3646                }
3647            }
3648        }
3649    }
3650
3651    /**
3652     * Update the permission flags for all packages and runtime permissions of a user in order
3653     * to allow device or profile owner to remove POLICY_FIXED.
3654     */
3655    @Override
3656    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3657        if (!sUserManager.exists(userId)) {
3658            return;
3659        }
3660
3661        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3662
3663        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3664                "updatePermissionFlagsForAllApps");
3665
3666        // Only the system can change system fixed flags.
3667        if (getCallingUid() != Process.SYSTEM_UID) {
3668            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3669            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3670        }
3671
3672        synchronized (mPackages) {
3673            boolean changed = false;
3674            final int packageCount = mPackages.size();
3675            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3676                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3677                SettingBase sb = (SettingBase) pkg.mExtras;
3678                if (sb == null) {
3679                    continue;
3680                }
3681                PermissionsState permissionsState = sb.getPermissionsState();
3682                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3683                        userId, flagMask, flagValues);
3684            }
3685            if (changed) {
3686                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3687            }
3688        }
3689    }
3690
3691    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3692        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3693                != PackageManager.PERMISSION_GRANTED
3694            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3695                != PackageManager.PERMISSION_GRANTED) {
3696            throw new SecurityException(message + " requires "
3697                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3698                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3699        }
3700    }
3701
3702    @Override
3703    public boolean shouldShowRequestPermissionRationale(String permissionName,
3704            String packageName, int userId) {
3705        if (UserHandle.getCallingUserId() != userId) {
3706            mContext.enforceCallingPermission(
3707                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3708                    "canShowRequestPermissionRationale for user " + userId);
3709        }
3710
3711        final int uid = getPackageUid(packageName, userId);
3712        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3713            return false;
3714        }
3715
3716        if (checkPermission(permissionName, packageName, userId)
3717                == PackageManager.PERMISSION_GRANTED) {
3718            return false;
3719        }
3720
3721        final int flags;
3722
3723        final long identity = Binder.clearCallingIdentity();
3724        try {
3725            flags = getPermissionFlags(permissionName,
3726                    packageName, userId);
3727        } finally {
3728            Binder.restoreCallingIdentity(identity);
3729        }
3730
3731        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3732                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3733                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3734
3735        if ((flags & fixedFlags) != 0) {
3736            return false;
3737        }
3738
3739        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3740    }
3741
3742    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3743        BasePermission bp = mSettings.mPermissions.get(permission);
3744        if (bp == null) {
3745            throw new SecurityException("Missing " + permission + " permission");
3746        }
3747
3748        SettingBase sb = (SettingBase) pkg.mExtras;
3749        PermissionsState permissionsState = sb.getPermissionsState();
3750
3751        if (permissionsState.grantInstallPermission(bp) !=
3752                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3753            scheduleWriteSettingsLocked();
3754        }
3755    }
3756
3757    @Override
3758    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3759        mContext.enforceCallingOrSelfPermission(
3760                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3761                "addOnPermissionsChangeListener");
3762
3763        synchronized (mPackages) {
3764            mOnPermissionChangeListeners.addListenerLocked(listener);
3765        }
3766    }
3767
3768    @Override
3769    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3770        synchronized (mPackages) {
3771            mOnPermissionChangeListeners.removeListenerLocked(listener);
3772        }
3773    }
3774
3775    @Override
3776    public boolean isProtectedBroadcast(String actionName) {
3777        synchronized (mPackages) {
3778            return mProtectedBroadcasts.contains(actionName);
3779        }
3780    }
3781
3782    @Override
3783    public int checkSignatures(String pkg1, String pkg2) {
3784        synchronized (mPackages) {
3785            final PackageParser.Package p1 = mPackages.get(pkg1);
3786            final PackageParser.Package p2 = mPackages.get(pkg2);
3787            if (p1 == null || p1.mExtras == null
3788                    || p2 == null || p2.mExtras == null) {
3789                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3790            }
3791            return compareSignatures(p1.mSignatures, p2.mSignatures);
3792        }
3793    }
3794
3795    @Override
3796    public int checkUidSignatures(int uid1, int uid2) {
3797        // Map to base uids.
3798        uid1 = UserHandle.getAppId(uid1);
3799        uid2 = UserHandle.getAppId(uid2);
3800        // reader
3801        synchronized (mPackages) {
3802            Signature[] s1;
3803            Signature[] s2;
3804            Object obj = mSettings.getUserIdLPr(uid1);
3805            if (obj != null) {
3806                if (obj instanceof SharedUserSetting) {
3807                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3808                } else if (obj instanceof PackageSetting) {
3809                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3810                } else {
3811                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3812                }
3813            } else {
3814                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3815            }
3816            obj = mSettings.getUserIdLPr(uid2);
3817            if (obj != null) {
3818                if (obj instanceof SharedUserSetting) {
3819                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3820                } else if (obj instanceof PackageSetting) {
3821                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3822                } else {
3823                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3824                }
3825            } else {
3826                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3827            }
3828            return compareSignatures(s1, s2);
3829        }
3830    }
3831
3832    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3833        final long identity = Binder.clearCallingIdentity();
3834        try {
3835            if (sb instanceof SharedUserSetting) {
3836                SharedUserSetting sus = (SharedUserSetting) sb;
3837                final int packageCount = sus.packages.size();
3838                for (int i = 0; i < packageCount; i++) {
3839                    PackageSetting susPs = sus.packages.valueAt(i);
3840                    if (userId == UserHandle.USER_ALL) {
3841                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3842                    } else {
3843                        final int uid = UserHandle.getUid(userId, susPs.appId);
3844                        killUid(uid, reason);
3845                    }
3846                }
3847            } else if (sb instanceof PackageSetting) {
3848                PackageSetting ps = (PackageSetting) sb;
3849                if (userId == UserHandle.USER_ALL) {
3850                    killApplication(ps.pkg.packageName, ps.appId, reason);
3851                } else {
3852                    final int uid = UserHandle.getUid(userId, ps.appId);
3853                    killUid(uid, reason);
3854                }
3855            }
3856        } finally {
3857            Binder.restoreCallingIdentity(identity);
3858        }
3859    }
3860
3861    private static void killUid(int uid, String reason) {
3862        IActivityManager am = ActivityManagerNative.getDefault();
3863        if (am != null) {
3864            try {
3865                am.killUid(uid, reason);
3866            } catch (RemoteException e) {
3867                /* ignore - same process */
3868            }
3869        }
3870    }
3871
3872    /**
3873     * Compares two sets of signatures. Returns:
3874     * <br />
3875     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3876     * <br />
3877     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3878     * <br />
3879     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3880     * <br />
3881     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3882     * <br />
3883     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3884     */
3885    static int compareSignatures(Signature[] s1, Signature[] s2) {
3886        if (s1 == null) {
3887            return s2 == null
3888                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3889                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3890        }
3891
3892        if (s2 == null) {
3893            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3894        }
3895
3896        if (s1.length != s2.length) {
3897            return PackageManager.SIGNATURE_NO_MATCH;
3898        }
3899
3900        // Since both signature sets are of size 1, we can compare without HashSets.
3901        if (s1.length == 1) {
3902            return s1[0].equals(s2[0]) ?
3903                    PackageManager.SIGNATURE_MATCH :
3904                    PackageManager.SIGNATURE_NO_MATCH;
3905        }
3906
3907        ArraySet<Signature> set1 = new ArraySet<Signature>();
3908        for (Signature sig : s1) {
3909            set1.add(sig);
3910        }
3911        ArraySet<Signature> set2 = new ArraySet<Signature>();
3912        for (Signature sig : s2) {
3913            set2.add(sig);
3914        }
3915        // Make sure s2 contains all signatures in s1.
3916        if (set1.equals(set2)) {
3917            return PackageManager.SIGNATURE_MATCH;
3918        }
3919        return PackageManager.SIGNATURE_NO_MATCH;
3920    }
3921
3922    /**
3923     * If the database version for this type of package (internal storage or
3924     * external storage) is less than the version where package signatures
3925     * were updated, return true.
3926     */
3927    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3928        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3929        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3930    }
3931
3932    /**
3933     * Used for backward compatibility to make sure any packages with
3934     * certificate chains get upgraded to the new style. {@code existingSigs}
3935     * will be in the old format (since they were stored on disk from before the
3936     * system upgrade) and {@code scannedSigs} will be in the newer format.
3937     */
3938    private int compareSignaturesCompat(PackageSignatures existingSigs,
3939            PackageParser.Package scannedPkg) {
3940        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3941            return PackageManager.SIGNATURE_NO_MATCH;
3942        }
3943
3944        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3945        for (Signature sig : existingSigs.mSignatures) {
3946            existingSet.add(sig);
3947        }
3948        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3949        for (Signature sig : scannedPkg.mSignatures) {
3950            try {
3951                Signature[] chainSignatures = sig.getChainSignatures();
3952                for (Signature chainSig : chainSignatures) {
3953                    scannedCompatSet.add(chainSig);
3954                }
3955            } catch (CertificateEncodingException e) {
3956                scannedCompatSet.add(sig);
3957            }
3958        }
3959        /*
3960         * Make sure the expanded scanned set contains all signatures in the
3961         * existing one.
3962         */
3963        if (scannedCompatSet.equals(existingSet)) {
3964            // Migrate the old signatures to the new scheme.
3965            existingSigs.assignSignatures(scannedPkg.mSignatures);
3966            // The new KeySets will be re-added later in the scanning process.
3967            synchronized (mPackages) {
3968                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3969            }
3970            return PackageManager.SIGNATURE_MATCH;
3971        }
3972        return PackageManager.SIGNATURE_NO_MATCH;
3973    }
3974
3975    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3976        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3977        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
3978    }
3979
3980    private int compareSignaturesRecover(PackageSignatures existingSigs,
3981            PackageParser.Package scannedPkg) {
3982        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3983            return PackageManager.SIGNATURE_NO_MATCH;
3984        }
3985
3986        String msg = null;
3987        try {
3988            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3989                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3990                        + scannedPkg.packageName);
3991                return PackageManager.SIGNATURE_MATCH;
3992            }
3993        } catch (CertificateException e) {
3994            msg = e.getMessage();
3995        }
3996
3997        logCriticalInfo(Log.INFO,
3998                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3999        return PackageManager.SIGNATURE_NO_MATCH;
4000    }
4001
4002    @Override
4003    public String[] getPackagesForUid(int uid) {
4004        uid = UserHandle.getAppId(uid);
4005        // reader
4006        synchronized (mPackages) {
4007            Object obj = mSettings.getUserIdLPr(uid);
4008            if (obj instanceof SharedUserSetting) {
4009                final SharedUserSetting sus = (SharedUserSetting) obj;
4010                final int N = sus.packages.size();
4011                final String[] res = new String[N];
4012                final Iterator<PackageSetting> it = sus.packages.iterator();
4013                int i = 0;
4014                while (it.hasNext()) {
4015                    res[i++] = it.next().name;
4016                }
4017                return res;
4018            } else if (obj instanceof PackageSetting) {
4019                final PackageSetting ps = (PackageSetting) obj;
4020                return new String[] { ps.name };
4021            }
4022        }
4023        return null;
4024    }
4025
4026    @Override
4027    public String getNameForUid(int uid) {
4028        // reader
4029        synchronized (mPackages) {
4030            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4031            if (obj instanceof SharedUserSetting) {
4032                final SharedUserSetting sus = (SharedUserSetting) obj;
4033                return sus.name + ":" + sus.userId;
4034            } else if (obj instanceof PackageSetting) {
4035                final PackageSetting ps = (PackageSetting) obj;
4036                return ps.name;
4037            }
4038        }
4039        return null;
4040    }
4041
4042    @Override
4043    public int getUidForSharedUser(String sharedUserName) {
4044        if(sharedUserName == null) {
4045            return -1;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4050            if (suid == null) {
4051                return -1;
4052            }
4053            return suid.userId;
4054        }
4055    }
4056
4057    @Override
4058    public int getFlagsForUid(int uid) {
4059        synchronized (mPackages) {
4060            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4061            if (obj instanceof SharedUserSetting) {
4062                final SharedUserSetting sus = (SharedUserSetting) obj;
4063                return sus.pkgFlags;
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return ps.pkgFlags;
4067            }
4068        }
4069        return 0;
4070    }
4071
4072    @Override
4073    public int getPrivateFlagsForUid(int uid) {
4074        synchronized (mPackages) {
4075            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4076            if (obj instanceof SharedUserSetting) {
4077                final SharedUserSetting sus = (SharedUserSetting) obj;
4078                return sus.pkgPrivateFlags;
4079            } else if (obj instanceof PackageSetting) {
4080                final PackageSetting ps = (PackageSetting) obj;
4081                return ps.pkgPrivateFlags;
4082            }
4083        }
4084        return 0;
4085    }
4086
4087    @Override
4088    public boolean isUidPrivileged(int uid) {
4089        uid = UserHandle.getAppId(uid);
4090        // reader
4091        synchronized (mPackages) {
4092            Object obj = mSettings.getUserIdLPr(uid);
4093            if (obj instanceof SharedUserSetting) {
4094                final SharedUserSetting sus = (SharedUserSetting) obj;
4095                final Iterator<PackageSetting> it = sus.packages.iterator();
4096                while (it.hasNext()) {
4097                    if (it.next().isPrivileged()) {
4098                        return true;
4099                    }
4100                }
4101            } else if (obj instanceof PackageSetting) {
4102                final PackageSetting ps = (PackageSetting) obj;
4103                return ps.isPrivileged();
4104            }
4105        }
4106        return false;
4107    }
4108
4109    @Override
4110    public String[] getAppOpPermissionPackages(String permissionName) {
4111        synchronized (mPackages) {
4112            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4113            if (pkgs == null) {
4114                return null;
4115            }
4116            return pkgs.toArray(new String[pkgs.size()]);
4117        }
4118    }
4119
4120    @Override
4121    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4122            int flags, int userId) {
4123        if (!sUserManager.exists(userId)) return null;
4124        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4125        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4126        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4127    }
4128
4129    @Override
4130    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4131            IntentFilter filter, int match, ComponentName activity) {
4132        final int userId = UserHandle.getCallingUserId();
4133        if (DEBUG_PREFERRED) {
4134            Log.v(TAG, "setLastChosenActivity intent=" + intent
4135                + " resolvedType=" + resolvedType
4136                + " flags=" + flags
4137                + " filter=" + filter
4138                + " match=" + match
4139                + " activity=" + activity);
4140            filter.dump(new PrintStreamPrinter(System.out), "    ");
4141        }
4142        intent.setComponent(null);
4143        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4144        // Find any earlier preferred or last chosen entries and nuke them
4145        findPreferredActivity(intent, resolvedType,
4146                flags, query, 0, false, true, false, userId);
4147        // Add the new activity as the last chosen for this filter
4148        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4149                "Setting last chosen");
4150    }
4151
4152    @Override
4153    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4154        final int userId = UserHandle.getCallingUserId();
4155        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4156        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4157        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4158                false, false, false, userId);
4159    }
4160
4161    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4162            int flags, List<ResolveInfo> query, int userId) {
4163        if (query != null) {
4164            final int N = query.size();
4165            if (N == 1) {
4166                return query.get(0);
4167            } else if (N > 1) {
4168                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4169                // If there is more than one activity with the same priority,
4170                // then let the user decide between them.
4171                ResolveInfo r0 = query.get(0);
4172                ResolveInfo r1 = query.get(1);
4173                if (DEBUG_INTENT_MATCHING || debug) {
4174                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4175                            + r1.activityInfo.name + "=" + r1.priority);
4176                }
4177                // If the first activity has a higher priority, or a different
4178                // default, then it is always desireable to pick it.
4179                if (r0.priority != r1.priority
4180                        || r0.preferredOrder != r1.preferredOrder
4181                        || r0.isDefault != r1.isDefault) {
4182                    return query.get(0);
4183                }
4184                // If we have saved a preference for a preferred activity for
4185                // this Intent, use that.
4186                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4187                        flags, query, r0.priority, true, false, debug, userId);
4188                if (ri != null) {
4189                    return ri;
4190                }
4191                if (userId != 0) {
4192                    ri = new ResolveInfo(mResolveInfo);
4193                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4194                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4195                            ri.activityInfo.applicationInfo);
4196                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4197                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4198                    return ri;
4199                }
4200                return mResolveInfo;
4201            }
4202        }
4203        return null;
4204    }
4205
4206    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4207            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4208        final int N = query.size();
4209        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4210                .get(userId);
4211        // Get the list of persistent preferred activities that handle the intent
4212        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4213        List<PersistentPreferredActivity> pprefs = ppir != null
4214                ? ppir.queryIntent(intent, resolvedType,
4215                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4216                : null;
4217        if (pprefs != null && pprefs.size() > 0) {
4218            final int M = pprefs.size();
4219            for (int i=0; i<M; i++) {
4220                final PersistentPreferredActivity ppa = pprefs.get(i);
4221                if (DEBUG_PREFERRED || debug) {
4222                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4223                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4224                            + "\n  component=" + ppa.mComponent);
4225                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4226                }
4227                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4228                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4229                if (DEBUG_PREFERRED || debug) {
4230                    Slog.v(TAG, "Found persistent preferred activity:");
4231                    if (ai != null) {
4232                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4233                    } else {
4234                        Slog.v(TAG, "  null");
4235                    }
4236                }
4237                if (ai == null) {
4238                    // This previously registered persistent preferred activity
4239                    // component is no longer known. Ignore it and do NOT remove it.
4240                    continue;
4241                }
4242                for (int j=0; j<N; j++) {
4243                    final ResolveInfo ri = query.get(j);
4244                    if (!ri.activityInfo.applicationInfo.packageName
4245                            .equals(ai.applicationInfo.packageName)) {
4246                        continue;
4247                    }
4248                    if (!ri.activityInfo.name.equals(ai.name)) {
4249                        continue;
4250                    }
4251                    //  Found a persistent preference that can handle the intent.
4252                    if (DEBUG_PREFERRED || debug) {
4253                        Slog.v(TAG, "Returning persistent preferred activity: " +
4254                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4255                    }
4256                    return ri;
4257                }
4258            }
4259        }
4260        return null;
4261    }
4262
4263    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4264            List<ResolveInfo> query, int priority, boolean always,
4265            boolean removeMatches, boolean debug, int userId) {
4266        if (!sUserManager.exists(userId)) return null;
4267        // writer
4268        synchronized (mPackages) {
4269            if (intent.getSelector() != null) {
4270                intent = intent.getSelector();
4271            }
4272            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4273
4274            // Try to find a matching persistent preferred activity.
4275            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4276                    debug, userId);
4277
4278            // If a persistent preferred activity matched, use it.
4279            if (pri != null) {
4280                return pri;
4281            }
4282
4283            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4284            // Get the list of preferred activities that handle the intent
4285            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4286            List<PreferredActivity> prefs = pir != null
4287                    ? pir.queryIntent(intent, resolvedType,
4288                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4289                    : null;
4290            if (prefs != null && prefs.size() > 0) {
4291                boolean changed = false;
4292                try {
4293                    // First figure out how good the original match set is.
4294                    // We will only allow preferred activities that came
4295                    // from the same match quality.
4296                    int match = 0;
4297
4298                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4299
4300                    final int N = query.size();
4301                    for (int j=0; j<N; j++) {
4302                        final ResolveInfo ri = query.get(j);
4303                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4304                                + ": 0x" + Integer.toHexString(match));
4305                        if (ri.match > match) {
4306                            match = ri.match;
4307                        }
4308                    }
4309
4310                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4311                            + Integer.toHexString(match));
4312
4313                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4314                    final int M = prefs.size();
4315                    for (int i=0; i<M; i++) {
4316                        final PreferredActivity pa = prefs.get(i);
4317                        if (DEBUG_PREFERRED || debug) {
4318                            Slog.v(TAG, "Checking PreferredActivity ds="
4319                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4320                                    + "\n  component=" + pa.mPref.mComponent);
4321                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4322                        }
4323                        if (pa.mPref.mMatch != match) {
4324                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4325                                    + Integer.toHexString(pa.mPref.mMatch));
4326                            continue;
4327                        }
4328                        // If it's not an "always" type preferred activity and that's what we're
4329                        // looking for, skip it.
4330                        if (always && !pa.mPref.mAlways) {
4331                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4332                            continue;
4333                        }
4334                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4335                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4336                        if (DEBUG_PREFERRED || debug) {
4337                            Slog.v(TAG, "Found preferred activity:");
4338                            if (ai != null) {
4339                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4340                            } else {
4341                                Slog.v(TAG, "  null");
4342                            }
4343                        }
4344                        if (ai == null) {
4345                            // This previously registered preferred activity
4346                            // component is no longer known.  Most likely an update
4347                            // to the app was installed and in the new version this
4348                            // component no longer exists.  Clean it up by removing
4349                            // it from the preferred activities list, and skip it.
4350                            Slog.w(TAG, "Removing dangling preferred activity: "
4351                                    + pa.mPref.mComponent);
4352                            pir.removeFilter(pa);
4353                            changed = true;
4354                            continue;
4355                        }
4356                        for (int j=0; j<N; j++) {
4357                            final ResolveInfo ri = query.get(j);
4358                            if (!ri.activityInfo.applicationInfo.packageName
4359                                    .equals(ai.applicationInfo.packageName)) {
4360                                continue;
4361                            }
4362                            if (!ri.activityInfo.name.equals(ai.name)) {
4363                                continue;
4364                            }
4365
4366                            if (removeMatches) {
4367                                pir.removeFilter(pa);
4368                                changed = true;
4369                                if (DEBUG_PREFERRED) {
4370                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4371                                }
4372                                break;
4373                            }
4374
4375                            // Okay we found a previously set preferred or last chosen app.
4376                            // If the result set is different from when this
4377                            // was created, we need to clear it and re-ask the
4378                            // user their preference, if we're looking for an "always" type entry.
4379                            if (always && !pa.mPref.sameSet(query)) {
4380                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4381                                        + intent + " type " + resolvedType);
4382                                if (DEBUG_PREFERRED) {
4383                                    Slog.v(TAG, "Removing preferred activity since set changed "
4384                                            + pa.mPref.mComponent);
4385                                }
4386                                pir.removeFilter(pa);
4387                                // Re-add the filter as a "last chosen" entry (!always)
4388                                PreferredActivity lastChosen = new PreferredActivity(
4389                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4390                                pir.addFilter(lastChosen);
4391                                changed = true;
4392                                return null;
4393                            }
4394
4395                            // Yay! Either the set matched or we're looking for the last chosen
4396                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4397                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4398                            return ri;
4399                        }
4400                    }
4401                } finally {
4402                    if (changed) {
4403                        if (DEBUG_PREFERRED) {
4404                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4405                        }
4406                        scheduleWritePackageRestrictionsLocked(userId);
4407                    }
4408                }
4409            }
4410        }
4411        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4412        return null;
4413    }
4414
4415    /*
4416     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4417     */
4418    @Override
4419    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4420            int targetUserId) {
4421        mContext.enforceCallingOrSelfPermission(
4422                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4423        List<CrossProfileIntentFilter> matches =
4424                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4425        if (matches != null) {
4426            int size = matches.size();
4427            for (int i = 0; i < size; i++) {
4428                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4429            }
4430        }
4431        if (hasWebURI(intent)) {
4432            // cross-profile app linking works only towards the parent.
4433            final UserInfo parent = getProfileParent(sourceUserId);
4434            synchronized(mPackages) {
4435                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4436                        intent, resolvedType, 0, sourceUserId, parent.id);
4437                return xpDomainInfo != null;
4438            }
4439        }
4440        return false;
4441    }
4442
4443    private UserInfo getProfileParent(int userId) {
4444        final long identity = Binder.clearCallingIdentity();
4445        try {
4446            return sUserManager.getProfileParent(userId);
4447        } finally {
4448            Binder.restoreCallingIdentity(identity);
4449        }
4450    }
4451
4452    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4453            String resolvedType, int userId) {
4454        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4455        if (resolver != null) {
4456            return resolver.queryIntent(intent, resolvedType, false, userId);
4457        }
4458        return null;
4459    }
4460
4461    @Override
4462    public List<ResolveInfo> queryIntentActivities(Intent intent,
4463            String resolvedType, int flags, int userId) {
4464        if (!sUserManager.exists(userId)) return Collections.emptyList();
4465        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4466        ComponentName comp = intent.getComponent();
4467        if (comp == null) {
4468            if (intent.getSelector() != null) {
4469                intent = intent.getSelector();
4470                comp = intent.getComponent();
4471            }
4472        }
4473
4474        if (comp != null) {
4475            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4476            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4477            if (ai != null) {
4478                final ResolveInfo ri = new ResolveInfo();
4479                ri.activityInfo = ai;
4480                list.add(ri);
4481            }
4482            return list;
4483        }
4484
4485        // reader
4486        synchronized (mPackages) {
4487            final String pkgName = intent.getPackage();
4488            if (pkgName == null) {
4489                List<CrossProfileIntentFilter> matchingFilters =
4490                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4491                // Check for results that need to skip the current profile.
4492                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4493                        resolvedType, flags, userId);
4494                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4495                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4496                    result.add(xpResolveInfo);
4497                    return filterIfNotPrimaryUser(result, userId);
4498                }
4499
4500                // Check for results in the current profile.
4501                List<ResolveInfo> result = mActivities.queryIntent(
4502                        intent, resolvedType, flags, userId);
4503
4504                // Check for cross profile results.
4505                xpResolveInfo = queryCrossProfileIntents(
4506                        matchingFilters, intent, resolvedType, flags, userId);
4507                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4508                    result.add(xpResolveInfo);
4509                    Collections.sort(result, mResolvePrioritySorter);
4510                }
4511                result = filterIfNotPrimaryUser(result, userId);
4512                if (hasWebURI(intent)) {
4513                    CrossProfileDomainInfo xpDomainInfo = null;
4514                    final UserInfo parent = getProfileParent(userId);
4515                    if (parent != null) {
4516                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4517                                flags, userId, parent.id);
4518                    }
4519                    if (xpDomainInfo != null) {
4520                        if (xpResolveInfo != null) {
4521                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4522                            // in the result.
4523                            result.remove(xpResolveInfo);
4524                        }
4525                        if (result.size() == 0) {
4526                            result.add(xpDomainInfo.resolveInfo);
4527                            return result;
4528                        }
4529                    } else if (result.size() <= 1) {
4530                        return result;
4531                    }
4532                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4533                            xpDomainInfo, userId);
4534                    Collections.sort(result, mResolvePrioritySorter);
4535                }
4536                return result;
4537            }
4538            final PackageParser.Package pkg = mPackages.get(pkgName);
4539            if (pkg != null) {
4540                return filterIfNotPrimaryUser(
4541                        mActivities.queryIntentForPackage(
4542                                intent, resolvedType, flags, pkg.activities, userId),
4543                        userId);
4544            }
4545            return new ArrayList<ResolveInfo>();
4546        }
4547    }
4548
4549    private static class CrossProfileDomainInfo {
4550        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4551        ResolveInfo resolveInfo;
4552        /* Best domain verification status of the activities found in the other profile */
4553        int bestDomainVerificationStatus;
4554    }
4555
4556    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4557            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4558        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4559                sourceUserId)) {
4560            return null;
4561        }
4562        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4563                resolvedType, flags, parentUserId);
4564
4565        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4566            return null;
4567        }
4568        CrossProfileDomainInfo result = null;
4569        int size = resultTargetUser.size();
4570        for (int i = 0; i < size; i++) {
4571            ResolveInfo riTargetUser = resultTargetUser.get(i);
4572            // Intent filter verification is only for filters that specify a host. So don't return
4573            // those that handle all web uris.
4574            if (riTargetUser.handleAllWebDataURI) {
4575                continue;
4576            }
4577            String packageName = riTargetUser.activityInfo.packageName;
4578            PackageSetting ps = mSettings.mPackages.get(packageName);
4579            if (ps == null) {
4580                continue;
4581            }
4582            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4583            int status = (int)(verificationState >> 32);
4584            if (result == null) {
4585                result = new CrossProfileDomainInfo();
4586                result.resolveInfo =
4587                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4588                result.bestDomainVerificationStatus = status;
4589            } else {
4590                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4591                        result.bestDomainVerificationStatus);
4592            }
4593        }
4594        // Don't consider matches with status NEVER across profiles.
4595        if (result != null && result.bestDomainVerificationStatus
4596                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4597            return null;
4598        }
4599        return result;
4600    }
4601
4602    /**
4603     * Verification statuses are ordered from the worse to the best, except for
4604     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4605     */
4606    private int bestDomainVerificationStatus(int status1, int status2) {
4607        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4608            return status2;
4609        }
4610        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4611            return status1;
4612        }
4613        return (int) MathUtils.max(status1, status2);
4614    }
4615
4616    private boolean isUserEnabled(int userId) {
4617        long callingId = Binder.clearCallingIdentity();
4618        try {
4619            UserInfo userInfo = sUserManager.getUserInfo(userId);
4620            return userInfo != null && userInfo.isEnabled();
4621        } finally {
4622            Binder.restoreCallingIdentity(callingId);
4623        }
4624    }
4625
4626    /**
4627     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4628     *
4629     * @return filtered list
4630     */
4631    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4632        if (userId == UserHandle.USER_OWNER) {
4633            return resolveInfos;
4634        }
4635        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4636            ResolveInfo info = resolveInfos.get(i);
4637            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4638                resolveInfos.remove(i);
4639            }
4640        }
4641        return resolveInfos;
4642    }
4643
4644    private static boolean hasWebURI(Intent intent) {
4645        if (intent.getData() == null) {
4646            return false;
4647        }
4648        final String scheme = intent.getScheme();
4649        if (TextUtils.isEmpty(scheme)) {
4650            return false;
4651        }
4652        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4653    }
4654
4655    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4656            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4657            int userId) {
4658        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4659
4660        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4661            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4662                    candidates.size());
4663        }
4664
4665        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4666        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4667        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4668        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4669        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4670
4671        synchronized (mPackages) {
4672            final int count = candidates.size();
4673            // First, try to use linked apps. Partition the candidates into four lists:
4674            // one for the final results, one for the "do not use ever", one for "undefined status"
4675            // and finally one for "browser app type".
4676            for (int n=0; n<count; n++) {
4677                ResolveInfo info = candidates.get(n);
4678                String packageName = info.activityInfo.packageName;
4679                PackageSetting ps = mSettings.mPackages.get(packageName);
4680                if (ps != null) {
4681                    // Add to the special match all list (Browser use case)
4682                    if (info.handleAllWebDataURI) {
4683                        matchAllList.add(info);
4684                        continue;
4685                    }
4686                    // Try to get the status from User settings first
4687                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4688                    int status = (int)(packedStatus >> 32);
4689                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4690                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4691                        if (DEBUG_DOMAIN_VERIFICATION) {
4692                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4693                                    + " : linkgen=" + linkGeneration);
4694                        }
4695                        // Use link-enabled generation as preferredOrder, i.e.
4696                        // prefer newly-enabled over earlier-enabled.
4697                        info.preferredOrder = linkGeneration;
4698                        alwaysList.add(info);
4699                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4700                        if (DEBUG_DOMAIN_VERIFICATION) {
4701                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4702                        }
4703                        neverList.add(info);
4704                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4705                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4706                        if (DEBUG_DOMAIN_VERIFICATION) {
4707                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4708                        }
4709                        undefinedList.add(info);
4710                    }
4711                }
4712            }
4713            // First try to add the "always" resolution(s) for the current user, if any
4714            if (alwaysList.size() > 0) {
4715                result.addAll(alwaysList);
4716            // if there is an "always" for the parent user, add it.
4717            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4718                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4719                result.add(xpDomainInfo.resolveInfo);
4720            } else {
4721                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4722                result.addAll(undefinedList);
4723                if (xpDomainInfo != null && (
4724                        xpDomainInfo.bestDomainVerificationStatus
4725                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4726                        || xpDomainInfo.bestDomainVerificationStatus
4727                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4728                    result.add(xpDomainInfo.resolveInfo);
4729                }
4730                // Also add Browsers (all of them or only the default one)
4731                if ((matchFlags & MATCH_ALL) != 0) {
4732                    result.addAll(matchAllList);
4733                } else {
4734                    // Browser/generic handling case.  If there's a default browser, go straight
4735                    // to that (but only if there is no other higher-priority match).
4736                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4737                    int maxMatchPrio = 0;
4738                    ResolveInfo defaultBrowserMatch = null;
4739                    final int numCandidates = matchAllList.size();
4740                    for (int n = 0; n < numCandidates; n++) {
4741                        ResolveInfo info = matchAllList.get(n);
4742                        // track the highest overall match priority...
4743                        if (info.priority > maxMatchPrio) {
4744                            maxMatchPrio = info.priority;
4745                        }
4746                        // ...and the highest-priority default browser match
4747                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4748                            if (defaultBrowserMatch == null
4749                                    || (defaultBrowserMatch.priority < info.priority)) {
4750                                if (debug) {
4751                                    Slog.v(TAG, "Considering default browser match " + info);
4752                                }
4753                                defaultBrowserMatch = info;
4754                            }
4755                        }
4756                    }
4757                    if (defaultBrowserMatch != null
4758                            && defaultBrowserMatch.priority >= maxMatchPrio
4759                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4760                    {
4761                        if (debug) {
4762                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4763                        }
4764                        result.add(defaultBrowserMatch);
4765                    } else {
4766                        result.addAll(matchAllList);
4767                    }
4768                }
4769
4770                // If there is nothing selected, add all candidates and remove the ones that the user
4771                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4772                if (result.size() == 0) {
4773                    result.addAll(candidates);
4774                    result.removeAll(neverList);
4775                }
4776            }
4777        }
4778        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4779            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4780                    result.size());
4781            for (ResolveInfo info : result) {
4782                Slog.v(TAG, "  + " + info.activityInfo);
4783            }
4784        }
4785        return result;
4786    }
4787
4788    // Returns a packed value as a long:
4789    //
4790    // high 'int'-sized word: link status: undefined/ask/never/always.
4791    // low 'int'-sized word: relative priority among 'always' results.
4792    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4793        long result = ps.getDomainVerificationStatusForUser(userId);
4794        // if none available, get the master status
4795        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4796            if (ps.getIntentFilterVerificationInfo() != null) {
4797                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4798            }
4799        }
4800        return result;
4801    }
4802
4803    private ResolveInfo querySkipCurrentProfileIntents(
4804            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4805            int flags, int sourceUserId) {
4806        if (matchingFilters != null) {
4807            int size = matchingFilters.size();
4808            for (int i = 0; i < size; i ++) {
4809                CrossProfileIntentFilter filter = matchingFilters.get(i);
4810                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4811                    // Checking if there are activities in the target user that can handle the
4812                    // intent.
4813                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4814                            flags, sourceUserId);
4815                    if (resolveInfo != null) {
4816                        return resolveInfo;
4817                    }
4818                }
4819            }
4820        }
4821        return null;
4822    }
4823
4824    // Return matching ResolveInfo if any for skip current profile intent filters.
4825    private ResolveInfo queryCrossProfileIntents(
4826            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4827            int flags, int sourceUserId) {
4828        if (matchingFilters != null) {
4829            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4830            // match the same intent. For performance reasons, it is better not to
4831            // run queryIntent twice for the same userId
4832            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4833            int size = matchingFilters.size();
4834            for (int i = 0; i < size; i++) {
4835                CrossProfileIntentFilter filter = matchingFilters.get(i);
4836                int targetUserId = filter.getTargetUserId();
4837                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4838                        && !alreadyTriedUserIds.get(targetUserId)) {
4839                    // Checking if there are activities in the target user that can handle the
4840                    // intent.
4841                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4842                            flags, sourceUserId);
4843                    if (resolveInfo != null) return resolveInfo;
4844                    alreadyTriedUserIds.put(targetUserId, true);
4845                }
4846            }
4847        }
4848        return null;
4849    }
4850
4851    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4852            String resolvedType, int flags, int sourceUserId) {
4853        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4854                resolvedType, flags, filter.getTargetUserId());
4855        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4856            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4857        }
4858        return null;
4859    }
4860
4861    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4862            int sourceUserId, int targetUserId) {
4863        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4864        String className;
4865        if (targetUserId == UserHandle.USER_OWNER) {
4866            className = FORWARD_INTENT_TO_USER_OWNER;
4867        } else {
4868            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4869        }
4870        ComponentName forwardingActivityComponentName = new ComponentName(
4871                mAndroidApplication.packageName, className);
4872        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4873                sourceUserId);
4874        if (targetUserId == UserHandle.USER_OWNER) {
4875            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4876            forwardingResolveInfo.noResourceId = true;
4877        }
4878        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4879        forwardingResolveInfo.priority = 0;
4880        forwardingResolveInfo.preferredOrder = 0;
4881        forwardingResolveInfo.match = 0;
4882        forwardingResolveInfo.isDefault = true;
4883        forwardingResolveInfo.filter = filter;
4884        forwardingResolveInfo.targetUserId = targetUserId;
4885        return forwardingResolveInfo;
4886    }
4887
4888    @Override
4889    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4890            Intent[] specifics, String[] specificTypes, Intent intent,
4891            String resolvedType, int flags, int userId) {
4892        if (!sUserManager.exists(userId)) return Collections.emptyList();
4893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4894                false, "query intent activity options");
4895        final String resultsAction = intent.getAction();
4896
4897        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4898                | PackageManager.GET_RESOLVED_FILTER, userId);
4899
4900        if (DEBUG_INTENT_MATCHING) {
4901            Log.v(TAG, "Query " + intent + ": " + results);
4902        }
4903
4904        int specificsPos = 0;
4905        int N;
4906
4907        // todo: note that the algorithm used here is O(N^2).  This
4908        // isn't a problem in our current environment, but if we start running
4909        // into situations where we have more than 5 or 10 matches then this
4910        // should probably be changed to something smarter...
4911
4912        // First we go through and resolve each of the specific items
4913        // that were supplied, taking care of removing any corresponding
4914        // duplicate items in the generic resolve list.
4915        if (specifics != null) {
4916            for (int i=0; i<specifics.length; i++) {
4917                final Intent sintent = specifics[i];
4918                if (sintent == null) {
4919                    continue;
4920                }
4921
4922                if (DEBUG_INTENT_MATCHING) {
4923                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4924                }
4925
4926                String action = sintent.getAction();
4927                if (resultsAction != null && resultsAction.equals(action)) {
4928                    // If this action was explicitly requested, then don't
4929                    // remove things that have it.
4930                    action = null;
4931                }
4932
4933                ResolveInfo ri = null;
4934                ActivityInfo ai = null;
4935
4936                ComponentName comp = sintent.getComponent();
4937                if (comp == null) {
4938                    ri = resolveIntent(
4939                        sintent,
4940                        specificTypes != null ? specificTypes[i] : null,
4941                            flags, userId);
4942                    if (ri == null) {
4943                        continue;
4944                    }
4945                    if (ri == mResolveInfo) {
4946                        // ACK!  Must do something better with this.
4947                    }
4948                    ai = ri.activityInfo;
4949                    comp = new ComponentName(ai.applicationInfo.packageName,
4950                            ai.name);
4951                } else {
4952                    ai = getActivityInfo(comp, flags, userId);
4953                    if (ai == null) {
4954                        continue;
4955                    }
4956                }
4957
4958                // Look for any generic query activities that are duplicates
4959                // of this specific one, and remove them from the results.
4960                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4961                N = results.size();
4962                int j;
4963                for (j=specificsPos; j<N; j++) {
4964                    ResolveInfo sri = results.get(j);
4965                    if ((sri.activityInfo.name.equals(comp.getClassName())
4966                            && sri.activityInfo.applicationInfo.packageName.equals(
4967                                    comp.getPackageName()))
4968                        || (action != null && sri.filter.matchAction(action))) {
4969                        results.remove(j);
4970                        if (DEBUG_INTENT_MATCHING) Log.v(
4971                            TAG, "Removing duplicate item from " + j
4972                            + " due to specific " + specificsPos);
4973                        if (ri == null) {
4974                            ri = sri;
4975                        }
4976                        j--;
4977                        N--;
4978                    }
4979                }
4980
4981                // Add this specific item to its proper place.
4982                if (ri == null) {
4983                    ri = new ResolveInfo();
4984                    ri.activityInfo = ai;
4985                }
4986                results.add(specificsPos, ri);
4987                ri.specificIndex = i;
4988                specificsPos++;
4989            }
4990        }
4991
4992        // Now we go through the remaining generic results and remove any
4993        // duplicate actions that are found here.
4994        N = results.size();
4995        for (int i=specificsPos; i<N-1; i++) {
4996            final ResolveInfo rii = results.get(i);
4997            if (rii.filter == null) {
4998                continue;
4999            }
5000
5001            // Iterate over all of the actions of this result's intent
5002            // filter...  typically this should be just one.
5003            final Iterator<String> it = rii.filter.actionsIterator();
5004            if (it == null) {
5005                continue;
5006            }
5007            while (it.hasNext()) {
5008                final String action = it.next();
5009                if (resultsAction != null && resultsAction.equals(action)) {
5010                    // If this action was explicitly requested, then don't
5011                    // remove things that have it.
5012                    continue;
5013                }
5014                for (int j=i+1; j<N; j++) {
5015                    final ResolveInfo rij = results.get(j);
5016                    if (rij.filter != null && rij.filter.hasAction(action)) {
5017                        results.remove(j);
5018                        if (DEBUG_INTENT_MATCHING) Log.v(
5019                            TAG, "Removing duplicate item from " + j
5020                            + " due to action " + action + " at " + i);
5021                        j--;
5022                        N--;
5023                    }
5024                }
5025            }
5026
5027            // If the caller didn't request filter information, drop it now
5028            // so we don't have to marshall/unmarshall it.
5029            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5030                rii.filter = null;
5031            }
5032        }
5033
5034        // Filter out the caller activity if so requested.
5035        if (caller != null) {
5036            N = results.size();
5037            for (int i=0; i<N; i++) {
5038                ActivityInfo ainfo = results.get(i).activityInfo;
5039                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5040                        && caller.getClassName().equals(ainfo.name)) {
5041                    results.remove(i);
5042                    break;
5043                }
5044            }
5045        }
5046
5047        // If the caller didn't request filter information,
5048        // drop them now so we don't have to
5049        // marshall/unmarshall it.
5050        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5051            N = results.size();
5052            for (int i=0; i<N; i++) {
5053                results.get(i).filter = null;
5054            }
5055        }
5056
5057        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5058        return results;
5059    }
5060
5061    @Override
5062    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5063            int userId) {
5064        if (!sUserManager.exists(userId)) return Collections.emptyList();
5065        ComponentName comp = intent.getComponent();
5066        if (comp == null) {
5067            if (intent.getSelector() != null) {
5068                intent = intent.getSelector();
5069                comp = intent.getComponent();
5070            }
5071        }
5072        if (comp != null) {
5073            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5074            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5075            if (ai != null) {
5076                ResolveInfo ri = new ResolveInfo();
5077                ri.activityInfo = ai;
5078                list.add(ri);
5079            }
5080            return list;
5081        }
5082
5083        // reader
5084        synchronized (mPackages) {
5085            String pkgName = intent.getPackage();
5086            if (pkgName == null) {
5087                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5088            }
5089            final PackageParser.Package pkg = mPackages.get(pkgName);
5090            if (pkg != null) {
5091                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5092                        userId);
5093            }
5094            return null;
5095        }
5096    }
5097
5098    @Override
5099    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5100        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5101        if (!sUserManager.exists(userId)) return null;
5102        if (query != null) {
5103            if (query.size() >= 1) {
5104                // If there is more than one service with the same priority,
5105                // just arbitrarily pick the first one.
5106                return query.get(0);
5107            }
5108        }
5109        return null;
5110    }
5111
5112    @Override
5113    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5114            int userId) {
5115        if (!sUserManager.exists(userId)) return Collections.emptyList();
5116        ComponentName comp = intent.getComponent();
5117        if (comp == null) {
5118            if (intent.getSelector() != null) {
5119                intent = intent.getSelector();
5120                comp = intent.getComponent();
5121            }
5122        }
5123        if (comp != null) {
5124            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5125            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5126            if (si != null) {
5127                final ResolveInfo ri = new ResolveInfo();
5128                ri.serviceInfo = si;
5129                list.add(ri);
5130            }
5131            return list;
5132        }
5133
5134        // reader
5135        synchronized (mPackages) {
5136            String pkgName = intent.getPackage();
5137            if (pkgName == null) {
5138                return mServices.queryIntent(intent, resolvedType, flags, userId);
5139            }
5140            final PackageParser.Package pkg = mPackages.get(pkgName);
5141            if (pkg != null) {
5142                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5143                        userId);
5144            }
5145            return null;
5146        }
5147    }
5148
5149    @Override
5150    public List<ResolveInfo> queryIntentContentProviders(
5151            Intent intent, String resolvedType, int flags, int userId) {
5152        if (!sUserManager.exists(userId)) return Collections.emptyList();
5153        ComponentName comp = intent.getComponent();
5154        if (comp == null) {
5155            if (intent.getSelector() != null) {
5156                intent = intent.getSelector();
5157                comp = intent.getComponent();
5158            }
5159        }
5160        if (comp != null) {
5161            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5162            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5163            if (pi != null) {
5164                final ResolveInfo ri = new ResolveInfo();
5165                ri.providerInfo = pi;
5166                list.add(ri);
5167            }
5168            return list;
5169        }
5170
5171        // reader
5172        synchronized (mPackages) {
5173            String pkgName = intent.getPackage();
5174            if (pkgName == null) {
5175                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5176            }
5177            final PackageParser.Package pkg = mPackages.get(pkgName);
5178            if (pkg != null) {
5179                return mProviders.queryIntentForPackage(
5180                        intent, resolvedType, flags, pkg.providers, userId);
5181            }
5182            return null;
5183        }
5184    }
5185
5186    @Override
5187    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5188        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5189
5190        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5191
5192        // writer
5193        synchronized (mPackages) {
5194            ArrayList<PackageInfo> list;
5195            if (listUninstalled) {
5196                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5197                for (PackageSetting ps : mSettings.mPackages.values()) {
5198                    PackageInfo pi;
5199                    if (ps.pkg != null) {
5200                        pi = generatePackageInfo(ps.pkg, flags, userId);
5201                    } else {
5202                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5203                    }
5204                    if (pi != null) {
5205                        list.add(pi);
5206                    }
5207                }
5208            } else {
5209                list = new ArrayList<PackageInfo>(mPackages.size());
5210                for (PackageParser.Package p : mPackages.values()) {
5211                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5212                    if (pi != null) {
5213                        list.add(pi);
5214                    }
5215                }
5216            }
5217
5218            return new ParceledListSlice<PackageInfo>(list);
5219        }
5220    }
5221
5222    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5223            String[] permissions, boolean[] tmp, int flags, int userId) {
5224        int numMatch = 0;
5225        final PermissionsState permissionsState = ps.getPermissionsState();
5226        for (int i=0; i<permissions.length; i++) {
5227            final String permission = permissions[i];
5228            if (permissionsState.hasPermission(permission, userId)) {
5229                tmp[i] = true;
5230                numMatch++;
5231            } else {
5232                tmp[i] = false;
5233            }
5234        }
5235        if (numMatch == 0) {
5236            return;
5237        }
5238        PackageInfo pi;
5239        if (ps.pkg != null) {
5240            pi = generatePackageInfo(ps.pkg, flags, userId);
5241        } else {
5242            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5243        }
5244        // The above might return null in cases of uninstalled apps or install-state
5245        // skew across users/profiles.
5246        if (pi != null) {
5247            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5248                if (numMatch == permissions.length) {
5249                    pi.requestedPermissions = permissions;
5250                } else {
5251                    pi.requestedPermissions = new String[numMatch];
5252                    numMatch = 0;
5253                    for (int i=0; i<permissions.length; i++) {
5254                        if (tmp[i]) {
5255                            pi.requestedPermissions[numMatch] = permissions[i];
5256                            numMatch++;
5257                        }
5258                    }
5259                }
5260            }
5261            list.add(pi);
5262        }
5263    }
5264
5265    @Override
5266    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5267            String[] permissions, int flags, int userId) {
5268        if (!sUserManager.exists(userId)) return null;
5269        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5270
5271        // writer
5272        synchronized (mPackages) {
5273            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5274            boolean[] tmpBools = new boolean[permissions.length];
5275            if (listUninstalled) {
5276                for (PackageSetting ps : mSettings.mPackages.values()) {
5277                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5278                }
5279            } else {
5280                for (PackageParser.Package pkg : mPackages.values()) {
5281                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5282                    if (ps != null) {
5283                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5284                                userId);
5285                    }
5286                }
5287            }
5288
5289            return new ParceledListSlice<PackageInfo>(list);
5290        }
5291    }
5292
5293    @Override
5294    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5295        if (!sUserManager.exists(userId)) return null;
5296        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5297
5298        // writer
5299        synchronized (mPackages) {
5300            ArrayList<ApplicationInfo> list;
5301            if (listUninstalled) {
5302                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5303                for (PackageSetting ps : mSettings.mPackages.values()) {
5304                    ApplicationInfo ai;
5305                    if (ps.pkg != null) {
5306                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5307                                ps.readUserState(userId), userId);
5308                    } else {
5309                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5310                    }
5311                    if (ai != null) {
5312                        list.add(ai);
5313                    }
5314                }
5315            } else {
5316                list = new ArrayList<ApplicationInfo>(mPackages.size());
5317                for (PackageParser.Package p : mPackages.values()) {
5318                    if (p.mExtras != null) {
5319                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5320                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5321                        if (ai != null) {
5322                            list.add(ai);
5323                        }
5324                    }
5325                }
5326            }
5327
5328            return new ParceledListSlice<ApplicationInfo>(list);
5329        }
5330    }
5331
5332    public List<ApplicationInfo> getPersistentApplications(int flags) {
5333        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5334
5335        // reader
5336        synchronized (mPackages) {
5337            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5338            final int userId = UserHandle.getCallingUserId();
5339            while (i.hasNext()) {
5340                final PackageParser.Package p = i.next();
5341                if (p.applicationInfo != null
5342                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5343                        && (!mSafeMode || isSystemApp(p))) {
5344                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5345                    if (ps != null) {
5346                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5347                                ps.readUserState(userId), userId);
5348                        if (ai != null) {
5349                            finalList.add(ai);
5350                        }
5351                    }
5352                }
5353            }
5354        }
5355
5356        return finalList;
5357    }
5358
5359    @Override
5360    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5361        if (!sUserManager.exists(userId)) return null;
5362        // reader
5363        synchronized (mPackages) {
5364            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5365            PackageSetting ps = provider != null
5366                    ? mSettings.mPackages.get(provider.owner.packageName)
5367                    : null;
5368            return ps != null
5369                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5370                    && (!mSafeMode || (provider.info.applicationInfo.flags
5371                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5372                    ? PackageParser.generateProviderInfo(provider, flags,
5373                            ps.readUserState(userId), userId)
5374                    : null;
5375        }
5376    }
5377
5378    /**
5379     * @deprecated
5380     */
5381    @Deprecated
5382    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5383        // reader
5384        synchronized (mPackages) {
5385            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5386                    .entrySet().iterator();
5387            final int userId = UserHandle.getCallingUserId();
5388            while (i.hasNext()) {
5389                Map.Entry<String, PackageParser.Provider> entry = i.next();
5390                PackageParser.Provider p = entry.getValue();
5391                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5392
5393                if (ps != null && p.syncable
5394                        && (!mSafeMode || (p.info.applicationInfo.flags
5395                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5396                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5397                            ps.readUserState(userId), userId);
5398                    if (info != null) {
5399                        outNames.add(entry.getKey());
5400                        outInfo.add(info);
5401                    }
5402                }
5403            }
5404        }
5405    }
5406
5407    @Override
5408    public List<ProviderInfo> queryContentProviders(String processName,
5409            int uid, int flags) {
5410        ArrayList<ProviderInfo> finalList = null;
5411        // reader
5412        synchronized (mPackages) {
5413            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5414            final int userId = processName != null ?
5415                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5416            while (i.hasNext()) {
5417                final PackageParser.Provider p = i.next();
5418                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5419                if (ps != null && p.info.authority != null
5420                        && (processName == null
5421                                || (p.info.processName.equals(processName)
5422                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5423                        && mSettings.isEnabledLPr(p.info, flags, userId)
5424                        && (!mSafeMode
5425                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5426                    if (finalList == null) {
5427                        finalList = new ArrayList<ProviderInfo>(3);
5428                    }
5429                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5430                            ps.readUserState(userId), userId);
5431                    if (info != null) {
5432                        finalList.add(info);
5433                    }
5434                }
5435            }
5436        }
5437
5438        if (finalList != null) {
5439            Collections.sort(finalList, mProviderInitOrderSorter);
5440        }
5441
5442        return finalList;
5443    }
5444
5445    @Override
5446    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5447            int flags) {
5448        // reader
5449        synchronized (mPackages) {
5450            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5451            return PackageParser.generateInstrumentationInfo(i, flags);
5452        }
5453    }
5454
5455    @Override
5456    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5457            int flags) {
5458        ArrayList<InstrumentationInfo> finalList =
5459            new ArrayList<InstrumentationInfo>();
5460
5461        // reader
5462        synchronized (mPackages) {
5463            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5464            while (i.hasNext()) {
5465                final PackageParser.Instrumentation p = i.next();
5466                if (targetPackage == null
5467                        || targetPackage.equals(p.info.targetPackage)) {
5468                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5469                            flags);
5470                    if (ii != null) {
5471                        finalList.add(ii);
5472                    }
5473                }
5474            }
5475        }
5476
5477        return finalList;
5478    }
5479
5480    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5481        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5482        if (overlays == null) {
5483            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5484            return;
5485        }
5486        for (PackageParser.Package opkg : overlays.values()) {
5487            // Not much to do if idmap fails: we already logged the error
5488            // and we certainly don't want to abort installation of pkg simply
5489            // because an overlay didn't fit properly. For these reasons,
5490            // ignore the return value of createIdmapForPackagePairLI.
5491            createIdmapForPackagePairLI(pkg, opkg);
5492        }
5493    }
5494
5495    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5496            PackageParser.Package opkg) {
5497        if (!opkg.mTrustedOverlay) {
5498            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5499                    opkg.baseCodePath + ": overlay not trusted");
5500            return false;
5501        }
5502        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5503        if (overlaySet == null) {
5504            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5505                    opkg.baseCodePath + " but target package has no known overlays");
5506            return false;
5507        }
5508        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5509        // TODO: generate idmap for split APKs
5510        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5511            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5512                    + opkg.baseCodePath);
5513            return false;
5514        }
5515        PackageParser.Package[] overlayArray =
5516            overlaySet.values().toArray(new PackageParser.Package[0]);
5517        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5518            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5519                return p1.mOverlayPriority - p2.mOverlayPriority;
5520            }
5521        };
5522        Arrays.sort(overlayArray, cmp);
5523
5524        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5525        int i = 0;
5526        for (PackageParser.Package p : overlayArray) {
5527            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5528        }
5529        return true;
5530    }
5531
5532    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5533        final File[] files = dir.listFiles();
5534        if (ArrayUtils.isEmpty(files)) {
5535            Log.d(TAG, "No files in app dir " + dir);
5536            return;
5537        }
5538
5539        if (DEBUG_PACKAGE_SCANNING) {
5540            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5541                    + " flags=0x" + Integer.toHexString(parseFlags));
5542        }
5543
5544        for (File file : files) {
5545            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5546                    && !PackageInstallerService.isStageName(file.getName());
5547            if (!isPackage) {
5548                // Ignore entries which are not packages
5549                continue;
5550            }
5551            try {
5552                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5553                        scanFlags, currentTime, null);
5554            } catch (PackageManagerException e) {
5555                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5556
5557                // Delete invalid userdata apps
5558                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5559                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5560                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5561                    if (file.isDirectory()) {
5562                        mInstaller.rmPackageDir(file.getAbsolutePath());
5563                    } else {
5564                        file.delete();
5565                    }
5566                }
5567            }
5568        }
5569    }
5570
5571    private static File getSettingsProblemFile() {
5572        File dataDir = Environment.getDataDirectory();
5573        File systemDir = new File(dataDir, "system");
5574        File fname = new File(systemDir, "uiderrors.txt");
5575        return fname;
5576    }
5577
5578    static void reportSettingsProblem(int priority, String msg) {
5579        logCriticalInfo(priority, msg);
5580    }
5581
5582    static void logCriticalInfo(int priority, String msg) {
5583        Slog.println(priority, TAG, msg);
5584        EventLogTags.writePmCriticalInfo(msg);
5585        try {
5586            File fname = getSettingsProblemFile();
5587            FileOutputStream out = new FileOutputStream(fname, true);
5588            PrintWriter pw = new FastPrintWriter(out);
5589            SimpleDateFormat formatter = new SimpleDateFormat();
5590            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5591            pw.println(dateString + ": " + msg);
5592            pw.close();
5593            FileUtils.setPermissions(
5594                    fname.toString(),
5595                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5596                    -1, -1);
5597        } catch (java.io.IOException e) {
5598        }
5599    }
5600
5601    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5602            PackageParser.Package pkg, File srcFile, int parseFlags)
5603            throws PackageManagerException {
5604        if (ps != null
5605                && ps.codePath.equals(srcFile)
5606                && ps.timeStamp == srcFile.lastModified()
5607                && !isCompatSignatureUpdateNeeded(pkg)
5608                && !isRecoverSignatureUpdateNeeded(pkg)) {
5609            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5610            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5611            ArraySet<PublicKey> signingKs;
5612            synchronized (mPackages) {
5613                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5614            }
5615            if (ps.signatures.mSignatures != null
5616                    && ps.signatures.mSignatures.length != 0
5617                    && signingKs != null) {
5618                // Optimization: reuse the existing cached certificates
5619                // if the package appears to be unchanged.
5620                pkg.mSignatures = ps.signatures.mSignatures;
5621                pkg.mSigningKeys = signingKs;
5622                return;
5623            }
5624
5625            Slog.w(TAG, "PackageSetting for " + ps.name
5626                    + " is missing signatures.  Collecting certs again to recover them.");
5627        } else {
5628            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5629        }
5630
5631        try {
5632            pp.collectCertificates(pkg, parseFlags);
5633            pp.collectManifestDigest(pkg);
5634        } catch (PackageParserException e) {
5635            throw PackageManagerException.from(e);
5636        }
5637    }
5638
5639    /*
5640     *  Scan a package and return the newly parsed package.
5641     *  Returns null in case of errors and the error code is stored in mLastScanError
5642     */
5643    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5644            long currentTime, UserHandle user) throws PackageManagerException {
5645        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5646        parseFlags |= mDefParseFlags;
5647        PackageParser pp = new PackageParser();
5648        pp.setSeparateProcesses(mSeparateProcesses);
5649        pp.setOnlyCoreApps(mOnlyCore);
5650        pp.setDisplayMetrics(mMetrics);
5651
5652        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5653            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5654        }
5655
5656        final PackageParser.Package pkg;
5657        try {
5658            pkg = pp.parsePackage(scanFile, parseFlags);
5659        } catch (PackageParserException e) {
5660            throw PackageManagerException.from(e);
5661        }
5662
5663        PackageSetting ps = null;
5664        PackageSetting updatedPkg;
5665        // reader
5666        synchronized (mPackages) {
5667            // Look to see if we already know about this package.
5668            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5669            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5670                // This package has been renamed to its original name.  Let's
5671                // use that.
5672                ps = mSettings.peekPackageLPr(oldName);
5673            }
5674            // If there was no original package, see one for the real package name.
5675            if (ps == null) {
5676                ps = mSettings.peekPackageLPr(pkg.packageName);
5677            }
5678            // Check to see if this package could be hiding/updating a system
5679            // package.  Must look for it either under the original or real
5680            // package name depending on our state.
5681            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5682            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5683        }
5684        boolean updatedPkgBetter = false;
5685        // First check if this is a system package that may involve an update
5686        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5687            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5688            // it needs to drop FLAG_PRIVILEGED.
5689            if (locationIsPrivileged(scanFile)) {
5690                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5691            } else {
5692                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5693            }
5694
5695            if (ps != null && !ps.codePath.equals(scanFile)) {
5696                // The path has changed from what was last scanned...  check the
5697                // version of the new path against what we have stored to determine
5698                // what to do.
5699                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5700                if (pkg.mVersionCode <= ps.versionCode) {
5701                    // The system package has been updated and the code path does not match
5702                    // Ignore entry. Skip it.
5703                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5704                            + " ignored: updated version " + ps.versionCode
5705                            + " better than this " + pkg.mVersionCode);
5706                    if (!updatedPkg.codePath.equals(scanFile)) {
5707                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5708                                + ps.name + " changing from " + updatedPkg.codePathString
5709                                + " to " + scanFile);
5710                        updatedPkg.codePath = scanFile;
5711                        updatedPkg.codePathString = scanFile.toString();
5712                        updatedPkg.resourcePath = scanFile;
5713                        updatedPkg.resourcePathString = scanFile.toString();
5714                    }
5715                    updatedPkg.pkg = pkg;
5716                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5717                            "Package " + ps.name + " at " + scanFile
5718                                    + " ignored: updated version " + ps.versionCode
5719                                    + " better than this " + pkg.mVersionCode);
5720                } else {
5721                    // The current app on the system partition is better than
5722                    // what we have updated to on the data partition; switch
5723                    // back to the system partition version.
5724                    // At this point, its safely assumed that package installation for
5725                    // apps in system partition will go through. If not there won't be a working
5726                    // version of the app
5727                    // writer
5728                    synchronized (mPackages) {
5729                        // Just remove the loaded entries from package lists.
5730                        mPackages.remove(ps.name);
5731                    }
5732
5733                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5734                            + " reverting from " + ps.codePathString
5735                            + ": new version " + pkg.mVersionCode
5736                            + " better than installed " + ps.versionCode);
5737
5738                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5739                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5740                    synchronized (mInstallLock) {
5741                        args.cleanUpResourcesLI();
5742                    }
5743                    synchronized (mPackages) {
5744                        mSettings.enableSystemPackageLPw(ps.name);
5745                    }
5746                    updatedPkgBetter = true;
5747                }
5748            }
5749        }
5750
5751        if (updatedPkg != null) {
5752            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5753            // initially
5754            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5755
5756            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5757            // flag set initially
5758            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5759                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5760            }
5761        }
5762
5763        // Verify certificates against what was last scanned
5764        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5765
5766        /*
5767         * A new system app appeared, but we already had a non-system one of the
5768         * same name installed earlier.
5769         */
5770        boolean shouldHideSystemApp = false;
5771        if (updatedPkg == null && ps != null
5772                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5773            /*
5774             * Check to make sure the signatures match first. If they don't,
5775             * wipe the installed application and its data.
5776             */
5777            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5778                    != PackageManager.SIGNATURE_MATCH) {
5779                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5780                        + " signatures don't match existing userdata copy; removing");
5781                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5782                ps = null;
5783            } else {
5784                /*
5785                 * If the newly-added system app is an older version than the
5786                 * already installed version, hide it. It will be scanned later
5787                 * and re-added like an update.
5788                 */
5789                if (pkg.mVersionCode <= ps.versionCode) {
5790                    shouldHideSystemApp = true;
5791                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5792                            + " but new version " + pkg.mVersionCode + " better than installed "
5793                            + ps.versionCode + "; hiding system");
5794                } else {
5795                    /*
5796                     * The newly found system app is a newer version that the
5797                     * one previously installed. Simply remove the
5798                     * already-installed application and replace it with our own
5799                     * while keeping the application data.
5800                     */
5801                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5802                            + " reverting from " + ps.codePathString + ": new version "
5803                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5804                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5805                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5806                    synchronized (mInstallLock) {
5807                        args.cleanUpResourcesLI();
5808                    }
5809                }
5810            }
5811        }
5812
5813        // The apk is forward locked (not public) if its code and resources
5814        // are kept in different files. (except for app in either system or
5815        // vendor path).
5816        // TODO grab this value from PackageSettings
5817        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5818            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5819                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5820            }
5821        }
5822
5823        // TODO: extend to support forward-locked splits
5824        String resourcePath = null;
5825        String baseResourcePath = null;
5826        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5827            if (ps != null && ps.resourcePathString != null) {
5828                resourcePath = ps.resourcePathString;
5829                baseResourcePath = ps.resourcePathString;
5830            } else {
5831                // Should not happen at all. Just log an error.
5832                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5833            }
5834        } else {
5835            resourcePath = pkg.codePath;
5836            baseResourcePath = pkg.baseCodePath;
5837        }
5838
5839        // Set application objects path explicitly.
5840        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5841        pkg.applicationInfo.setCodePath(pkg.codePath);
5842        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5843        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5844        pkg.applicationInfo.setResourcePath(resourcePath);
5845        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5846        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5847
5848        // Note that we invoke the following method only if we are about to unpack an application
5849        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5850                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5851
5852        /*
5853         * If the system app should be overridden by a previously installed
5854         * data, hide the system app now and let the /data/app scan pick it up
5855         * again.
5856         */
5857        if (shouldHideSystemApp) {
5858            synchronized (mPackages) {
5859                /*
5860                 * We have to grant systems permissions before we hide, because
5861                 * grantPermissions will assume the package update is trying to
5862                 * expand its permissions.
5863                 */
5864                grantPermissionsLPw(pkg, true, pkg.packageName);
5865                mSettings.disableSystemPackageLPw(pkg.packageName);
5866            }
5867        }
5868
5869        return scannedPkg;
5870    }
5871
5872    private static String fixProcessName(String defProcessName,
5873            String processName, int uid) {
5874        if (processName == null) {
5875            return defProcessName;
5876        }
5877        return processName;
5878    }
5879
5880    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5881            throws PackageManagerException {
5882        if (pkgSetting.signatures.mSignatures != null) {
5883            // Already existing package. Make sure signatures match
5884            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5885                    == PackageManager.SIGNATURE_MATCH;
5886            if (!match) {
5887                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5888                        == PackageManager.SIGNATURE_MATCH;
5889            }
5890            if (!match) {
5891                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5892                        == PackageManager.SIGNATURE_MATCH;
5893            }
5894            if (!match) {
5895                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5896                        + pkg.packageName + " signatures do not match the "
5897                        + "previously installed version; ignoring!");
5898            }
5899        }
5900
5901        // Check for shared user signatures
5902        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5903            // Already existing package. Make sure signatures match
5904            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5905                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5906            if (!match) {
5907                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5908                        == PackageManager.SIGNATURE_MATCH;
5909            }
5910            if (!match) {
5911                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5912                        == PackageManager.SIGNATURE_MATCH;
5913            }
5914            if (!match) {
5915                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5916                        "Package " + pkg.packageName
5917                        + " has no signatures that match those in shared user "
5918                        + pkgSetting.sharedUser.name + "; ignoring!");
5919            }
5920        }
5921    }
5922
5923    /**
5924     * Enforces that only the system UID or root's UID can call a method exposed
5925     * via Binder.
5926     *
5927     * @param message used as message if SecurityException is thrown
5928     * @throws SecurityException if the caller is not system or root
5929     */
5930    private static final void enforceSystemOrRoot(String message) {
5931        final int uid = Binder.getCallingUid();
5932        if (uid != Process.SYSTEM_UID && uid != 0) {
5933            throw new SecurityException(message);
5934        }
5935    }
5936
5937    @Override
5938    public void performBootDexOpt() {
5939        enforceSystemOrRoot("Only the system can request dexopt be performed");
5940
5941        // Before everything else, see whether we need to fstrim.
5942        try {
5943            IMountService ms = PackageHelper.getMountService();
5944            if (ms != null) {
5945                final boolean isUpgrade = isUpgrade();
5946                boolean doTrim = isUpgrade;
5947                if (doTrim) {
5948                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5949                } else {
5950                    final long interval = android.provider.Settings.Global.getLong(
5951                            mContext.getContentResolver(),
5952                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5953                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5954                    if (interval > 0) {
5955                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5956                        if (timeSinceLast > interval) {
5957                            doTrim = true;
5958                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5959                                    + "; running immediately");
5960                        }
5961                    }
5962                }
5963                if (doTrim) {
5964                    if (!isFirstBoot()) {
5965                        try {
5966                            ActivityManagerNative.getDefault().showBootMessage(
5967                                    mContext.getResources().getString(
5968                                            R.string.android_upgrading_fstrim), true);
5969                        } catch (RemoteException e) {
5970                        }
5971                    }
5972                    ms.runMaintenance();
5973                }
5974            } else {
5975                Slog.e(TAG, "Mount service unavailable!");
5976            }
5977        } catch (RemoteException e) {
5978            // Can't happen; MountService is local
5979        }
5980
5981        final ArraySet<PackageParser.Package> pkgs;
5982        synchronized (mPackages) {
5983            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5984        }
5985
5986        if (pkgs != null) {
5987            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5988            // in case the device runs out of space.
5989            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5990            // Give priority to core apps.
5991            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5992                PackageParser.Package pkg = it.next();
5993                if (pkg.coreApp) {
5994                    if (DEBUG_DEXOPT) {
5995                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5996                    }
5997                    sortedPkgs.add(pkg);
5998                    it.remove();
5999                }
6000            }
6001            // Give priority to system apps that listen for pre boot complete.
6002            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6003            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6004            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6005                PackageParser.Package pkg = it.next();
6006                if (pkgNames.contains(pkg.packageName)) {
6007                    if (DEBUG_DEXOPT) {
6008                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6009                    }
6010                    sortedPkgs.add(pkg);
6011                    it.remove();
6012                }
6013            }
6014            // Give priority to system apps.
6015            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6016                PackageParser.Package pkg = it.next();
6017                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6018                    if (DEBUG_DEXOPT) {
6019                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6020                    }
6021                    sortedPkgs.add(pkg);
6022                    it.remove();
6023                }
6024            }
6025            // Give priority to updated system apps.
6026            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6027                PackageParser.Package pkg = it.next();
6028                if (pkg.isUpdatedSystemApp()) {
6029                    if (DEBUG_DEXOPT) {
6030                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6031                    }
6032                    sortedPkgs.add(pkg);
6033                    it.remove();
6034                }
6035            }
6036            // Give priority to apps that listen for boot complete.
6037            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6038            pkgNames = getPackageNamesForIntent(intent);
6039            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6040                PackageParser.Package pkg = it.next();
6041                if (pkgNames.contains(pkg.packageName)) {
6042                    if (DEBUG_DEXOPT) {
6043                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6044                    }
6045                    sortedPkgs.add(pkg);
6046                    it.remove();
6047                }
6048            }
6049            // Filter out packages that aren't recently used.
6050            filterRecentlyUsedApps(pkgs);
6051            // Add all remaining apps.
6052            for (PackageParser.Package pkg : pkgs) {
6053                if (DEBUG_DEXOPT) {
6054                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6055                }
6056                sortedPkgs.add(pkg);
6057            }
6058
6059            // If we want to be lazy, filter everything that wasn't recently used.
6060            if (mLazyDexOpt) {
6061                filterRecentlyUsedApps(sortedPkgs);
6062            }
6063
6064            int i = 0;
6065            int total = sortedPkgs.size();
6066            File dataDir = Environment.getDataDirectory();
6067            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6068            if (lowThreshold == 0) {
6069                throw new IllegalStateException("Invalid low memory threshold");
6070            }
6071            for (PackageParser.Package pkg : sortedPkgs) {
6072                long usableSpace = dataDir.getUsableSpace();
6073                if (usableSpace < lowThreshold) {
6074                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6075                    break;
6076                }
6077                performBootDexOpt(pkg, ++i, total);
6078            }
6079        }
6080    }
6081
6082    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6083        // Filter out packages that aren't recently used.
6084        //
6085        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6086        // should do a full dexopt.
6087        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6088            int total = pkgs.size();
6089            int skipped = 0;
6090            long now = System.currentTimeMillis();
6091            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6092                PackageParser.Package pkg = i.next();
6093                long then = pkg.mLastPackageUsageTimeInMills;
6094                if (then + mDexOptLRUThresholdInMills < now) {
6095                    if (DEBUG_DEXOPT) {
6096                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6097                              ((then == 0) ? "never" : new Date(then)));
6098                    }
6099                    i.remove();
6100                    skipped++;
6101                }
6102            }
6103            if (DEBUG_DEXOPT) {
6104                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6105            }
6106        }
6107    }
6108
6109    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6110        List<ResolveInfo> ris = null;
6111        try {
6112            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6113                    intent, null, 0, UserHandle.USER_OWNER);
6114        } catch (RemoteException e) {
6115        }
6116        ArraySet<String> pkgNames = new ArraySet<String>();
6117        if (ris != null) {
6118            for (ResolveInfo ri : ris) {
6119                pkgNames.add(ri.activityInfo.packageName);
6120            }
6121        }
6122        return pkgNames;
6123    }
6124
6125    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6126        if (DEBUG_DEXOPT) {
6127            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6128        }
6129        if (!isFirstBoot()) {
6130            try {
6131                ActivityManagerNative.getDefault().showBootMessage(
6132                        mContext.getResources().getString(R.string.android_upgrading_apk,
6133                                curr, total), true);
6134            } catch (RemoteException e) {
6135            }
6136        }
6137        PackageParser.Package p = pkg;
6138        synchronized (mInstallLock) {
6139            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6140                    false /* force dex */, false /* defer */, true /* include dependencies */);
6141        }
6142    }
6143
6144    @Override
6145    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6146        return performDexOpt(packageName, instructionSet, false);
6147    }
6148
6149    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6150        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6151        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6152        if (!dexopt && !updateUsage) {
6153            // We aren't going to dexopt or update usage, so bail early.
6154            return false;
6155        }
6156        PackageParser.Package p;
6157        final String targetInstructionSet;
6158        synchronized (mPackages) {
6159            p = mPackages.get(packageName);
6160            if (p == null) {
6161                return false;
6162            }
6163            if (updateUsage) {
6164                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6165            }
6166            mPackageUsage.write(false);
6167            if (!dexopt) {
6168                // We aren't going to dexopt, so bail early.
6169                return false;
6170            }
6171
6172            targetInstructionSet = instructionSet != null ? instructionSet :
6173                    getPrimaryInstructionSet(p.applicationInfo);
6174            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6175                return false;
6176            }
6177        }
6178        long callingId = Binder.clearCallingIdentity();
6179        try {
6180            synchronized (mInstallLock) {
6181                final String[] instructionSets = new String[] { targetInstructionSet };
6182                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6183                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6184                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6185            }
6186        } finally {
6187            Binder.restoreCallingIdentity(callingId);
6188        }
6189    }
6190
6191    public ArraySet<String> getPackagesThatNeedDexOpt() {
6192        ArraySet<String> pkgs = null;
6193        synchronized (mPackages) {
6194            for (PackageParser.Package p : mPackages.values()) {
6195                if (DEBUG_DEXOPT) {
6196                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6197                }
6198                if (!p.mDexOptPerformed.isEmpty()) {
6199                    continue;
6200                }
6201                if (pkgs == null) {
6202                    pkgs = new ArraySet<String>();
6203                }
6204                pkgs.add(p.packageName);
6205            }
6206        }
6207        return pkgs;
6208    }
6209
6210    public void shutdown() {
6211        mPackageUsage.write(true);
6212    }
6213
6214    @Override
6215    public void forceDexOpt(String packageName) {
6216        enforceSystemOrRoot("forceDexOpt");
6217
6218        PackageParser.Package pkg;
6219        synchronized (mPackages) {
6220            pkg = mPackages.get(packageName);
6221            if (pkg == null) {
6222                throw new IllegalArgumentException("Missing package: " + packageName);
6223            }
6224        }
6225
6226        synchronized (mInstallLock) {
6227            final String[] instructionSets = new String[] {
6228                    getPrimaryInstructionSet(pkg.applicationInfo) };
6229            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6230                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6231            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6232                throw new IllegalStateException("Failed to dexopt: " + res);
6233            }
6234        }
6235    }
6236
6237    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6238        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6239            Slog.w(TAG, "Unable to update from " + oldPkg.name
6240                    + " to " + newPkg.packageName
6241                    + ": old package not in system partition");
6242            return false;
6243        } else if (mPackages.get(oldPkg.name) != null) {
6244            Slog.w(TAG, "Unable to update from " + oldPkg.name
6245                    + " to " + newPkg.packageName
6246                    + ": old package still exists");
6247            return false;
6248        }
6249        return true;
6250    }
6251
6252    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6253        int[] users = sUserManager.getUserIds();
6254        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6255        if (res < 0) {
6256            return res;
6257        }
6258        for (int user : users) {
6259            if (user != 0) {
6260                res = mInstaller.createUserData(volumeUuid, packageName,
6261                        UserHandle.getUid(user, uid), user, seinfo);
6262                if (res < 0) {
6263                    return res;
6264                }
6265            }
6266        }
6267        return res;
6268    }
6269
6270    private int removeDataDirsLI(String volumeUuid, String packageName) {
6271        int[] users = sUserManager.getUserIds();
6272        int res = 0;
6273        for (int user : users) {
6274            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6275            if (resInner < 0) {
6276                res = resInner;
6277            }
6278        }
6279
6280        return res;
6281    }
6282
6283    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6284        int[] users = sUserManager.getUserIds();
6285        int res = 0;
6286        for (int user : users) {
6287            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6288            if (resInner < 0) {
6289                res = resInner;
6290            }
6291        }
6292        return res;
6293    }
6294
6295    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6296            PackageParser.Package changingLib) {
6297        if (file.path != null) {
6298            usesLibraryFiles.add(file.path);
6299            return;
6300        }
6301        PackageParser.Package p = mPackages.get(file.apk);
6302        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6303            // If we are doing this while in the middle of updating a library apk,
6304            // then we need to make sure to use that new apk for determining the
6305            // dependencies here.  (We haven't yet finished committing the new apk
6306            // to the package manager state.)
6307            if (p == null || p.packageName.equals(changingLib.packageName)) {
6308                p = changingLib;
6309            }
6310        }
6311        if (p != null) {
6312            usesLibraryFiles.addAll(p.getAllCodePaths());
6313        }
6314    }
6315
6316    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6317            PackageParser.Package changingLib) throws PackageManagerException {
6318        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6319            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6320            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6321            for (int i=0; i<N; i++) {
6322                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6323                if (file == null) {
6324                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6325                            "Package " + pkg.packageName + " requires unavailable shared library "
6326                            + pkg.usesLibraries.get(i) + "; failing!");
6327                }
6328                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6329            }
6330            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6331            for (int i=0; i<N; i++) {
6332                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6333                if (file == null) {
6334                    Slog.w(TAG, "Package " + pkg.packageName
6335                            + " desires unavailable shared library "
6336                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6337                } else {
6338                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6339                }
6340            }
6341            N = usesLibraryFiles.size();
6342            if (N > 0) {
6343                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6344            } else {
6345                pkg.usesLibraryFiles = null;
6346            }
6347        }
6348    }
6349
6350    private static boolean hasString(List<String> list, List<String> which) {
6351        if (list == null) {
6352            return false;
6353        }
6354        for (int i=list.size()-1; i>=0; i--) {
6355            for (int j=which.size()-1; j>=0; j--) {
6356                if (which.get(j).equals(list.get(i))) {
6357                    return true;
6358                }
6359            }
6360        }
6361        return false;
6362    }
6363
6364    private void updateAllSharedLibrariesLPw() {
6365        for (PackageParser.Package pkg : mPackages.values()) {
6366            try {
6367                updateSharedLibrariesLPw(pkg, null);
6368            } catch (PackageManagerException e) {
6369                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6370            }
6371        }
6372    }
6373
6374    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6375            PackageParser.Package changingPkg) {
6376        ArrayList<PackageParser.Package> res = null;
6377        for (PackageParser.Package pkg : mPackages.values()) {
6378            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6379                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6380                if (res == null) {
6381                    res = new ArrayList<PackageParser.Package>();
6382                }
6383                res.add(pkg);
6384                try {
6385                    updateSharedLibrariesLPw(pkg, changingPkg);
6386                } catch (PackageManagerException e) {
6387                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6388                }
6389            }
6390        }
6391        return res;
6392    }
6393
6394    /**
6395     * Derive the value of the {@code cpuAbiOverride} based on the provided
6396     * value and an optional stored value from the package settings.
6397     */
6398    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6399        String cpuAbiOverride = null;
6400
6401        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6402            cpuAbiOverride = null;
6403        } else if (abiOverride != null) {
6404            cpuAbiOverride = abiOverride;
6405        } else if (settings != null) {
6406            cpuAbiOverride = settings.cpuAbiOverrideString;
6407        }
6408
6409        return cpuAbiOverride;
6410    }
6411
6412    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6413            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6414        boolean success = false;
6415        try {
6416            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6417                    currentTime, user);
6418            success = true;
6419            return res;
6420        } finally {
6421            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6422                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6423            }
6424        }
6425    }
6426
6427    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6428            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6429        final File scanFile = new File(pkg.codePath);
6430        if (pkg.applicationInfo.getCodePath() == null ||
6431                pkg.applicationInfo.getResourcePath() == null) {
6432            // Bail out. The resource and code paths haven't been set.
6433            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6434                    "Code and resource paths haven't been set correctly");
6435        }
6436
6437        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6438            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6439        } else {
6440            // Only allow system apps to be flagged as core apps.
6441            pkg.coreApp = false;
6442        }
6443
6444        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6445            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6446        }
6447
6448        if (mCustomResolverComponentName != null &&
6449                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6450            setUpCustomResolverActivity(pkg);
6451        }
6452
6453        if (pkg.packageName.equals("android")) {
6454            synchronized (mPackages) {
6455                if (mAndroidApplication != null) {
6456                    Slog.w(TAG, "*************************************************");
6457                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6458                    Slog.w(TAG, " file=" + scanFile);
6459                    Slog.w(TAG, "*************************************************");
6460                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6461                            "Core android package being redefined.  Skipping.");
6462                }
6463
6464                // Set up information for our fall-back user intent resolution activity.
6465                mPlatformPackage = pkg;
6466                pkg.mVersionCode = mSdkVersion;
6467                mAndroidApplication = pkg.applicationInfo;
6468
6469                if (!mResolverReplaced) {
6470                    mResolveActivity.applicationInfo = mAndroidApplication;
6471                    mResolveActivity.name = ResolverActivity.class.getName();
6472                    mResolveActivity.packageName = mAndroidApplication.packageName;
6473                    mResolveActivity.processName = "system:ui";
6474                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6475                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6476                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6477                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6478                    mResolveActivity.exported = true;
6479                    mResolveActivity.enabled = true;
6480                    mResolveInfo.activityInfo = mResolveActivity;
6481                    mResolveInfo.priority = 0;
6482                    mResolveInfo.preferredOrder = 0;
6483                    mResolveInfo.match = 0;
6484                    mResolveComponentName = new ComponentName(
6485                            mAndroidApplication.packageName, mResolveActivity.name);
6486                }
6487            }
6488        }
6489
6490        if (DEBUG_PACKAGE_SCANNING) {
6491            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6492                Log.d(TAG, "Scanning package " + pkg.packageName);
6493        }
6494
6495        if (mPackages.containsKey(pkg.packageName)
6496                || mSharedLibraries.containsKey(pkg.packageName)) {
6497            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6498                    "Application package " + pkg.packageName
6499                    + " already installed.  Skipping duplicate.");
6500        }
6501
6502        // If we're only installing presumed-existing packages, require that the
6503        // scanned APK is both already known and at the path previously established
6504        // for it.  Previously unknown packages we pick up normally, but if we have an
6505        // a priori expectation about this package's install presence, enforce it.
6506        // With a singular exception for new system packages. When an OTA contains
6507        // a new system package, we allow the codepath to change from a system location
6508        // to the user-installed location. If we don't allow this change, any newer,
6509        // user-installed version of the application will be ignored.
6510        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6511            if (mExpectingBetter.containsKey(pkg.packageName)) {
6512                logCriticalInfo(Log.WARN,
6513                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6514            } else {
6515                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6516                if (known != null) {
6517                    if (DEBUG_PACKAGE_SCANNING) {
6518                        Log.d(TAG, "Examining " + pkg.codePath
6519                                + " and requiring known paths " + known.codePathString
6520                                + " & " + known.resourcePathString);
6521                    }
6522                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6523                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6524                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6525                                "Application package " + pkg.packageName
6526                                + " found at " + pkg.applicationInfo.getCodePath()
6527                                + " but expected at " + known.codePathString + "; ignoring.");
6528                    }
6529                }
6530            }
6531        }
6532
6533        // Initialize package source and resource directories
6534        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6535        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6536
6537        SharedUserSetting suid = null;
6538        PackageSetting pkgSetting = null;
6539
6540        if (!isSystemApp(pkg)) {
6541            // Only system apps can use these features.
6542            pkg.mOriginalPackages = null;
6543            pkg.mRealPackage = null;
6544            pkg.mAdoptPermissions = null;
6545        }
6546
6547        // writer
6548        synchronized (mPackages) {
6549            if (pkg.mSharedUserId != null) {
6550                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6551                if (suid == null) {
6552                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6553                            "Creating application package " + pkg.packageName
6554                            + " for shared user failed");
6555                }
6556                if (DEBUG_PACKAGE_SCANNING) {
6557                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6558                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6559                                + "): packages=" + suid.packages);
6560                }
6561            }
6562
6563            // Check if we are renaming from an original package name.
6564            PackageSetting origPackage = null;
6565            String realName = null;
6566            if (pkg.mOriginalPackages != null) {
6567                // This package may need to be renamed to a previously
6568                // installed name.  Let's check on that...
6569                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6570                if (pkg.mOriginalPackages.contains(renamed)) {
6571                    // This package had originally been installed as the
6572                    // original name, and we have already taken care of
6573                    // transitioning to the new one.  Just update the new
6574                    // one to continue using the old name.
6575                    realName = pkg.mRealPackage;
6576                    if (!pkg.packageName.equals(renamed)) {
6577                        // Callers into this function may have already taken
6578                        // care of renaming the package; only do it here if
6579                        // it is not already done.
6580                        pkg.setPackageName(renamed);
6581                    }
6582
6583                } else {
6584                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6585                        if ((origPackage = mSettings.peekPackageLPr(
6586                                pkg.mOriginalPackages.get(i))) != null) {
6587                            // We do have the package already installed under its
6588                            // original name...  should we use it?
6589                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6590                                // New package is not compatible with original.
6591                                origPackage = null;
6592                                continue;
6593                            } else if (origPackage.sharedUser != null) {
6594                                // Make sure uid is compatible between packages.
6595                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6596                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6597                                            + " to " + pkg.packageName + ": old uid "
6598                                            + origPackage.sharedUser.name
6599                                            + " differs from " + pkg.mSharedUserId);
6600                                    origPackage = null;
6601                                    continue;
6602                                }
6603                            } else {
6604                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6605                                        + pkg.packageName + " to old name " + origPackage.name);
6606                            }
6607                            break;
6608                        }
6609                    }
6610                }
6611            }
6612
6613            if (mTransferedPackages.contains(pkg.packageName)) {
6614                Slog.w(TAG, "Package " + pkg.packageName
6615                        + " was transferred to another, but its .apk remains");
6616            }
6617
6618            // Just create the setting, don't add it yet. For already existing packages
6619            // the PkgSetting exists already and doesn't have to be created.
6620            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6621                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6622                    pkg.applicationInfo.primaryCpuAbi,
6623                    pkg.applicationInfo.secondaryCpuAbi,
6624                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6625                    user, false);
6626            if (pkgSetting == null) {
6627                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6628                        "Creating application package " + pkg.packageName + " failed");
6629            }
6630
6631            if (pkgSetting.origPackage != null) {
6632                // If we are first transitioning from an original package,
6633                // fix up the new package's name now.  We need to do this after
6634                // looking up the package under its new name, so getPackageLP
6635                // can take care of fiddling things correctly.
6636                pkg.setPackageName(origPackage.name);
6637
6638                // File a report about this.
6639                String msg = "New package " + pkgSetting.realName
6640                        + " renamed to replace old package " + pkgSetting.name;
6641                reportSettingsProblem(Log.WARN, msg);
6642
6643                // Make a note of it.
6644                mTransferedPackages.add(origPackage.name);
6645
6646                // No longer need to retain this.
6647                pkgSetting.origPackage = null;
6648            }
6649
6650            if (realName != null) {
6651                // Make a note of it.
6652                mTransferedPackages.add(pkg.packageName);
6653            }
6654
6655            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6656                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6657            }
6658
6659            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6660                // Check all shared libraries and map to their actual file path.
6661                // We only do this here for apps not on a system dir, because those
6662                // are the only ones that can fail an install due to this.  We
6663                // will take care of the system apps by updating all of their
6664                // library paths after the scan is done.
6665                updateSharedLibrariesLPw(pkg, null);
6666            }
6667
6668            if (mFoundPolicyFile) {
6669                SELinuxMMAC.assignSeinfoValue(pkg);
6670            }
6671
6672            pkg.applicationInfo.uid = pkgSetting.appId;
6673            pkg.mExtras = pkgSetting;
6674            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6675                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6676                    // We just determined the app is signed correctly, so bring
6677                    // over the latest parsed certs.
6678                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6679                } else {
6680                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6681                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6682                                "Package " + pkg.packageName + " upgrade keys do not match the "
6683                                + "previously installed version");
6684                    } else {
6685                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6686                        String msg = "System package " + pkg.packageName
6687                            + " signature changed; retaining data.";
6688                        reportSettingsProblem(Log.WARN, msg);
6689                    }
6690                }
6691            } else {
6692                try {
6693                    verifySignaturesLP(pkgSetting, pkg);
6694                    // We just determined the app is signed correctly, so bring
6695                    // over the latest parsed certs.
6696                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6697                } catch (PackageManagerException e) {
6698                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6699                        throw e;
6700                    }
6701                    // The signature has changed, but this package is in the system
6702                    // image...  let's recover!
6703                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6704                    // However...  if this package is part of a shared user, but it
6705                    // doesn't match the signature of the shared user, let's fail.
6706                    // What this means is that you can't change the signatures
6707                    // associated with an overall shared user, which doesn't seem all
6708                    // that unreasonable.
6709                    if (pkgSetting.sharedUser != null) {
6710                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6711                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6712                            throw new PackageManagerException(
6713                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6714                                            "Signature mismatch for shared user : "
6715                                            + pkgSetting.sharedUser);
6716                        }
6717                    }
6718                    // File a report about this.
6719                    String msg = "System package " + pkg.packageName
6720                        + " signature changed; retaining data.";
6721                    reportSettingsProblem(Log.WARN, msg);
6722                }
6723            }
6724            // Verify that this new package doesn't have any content providers
6725            // that conflict with existing packages.  Only do this if the
6726            // package isn't already installed, since we don't want to break
6727            // things that are installed.
6728            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6729                final int N = pkg.providers.size();
6730                int i;
6731                for (i=0; i<N; i++) {
6732                    PackageParser.Provider p = pkg.providers.get(i);
6733                    if (p.info.authority != null) {
6734                        String names[] = p.info.authority.split(";");
6735                        for (int j = 0; j < names.length; j++) {
6736                            if (mProvidersByAuthority.containsKey(names[j])) {
6737                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6738                                final String otherPackageName =
6739                                        ((other != null && other.getComponentName() != null) ?
6740                                                other.getComponentName().getPackageName() : "?");
6741                                throw new PackageManagerException(
6742                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6743                                                "Can't install because provider name " + names[j]
6744                                                + " (in package " + pkg.applicationInfo.packageName
6745                                                + ") is already used by " + otherPackageName);
6746                            }
6747                        }
6748                    }
6749                }
6750            }
6751
6752            if (pkg.mAdoptPermissions != null) {
6753                // This package wants to adopt ownership of permissions from
6754                // another package.
6755                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6756                    final String origName = pkg.mAdoptPermissions.get(i);
6757                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6758                    if (orig != null) {
6759                        if (verifyPackageUpdateLPr(orig, pkg)) {
6760                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6761                                    + pkg.packageName);
6762                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6763                        }
6764                    }
6765                }
6766            }
6767        }
6768
6769        final String pkgName = pkg.packageName;
6770
6771        final long scanFileTime = scanFile.lastModified();
6772        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6773        pkg.applicationInfo.processName = fixProcessName(
6774                pkg.applicationInfo.packageName,
6775                pkg.applicationInfo.processName,
6776                pkg.applicationInfo.uid);
6777
6778        File dataPath;
6779        if (mPlatformPackage == pkg) {
6780            // The system package is special.
6781            dataPath = new File(Environment.getDataDirectory(), "system");
6782
6783            pkg.applicationInfo.dataDir = dataPath.getPath();
6784
6785        } else {
6786            // This is a normal package, need to make its data directory.
6787            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6788                    UserHandle.USER_OWNER, pkg.packageName);
6789
6790            boolean uidError = false;
6791            if (dataPath.exists()) {
6792                int currentUid = 0;
6793                try {
6794                    StructStat stat = Os.stat(dataPath.getPath());
6795                    currentUid = stat.st_uid;
6796                } catch (ErrnoException e) {
6797                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6798                }
6799
6800                // If we have mismatched owners for the data path, we have a problem.
6801                if (currentUid != pkg.applicationInfo.uid) {
6802                    boolean recovered = false;
6803                    if (currentUid == 0) {
6804                        // The directory somehow became owned by root.  Wow.
6805                        // This is probably because the system was stopped while
6806                        // installd was in the middle of messing with its libs
6807                        // directory.  Ask installd to fix that.
6808                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6809                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6810                        if (ret >= 0) {
6811                            recovered = true;
6812                            String msg = "Package " + pkg.packageName
6813                                    + " unexpectedly changed to uid 0; recovered to " +
6814                                    + pkg.applicationInfo.uid;
6815                            reportSettingsProblem(Log.WARN, msg);
6816                        }
6817                    }
6818                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6819                            || (scanFlags&SCAN_BOOTING) != 0)) {
6820                        // If this is a system app, we can at least delete its
6821                        // current data so the application will still work.
6822                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6823                        if (ret >= 0) {
6824                            // TODO: Kill the processes first
6825                            // Old data gone!
6826                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6827                                    ? "System package " : "Third party package ";
6828                            String msg = prefix + pkg.packageName
6829                                    + " has changed from uid: "
6830                                    + currentUid + " to "
6831                                    + pkg.applicationInfo.uid + "; old data erased";
6832                            reportSettingsProblem(Log.WARN, msg);
6833                            recovered = true;
6834
6835                            // And now re-install the app.
6836                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6837                                    pkg.applicationInfo.seinfo);
6838                            if (ret == -1) {
6839                                // Ack should not happen!
6840                                msg = prefix + pkg.packageName
6841                                        + " could not have data directory re-created after delete.";
6842                                reportSettingsProblem(Log.WARN, msg);
6843                                throw new PackageManagerException(
6844                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6845                            }
6846                        }
6847                        if (!recovered) {
6848                            mHasSystemUidErrors = true;
6849                        }
6850                    } else if (!recovered) {
6851                        // If we allow this install to proceed, we will be broken.
6852                        // Abort, abort!
6853                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6854                                "scanPackageLI");
6855                    }
6856                    if (!recovered) {
6857                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6858                            + pkg.applicationInfo.uid + "/fs_"
6859                            + currentUid;
6860                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6861                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6862                        String msg = "Package " + pkg.packageName
6863                                + " has mismatched uid: "
6864                                + currentUid + " on disk, "
6865                                + pkg.applicationInfo.uid + " in settings";
6866                        // writer
6867                        synchronized (mPackages) {
6868                            mSettings.mReadMessages.append(msg);
6869                            mSettings.mReadMessages.append('\n');
6870                            uidError = true;
6871                            if (!pkgSetting.uidError) {
6872                                reportSettingsProblem(Log.ERROR, msg);
6873                            }
6874                        }
6875                    }
6876                }
6877                pkg.applicationInfo.dataDir = dataPath.getPath();
6878                if (mShouldRestoreconData) {
6879                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6880                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6881                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6882                }
6883            } else {
6884                if (DEBUG_PACKAGE_SCANNING) {
6885                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6886                        Log.v(TAG, "Want this data dir: " + dataPath);
6887                }
6888                //invoke installer to do the actual installation
6889                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6890                        pkg.applicationInfo.seinfo);
6891                if (ret < 0) {
6892                    // Error from installer
6893                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6894                            "Unable to create data dirs [errorCode=" + ret + "]");
6895                }
6896
6897                if (dataPath.exists()) {
6898                    pkg.applicationInfo.dataDir = dataPath.getPath();
6899                } else {
6900                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6901                    pkg.applicationInfo.dataDir = null;
6902                }
6903            }
6904
6905            pkgSetting.uidError = uidError;
6906        }
6907
6908        final String path = scanFile.getPath();
6909        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6910
6911        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6912            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6913
6914            // Some system apps still use directory structure for native libraries
6915            // in which case we might end up not detecting abi solely based on apk
6916            // structure. Try to detect abi based on directory structure.
6917            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6918                    pkg.applicationInfo.primaryCpuAbi == null) {
6919                setBundledAppAbisAndRoots(pkg, pkgSetting);
6920                setNativeLibraryPaths(pkg);
6921            }
6922
6923        } else {
6924            if ((scanFlags & SCAN_MOVE) != 0) {
6925                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6926                // but we already have this packages package info in the PackageSetting. We just
6927                // use that and derive the native library path based on the new codepath.
6928                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6929                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6930            }
6931
6932            // Set native library paths again. For moves, the path will be updated based on the
6933            // ABIs we've determined above. For non-moves, the path will be updated based on the
6934            // ABIs we determined during compilation, but the path will depend on the final
6935            // package path (after the rename away from the stage path).
6936            setNativeLibraryPaths(pkg);
6937        }
6938
6939        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6940        final int[] userIds = sUserManager.getUserIds();
6941        synchronized (mInstallLock) {
6942            // Make sure all user data directories are ready to roll; we're okay
6943            // if they already exist
6944            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6945                for (int userId : userIds) {
6946                    if (userId != 0) {
6947                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6948                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6949                                pkg.applicationInfo.seinfo);
6950                    }
6951                }
6952            }
6953
6954            // Create a native library symlink only if we have native libraries
6955            // and if the native libraries are 32 bit libraries. We do not provide
6956            // this symlink for 64 bit libraries.
6957            if (pkg.applicationInfo.primaryCpuAbi != null &&
6958                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6959                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6960                for (int userId : userIds) {
6961                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6962                            nativeLibPath, userId) < 0) {
6963                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6964                                "Failed linking native library dir (user=" + userId + ")");
6965                    }
6966                }
6967            }
6968        }
6969
6970        // This is a special case for the "system" package, where the ABI is
6971        // dictated by the zygote configuration (and init.rc). We should keep track
6972        // of this ABI so that we can deal with "normal" applications that run under
6973        // the same UID correctly.
6974        if (mPlatformPackage == pkg) {
6975            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6976                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6977        }
6978
6979        // If there's a mismatch between the abi-override in the package setting
6980        // and the abiOverride specified for the install. Warn about this because we
6981        // would've already compiled the app without taking the package setting into
6982        // account.
6983        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6984            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6985                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6986                        " for package: " + pkg.packageName);
6987            }
6988        }
6989
6990        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6991        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6992        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6993
6994        // Copy the derived override back to the parsed package, so that we can
6995        // update the package settings accordingly.
6996        pkg.cpuAbiOverride = cpuAbiOverride;
6997
6998        if (DEBUG_ABI_SELECTION) {
6999            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7000                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7001                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7002        }
7003
7004        // Push the derived path down into PackageSettings so we know what to
7005        // clean up at uninstall time.
7006        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7007
7008        if (DEBUG_ABI_SELECTION) {
7009            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7010                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7011                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7012        }
7013
7014        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7015            // We don't do this here during boot because we can do it all
7016            // at once after scanning all existing packages.
7017            //
7018            // We also do this *before* we perform dexopt on this package, so that
7019            // we can avoid redundant dexopts, and also to make sure we've got the
7020            // code and package path correct.
7021            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7022                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7023        }
7024
7025        if ((scanFlags & SCAN_NO_DEX) == 0) {
7026            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7027                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7028            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7029                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7030            }
7031        }
7032        if (mFactoryTest && pkg.requestedPermissions.contains(
7033                android.Manifest.permission.FACTORY_TEST)) {
7034            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7035        }
7036
7037        ArrayList<PackageParser.Package> clientLibPkgs = null;
7038
7039        // writer
7040        synchronized (mPackages) {
7041            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7042                // Only system apps can add new shared libraries.
7043                if (pkg.libraryNames != null) {
7044                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7045                        String name = pkg.libraryNames.get(i);
7046                        boolean allowed = false;
7047                        if (pkg.isUpdatedSystemApp()) {
7048                            // New library entries can only be added through the
7049                            // system image.  This is important to get rid of a lot
7050                            // of nasty edge cases: for example if we allowed a non-
7051                            // system update of the app to add a library, then uninstalling
7052                            // the update would make the library go away, and assumptions
7053                            // we made such as through app install filtering would now
7054                            // have allowed apps on the device which aren't compatible
7055                            // with it.  Better to just have the restriction here, be
7056                            // conservative, and create many fewer cases that can negatively
7057                            // impact the user experience.
7058                            final PackageSetting sysPs = mSettings
7059                                    .getDisabledSystemPkgLPr(pkg.packageName);
7060                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7061                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7062                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7063                                        allowed = true;
7064                                        allowed = true;
7065                                        break;
7066                                    }
7067                                }
7068                            }
7069                        } else {
7070                            allowed = true;
7071                        }
7072                        if (allowed) {
7073                            if (!mSharedLibraries.containsKey(name)) {
7074                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7075                            } else if (!name.equals(pkg.packageName)) {
7076                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7077                                        + name + " already exists; skipping");
7078                            }
7079                        } else {
7080                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7081                                    + name + " that is not declared on system image; skipping");
7082                        }
7083                    }
7084                    if ((scanFlags&SCAN_BOOTING) == 0) {
7085                        // If we are not booting, we need to update any applications
7086                        // that are clients of our shared library.  If we are booting,
7087                        // this will all be done once the scan is complete.
7088                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7089                    }
7090                }
7091            }
7092        }
7093
7094        // We also need to dexopt any apps that are dependent on this library.  Note that
7095        // if these fail, we should abort the install since installing the library will
7096        // result in some apps being broken.
7097        if (clientLibPkgs != null) {
7098            if ((scanFlags & SCAN_NO_DEX) == 0) {
7099                for (int i = 0; i < clientLibPkgs.size(); i++) {
7100                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7101                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7102                            null /* instruction sets */, forceDex,
7103                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7104                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7105                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7106                                "scanPackageLI failed to dexopt clientLibPkgs");
7107                    }
7108                }
7109            }
7110        }
7111
7112        // Also need to kill any apps that are dependent on the library.
7113        if (clientLibPkgs != null) {
7114            for (int i=0; i<clientLibPkgs.size(); i++) {
7115                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7116                killApplication(clientPkg.applicationInfo.packageName,
7117                        clientPkg.applicationInfo.uid, "update lib");
7118            }
7119        }
7120
7121        // Make sure we're not adding any bogus keyset info
7122        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7123        ksms.assertScannedPackageValid(pkg);
7124
7125        // writer
7126        synchronized (mPackages) {
7127            // We don't expect installation to fail beyond this point
7128
7129            // Add the new setting to mSettings
7130            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7131            // Add the new setting to mPackages
7132            mPackages.put(pkg.applicationInfo.packageName, pkg);
7133            // Make sure we don't accidentally delete its data.
7134            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7135            while (iter.hasNext()) {
7136                PackageCleanItem item = iter.next();
7137                if (pkgName.equals(item.packageName)) {
7138                    iter.remove();
7139                }
7140            }
7141
7142            // Take care of first install / last update times.
7143            if (currentTime != 0) {
7144                if (pkgSetting.firstInstallTime == 0) {
7145                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7146                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7147                    pkgSetting.lastUpdateTime = currentTime;
7148                }
7149            } else if (pkgSetting.firstInstallTime == 0) {
7150                // We need *something*.  Take time time stamp of the file.
7151                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7152            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7153                if (scanFileTime != pkgSetting.timeStamp) {
7154                    // A package on the system image has changed; consider this
7155                    // to be an update.
7156                    pkgSetting.lastUpdateTime = scanFileTime;
7157                }
7158            }
7159
7160            // Add the package's KeySets to the global KeySetManagerService
7161            ksms.addScannedPackageLPw(pkg);
7162
7163            int N = pkg.providers.size();
7164            StringBuilder r = null;
7165            int i;
7166            for (i=0; i<N; i++) {
7167                PackageParser.Provider p = pkg.providers.get(i);
7168                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7169                        p.info.processName, pkg.applicationInfo.uid);
7170                mProviders.addProvider(p);
7171                p.syncable = p.info.isSyncable;
7172                if (p.info.authority != null) {
7173                    String names[] = p.info.authority.split(";");
7174                    p.info.authority = null;
7175                    for (int j = 0; j < names.length; j++) {
7176                        if (j == 1 && p.syncable) {
7177                            // We only want the first authority for a provider to possibly be
7178                            // syncable, so if we already added this provider using a different
7179                            // authority clear the syncable flag. We copy the provider before
7180                            // changing it because the mProviders object contains a reference
7181                            // to a provider that we don't want to change.
7182                            // Only do this for the second authority since the resulting provider
7183                            // object can be the same for all future authorities for this provider.
7184                            p = new PackageParser.Provider(p);
7185                            p.syncable = false;
7186                        }
7187                        if (!mProvidersByAuthority.containsKey(names[j])) {
7188                            mProvidersByAuthority.put(names[j], p);
7189                            if (p.info.authority == null) {
7190                                p.info.authority = names[j];
7191                            } else {
7192                                p.info.authority = p.info.authority + ";" + names[j];
7193                            }
7194                            if (DEBUG_PACKAGE_SCANNING) {
7195                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7196                                    Log.d(TAG, "Registered content provider: " + names[j]
7197                                            + ", className = " + p.info.name + ", isSyncable = "
7198                                            + p.info.isSyncable);
7199                            }
7200                        } else {
7201                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7202                            Slog.w(TAG, "Skipping provider name " + names[j] +
7203                                    " (in package " + pkg.applicationInfo.packageName +
7204                                    "): name already used by "
7205                                    + ((other != null && other.getComponentName() != null)
7206                                            ? other.getComponentName().getPackageName() : "?"));
7207                        }
7208                    }
7209                }
7210                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7211                    if (r == null) {
7212                        r = new StringBuilder(256);
7213                    } else {
7214                        r.append(' ');
7215                    }
7216                    r.append(p.info.name);
7217                }
7218            }
7219            if (r != null) {
7220                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7221            }
7222
7223            N = pkg.services.size();
7224            r = null;
7225            for (i=0; i<N; i++) {
7226                PackageParser.Service s = pkg.services.get(i);
7227                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7228                        s.info.processName, pkg.applicationInfo.uid);
7229                mServices.addService(s);
7230                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7231                    if (r == null) {
7232                        r = new StringBuilder(256);
7233                    } else {
7234                        r.append(' ');
7235                    }
7236                    r.append(s.info.name);
7237                }
7238            }
7239            if (r != null) {
7240                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7241            }
7242
7243            N = pkg.receivers.size();
7244            r = null;
7245            for (i=0; i<N; i++) {
7246                PackageParser.Activity a = pkg.receivers.get(i);
7247                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7248                        a.info.processName, pkg.applicationInfo.uid);
7249                mReceivers.addActivity(a, "receiver");
7250                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7251                    if (r == null) {
7252                        r = new StringBuilder(256);
7253                    } else {
7254                        r.append(' ');
7255                    }
7256                    r.append(a.info.name);
7257                }
7258            }
7259            if (r != null) {
7260                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7261            }
7262
7263            N = pkg.activities.size();
7264            r = null;
7265            for (i=0; i<N; i++) {
7266                PackageParser.Activity a = pkg.activities.get(i);
7267                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7268                        a.info.processName, pkg.applicationInfo.uid);
7269                mActivities.addActivity(a, "activity");
7270                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7271                    if (r == null) {
7272                        r = new StringBuilder(256);
7273                    } else {
7274                        r.append(' ');
7275                    }
7276                    r.append(a.info.name);
7277                }
7278            }
7279            if (r != null) {
7280                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7281            }
7282
7283            N = pkg.permissionGroups.size();
7284            r = null;
7285            for (i=0; i<N; i++) {
7286                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7287                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7288                if (cur == null) {
7289                    mPermissionGroups.put(pg.info.name, pg);
7290                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7291                        if (r == null) {
7292                            r = new StringBuilder(256);
7293                        } else {
7294                            r.append(' ');
7295                        }
7296                        r.append(pg.info.name);
7297                    }
7298                } else {
7299                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7300                            + pg.info.packageName + " ignored: original from "
7301                            + cur.info.packageName);
7302                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7303                        if (r == null) {
7304                            r = new StringBuilder(256);
7305                        } else {
7306                            r.append(' ');
7307                        }
7308                        r.append("DUP:");
7309                        r.append(pg.info.name);
7310                    }
7311                }
7312            }
7313            if (r != null) {
7314                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7315            }
7316
7317            N = pkg.permissions.size();
7318            r = null;
7319            for (i=0; i<N; i++) {
7320                PackageParser.Permission p = pkg.permissions.get(i);
7321
7322                // Assume by default that we did not install this permission into the system.
7323                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7324
7325                // Now that permission groups have a special meaning, we ignore permission
7326                // groups for legacy apps to prevent unexpected behavior. In particular,
7327                // permissions for one app being granted to someone just becuase they happen
7328                // to be in a group defined by another app (before this had no implications).
7329                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7330                    p.group = mPermissionGroups.get(p.info.group);
7331                    // Warn for a permission in an unknown group.
7332                    if (p.info.group != null && p.group == null) {
7333                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7334                                + p.info.packageName + " in an unknown group " + p.info.group);
7335                    }
7336                }
7337
7338                ArrayMap<String, BasePermission> permissionMap =
7339                        p.tree ? mSettings.mPermissionTrees
7340                                : mSettings.mPermissions;
7341                BasePermission bp = permissionMap.get(p.info.name);
7342
7343                // Allow system apps to redefine non-system permissions
7344                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7345                    final boolean currentOwnerIsSystem = (bp.perm != null
7346                            && isSystemApp(bp.perm.owner));
7347                    if (isSystemApp(p.owner)) {
7348                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7349                            // It's a built-in permission and no owner, take ownership now
7350                            bp.packageSetting = pkgSetting;
7351                            bp.perm = p;
7352                            bp.uid = pkg.applicationInfo.uid;
7353                            bp.sourcePackage = p.info.packageName;
7354                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7355                        } else if (!currentOwnerIsSystem) {
7356                            String msg = "New decl " + p.owner + " of permission  "
7357                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7358                            reportSettingsProblem(Log.WARN, msg);
7359                            bp = null;
7360                        }
7361                    }
7362                }
7363
7364                if (bp == null) {
7365                    bp = new BasePermission(p.info.name, p.info.packageName,
7366                            BasePermission.TYPE_NORMAL);
7367                    permissionMap.put(p.info.name, bp);
7368                }
7369
7370                if (bp.perm == null) {
7371                    if (bp.sourcePackage == null
7372                            || bp.sourcePackage.equals(p.info.packageName)) {
7373                        BasePermission tree = findPermissionTreeLP(p.info.name);
7374                        if (tree == null
7375                                || tree.sourcePackage.equals(p.info.packageName)) {
7376                            bp.packageSetting = pkgSetting;
7377                            bp.perm = p;
7378                            bp.uid = pkg.applicationInfo.uid;
7379                            bp.sourcePackage = p.info.packageName;
7380                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7381                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7382                                if (r == null) {
7383                                    r = new StringBuilder(256);
7384                                } else {
7385                                    r.append(' ');
7386                                }
7387                                r.append(p.info.name);
7388                            }
7389                        } else {
7390                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7391                                    + p.info.packageName + " ignored: base tree "
7392                                    + tree.name + " is from package "
7393                                    + tree.sourcePackage);
7394                        }
7395                    } else {
7396                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7397                                + p.info.packageName + " ignored: original from "
7398                                + bp.sourcePackage);
7399                    }
7400                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7401                    if (r == null) {
7402                        r = new StringBuilder(256);
7403                    } else {
7404                        r.append(' ');
7405                    }
7406                    r.append("DUP:");
7407                    r.append(p.info.name);
7408                }
7409                if (bp.perm == p) {
7410                    bp.protectionLevel = p.info.protectionLevel;
7411                }
7412            }
7413
7414            if (r != null) {
7415                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7416            }
7417
7418            N = pkg.instrumentation.size();
7419            r = null;
7420            for (i=0; i<N; i++) {
7421                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7422                a.info.packageName = pkg.applicationInfo.packageName;
7423                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7424                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7425                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7426                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7427                a.info.dataDir = pkg.applicationInfo.dataDir;
7428
7429                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7430                // need other information about the application, like the ABI and what not ?
7431                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7432                mInstrumentation.put(a.getComponentName(), a);
7433                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7434                    if (r == null) {
7435                        r = new StringBuilder(256);
7436                    } else {
7437                        r.append(' ');
7438                    }
7439                    r.append(a.info.name);
7440                }
7441            }
7442            if (r != null) {
7443                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7444            }
7445
7446            if (pkg.protectedBroadcasts != null) {
7447                N = pkg.protectedBroadcasts.size();
7448                for (i=0; i<N; i++) {
7449                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7450                }
7451            }
7452
7453            pkgSetting.setTimeStamp(scanFileTime);
7454
7455            // Create idmap files for pairs of (packages, overlay packages).
7456            // Note: "android", ie framework-res.apk, is handled by native layers.
7457            if (pkg.mOverlayTarget != null) {
7458                // This is an overlay package.
7459                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7460                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7461                        mOverlays.put(pkg.mOverlayTarget,
7462                                new ArrayMap<String, PackageParser.Package>());
7463                    }
7464                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7465                    map.put(pkg.packageName, pkg);
7466                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7467                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7468                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7469                                "scanPackageLI failed to createIdmap");
7470                    }
7471                }
7472            } else if (mOverlays.containsKey(pkg.packageName) &&
7473                    !pkg.packageName.equals("android")) {
7474                // This is a regular package, with one or more known overlay packages.
7475                createIdmapsForPackageLI(pkg);
7476            }
7477        }
7478
7479        return pkg;
7480    }
7481
7482    /**
7483     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7484     * is derived purely on the basis of the contents of {@code scanFile} and
7485     * {@code cpuAbiOverride}.
7486     *
7487     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7488     */
7489    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7490                                 String cpuAbiOverride, boolean extractLibs)
7491            throws PackageManagerException {
7492        // TODO: We can probably be smarter about this stuff. For installed apps,
7493        // we can calculate this information at install time once and for all. For
7494        // system apps, we can probably assume that this information doesn't change
7495        // after the first boot scan. As things stand, we do lots of unnecessary work.
7496
7497        // Give ourselves some initial paths; we'll come back for another
7498        // pass once we've determined ABI below.
7499        setNativeLibraryPaths(pkg);
7500
7501        // We would never need to extract libs for forward-locked and external packages,
7502        // since the container service will do it for us. We shouldn't attempt to
7503        // extract libs from system app when it was not updated.
7504        if (pkg.isForwardLocked() || isExternal(pkg) ||
7505            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7506            extractLibs = false;
7507        }
7508
7509        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7510        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7511
7512        NativeLibraryHelper.Handle handle = null;
7513        try {
7514            handle = NativeLibraryHelper.Handle.create(pkg);
7515            // TODO(multiArch): This can be null for apps that didn't go through the
7516            // usual installation process. We can calculate it again, like we
7517            // do during install time.
7518            //
7519            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7520            // unnecessary.
7521            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7522
7523            // Null out the abis so that they can be recalculated.
7524            pkg.applicationInfo.primaryCpuAbi = null;
7525            pkg.applicationInfo.secondaryCpuAbi = null;
7526            if (isMultiArch(pkg.applicationInfo)) {
7527                // Warn if we've set an abiOverride for multi-lib packages..
7528                // By definition, we need to copy both 32 and 64 bit libraries for
7529                // such packages.
7530                if (pkg.cpuAbiOverride != null
7531                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7532                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7533                }
7534
7535                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7536                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7537                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7538                    if (extractLibs) {
7539                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7540                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7541                                useIsaSpecificSubdirs);
7542                    } else {
7543                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7544                    }
7545                }
7546
7547                maybeThrowExceptionForMultiArchCopy(
7548                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7549
7550                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7551                    if (extractLibs) {
7552                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7553                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7554                                useIsaSpecificSubdirs);
7555                    } else {
7556                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7557                    }
7558                }
7559
7560                maybeThrowExceptionForMultiArchCopy(
7561                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7562
7563                if (abi64 >= 0) {
7564                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7565                }
7566
7567                if (abi32 >= 0) {
7568                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7569                    if (abi64 >= 0) {
7570                        pkg.applicationInfo.secondaryCpuAbi = abi;
7571                    } else {
7572                        pkg.applicationInfo.primaryCpuAbi = abi;
7573                    }
7574                }
7575            } else {
7576                String[] abiList = (cpuAbiOverride != null) ?
7577                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7578
7579                // Enable gross and lame hacks for apps that are built with old
7580                // SDK tools. We must scan their APKs for renderscript bitcode and
7581                // not launch them if it's present. Don't bother checking on devices
7582                // that don't have 64 bit support.
7583                boolean needsRenderScriptOverride = false;
7584                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7585                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7586                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7587                    needsRenderScriptOverride = true;
7588                }
7589
7590                final int copyRet;
7591                if (extractLibs) {
7592                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7593                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7594                } else {
7595                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7596                }
7597
7598                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7599                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7600                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7601                }
7602
7603                if (copyRet >= 0) {
7604                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7605                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7606                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7607                } else if (needsRenderScriptOverride) {
7608                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7609                }
7610            }
7611        } catch (IOException ioe) {
7612            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7613        } finally {
7614            IoUtils.closeQuietly(handle);
7615        }
7616
7617        // Now that we've calculated the ABIs and determined if it's an internal app,
7618        // we will go ahead and populate the nativeLibraryPath.
7619        setNativeLibraryPaths(pkg);
7620    }
7621
7622    /**
7623     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7624     * i.e, so that all packages can be run inside a single process if required.
7625     *
7626     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7627     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7628     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7629     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7630     * updating a package that belongs to a shared user.
7631     *
7632     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7633     * adds unnecessary complexity.
7634     */
7635    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7636            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7637        String requiredInstructionSet = null;
7638        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7639            requiredInstructionSet = VMRuntime.getInstructionSet(
7640                     scannedPackage.applicationInfo.primaryCpuAbi);
7641        }
7642
7643        PackageSetting requirer = null;
7644        for (PackageSetting ps : packagesForUser) {
7645            // If packagesForUser contains scannedPackage, we skip it. This will happen
7646            // when scannedPackage is an update of an existing package. Without this check,
7647            // we will never be able to change the ABI of any package belonging to a shared
7648            // user, even if it's compatible with other packages.
7649            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7650                if (ps.primaryCpuAbiString == null) {
7651                    continue;
7652                }
7653
7654                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7655                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7656                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7657                    // this but there's not much we can do.
7658                    String errorMessage = "Instruction set mismatch, "
7659                            + ((requirer == null) ? "[caller]" : requirer)
7660                            + " requires " + requiredInstructionSet + " whereas " + ps
7661                            + " requires " + instructionSet;
7662                    Slog.w(TAG, errorMessage);
7663                }
7664
7665                if (requiredInstructionSet == null) {
7666                    requiredInstructionSet = instructionSet;
7667                    requirer = ps;
7668                }
7669            }
7670        }
7671
7672        if (requiredInstructionSet != null) {
7673            String adjustedAbi;
7674            if (requirer != null) {
7675                // requirer != null implies that either scannedPackage was null or that scannedPackage
7676                // did not require an ABI, in which case we have to adjust scannedPackage to match
7677                // the ABI of the set (which is the same as requirer's ABI)
7678                adjustedAbi = requirer.primaryCpuAbiString;
7679                if (scannedPackage != null) {
7680                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7681                }
7682            } else {
7683                // requirer == null implies that we're updating all ABIs in the set to
7684                // match scannedPackage.
7685                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7686            }
7687
7688            for (PackageSetting ps : packagesForUser) {
7689                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7690                    if (ps.primaryCpuAbiString != null) {
7691                        continue;
7692                    }
7693
7694                    ps.primaryCpuAbiString = adjustedAbi;
7695                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7696                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7697                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7698
7699                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7700                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7701                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7702                            ps.primaryCpuAbiString = null;
7703                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7704                            return;
7705                        } else {
7706                            mInstaller.rmdex(ps.codePathString,
7707                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7708                        }
7709                    }
7710                }
7711            }
7712        }
7713    }
7714
7715    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7716        synchronized (mPackages) {
7717            mResolverReplaced = true;
7718            // Set up information for custom user intent resolution activity.
7719            mResolveActivity.applicationInfo = pkg.applicationInfo;
7720            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7721            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7722            mResolveActivity.processName = pkg.applicationInfo.packageName;
7723            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7724            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7725                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7726            mResolveActivity.theme = 0;
7727            mResolveActivity.exported = true;
7728            mResolveActivity.enabled = true;
7729            mResolveInfo.activityInfo = mResolveActivity;
7730            mResolveInfo.priority = 0;
7731            mResolveInfo.preferredOrder = 0;
7732            mResolveInfo.match = 0;
7733            mResolveComponentName = mCustomResolverComponentName;
7734            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7735                    mResolveComponentName);
7736        }
7737    }
7738
7739    private static String calculateBundledApkRoot(final String codePathString) {
7740        final File codePath = new File(codePathString);
7741        final File codeRoot;
7742        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7743            codeRoot = Environment.getRootDirectory();
7744        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7745            codeRoot = Environment.getOemDirectory();
7746        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7747            codeRoot = Environment.getVendorDirectory();
7748        } else {
7749            // Unrecognized code path; take its top real segment as the apk root:
7750            // e.g. /something/app/blah.apk => /something
7751            try {
7752                File f = codePath.getCanonicalFile();
7753                File parent = f.getParentFile();    // non-null because codePath is a file
7754                File tmp;
7755                while ((tmp = parent.getParentFile()) != null) {
7756                    f = parent;
7757                    parent = tmp;
7758                }
7759                codeRoot = f;
7760                Slog.w(TAG, "Unrecognized code path "
7761                        + codePath + " - using " + codeRoot);
7762            } catch (IOException e) {
7763                // Can't canonicalize the code path -- shenanigans?
7764                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7765                return Environment.getRootDirectory().getPath();
7766            }
7767        }
7768        return codeRoot.getPath();
7769    }
7770
7771    /**
7772     * Derive and set the location of native libraries for the given package,
7773     * which varies depending on where and how the package was installed.
7774     */
7775    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7776        final ApplicationInfo info = pkg.applicationInfo;
7777        final String codePath = pkg.codePath;
7778        final File codeFile = new File(codePath);
7779        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7780        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7781
7782        info.nativeLibraryRootDir = null;
7783        info.nativeLibraryRootRequiresIsa = false;
7784        info.nativeLibraryDir = null;
7785        info.secondaryNativeLibraryDir = null;
7786
7787        if (isApkFile(codeFile)) {
7788            // Monolithic install
7789            if (bundledApp) {
7790                // If "/system/lib64/apkname" exists, assume that is the per-package
7791                // native library directory to use; otherwise use "/system/lib/apkname".
7792                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7793                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7794                        getPrimaryInstructionSet(info));
7795
7796                // This is a bundled system app so choose the path based on the ABI.
7797                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7798                // is just the default path.
7799                final String apkName = deriveCodePathName(codePath);
7800                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7801                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7802                        apkName).getAbsolutePath();
7803
7804                if (info.secondaryCpuAbi != null) {
7805                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7806                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7807                            secondaryLibDir, apkName).getAbsolutePath();
7808                }
7809            } else if (asecApp) {
7810                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7811                        .getAbsolutePath();
7812            } else {
7813                final String apkName = deriveCodePathName(codePath);
7814                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7815                        .getAbsolutePath();
7816            }
7817
7818            info.nativeLibraryRootRequiresIsa = false;
7819            info.nativeLibraryDir = info.nativeLibraryRootDir;
7820        } else {
7821            // Cluster install
7822            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7823            info.nativeLibraryRootRequiresIsa = true;
7824
7825            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7826                    getPrimaryInstructionSet(info)).getAbsolutePath();
7827
7828            if (info.secondaryCpuAbi != null) {
7829                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7830                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7831            }
7832        }
7833    }
7834
7835    /**
7836     * Calculate the abis and roots for a bundled app. These can uniquely
7837     * be determined from the contents of the system partition, i.e whether
7838     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7839     * of this information, and instead assume that the system was built
7840     * sensibly.
7841     */
7842    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7843                                           PackageSetting pkgSetting) {
7844        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7845
7846        // If "/system/lib64/apkname" exists, assume that is the per-package
7847        // native library directory to use; otherwise use "/system/lib/apkname".
7848        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7849        setBundledAppAbi(pkg, apkRoot, apkName);
7850        // pkgSetting might be null during rescan following uninstall of updates
7851        // to a bundled app, so accommodate that possibility.  The settings in
7852        // that case will be established later from the parsed package.
7853        //
7854        // If the settings aren't null, sync them up with what we've just derived.
7855        // note that apkRoot isn't stored in the package settings.
7856        if (pkgSetting != null) {
7857            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7858            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7859        }
7860    }
7861
7862    /**
7863     * Deduces the ABI of a bundled app and sets the relevant fields on the
7864     * parsed pkg object.
7865     *
7866     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7867     *        under which system libraries are installed.
7868     * @param apkName the name of the installed package.
7869     */
7870    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7871        final File codeFile = new File(pkg.codePath);
7872
7873        final boolean has64BitLibs;
7874        final boolean has32BitLibs;
7875        if (isApkFile(codeFile)) {
7876            // Monolithic install
7877            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7878            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7879        } else {
7880            // Cluster install
7881            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7882            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7883                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7884                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7885                has64BitLibs = (new File(rootDir, isa)).exists();
7886            } else {
7887                has64BitLibs = false;
7888            }
7889            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7890                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7891                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7892                has32BitLibs = (new File(rootDir, isa)).exists();
7893            } else {
7894                has32BitLibs = false;
7895            }
7896        }
7897
7898        if (has64BitLibs && !has32BitLibs) {
7899            // The package has 64 bit libs, but not 32 bit libs. Its primary
7900            // ABI should be 64 bit. We can safely assume here that the bundled
7901            // native libraries correspond to the most preferred ABI in the list.
7902
7903            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7904            pkg.applicationInfo.secondaryCpuAbi = null;
7905        } else if (has32BitLibs && !has64BitLibs) {
7906            // The package has 32 bit libs but not 64 bit libs. Its primary
7907            // ABI should be 32 bit.
7908
7909            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7910            pkg.applicationInfo.secondaryCpuAbi = null;
7911        } else if (has32BitLibs && has64BitLibs) {
7912            // The application has both 64 and 32 bit bundled libraries. We check
7913            // here that the app declares multiArch support, and warn if it doesn't.
7914            //
7915            // We will be lenient here and record both ABIs. The primary will be the
7916            // ABI that's higher on the list, i.e, a device that's configured to prefer
7917            // 64 bit apps will see a 64 bit primary ABI,
7918
7919            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7920                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7921            }
7922
7923            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7924                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7925                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7926            } else {
7927                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7928                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7929            }
7930        } else {
7931            pkg.applicationInfo.primaryCpuAbi = null;
7932            pkg.applicationInfo.secondaryCpuAbi = null;
7933        }
7934    }
7935
7936    private void killApplication(String pkgName, int appId, String reason) {
7937        // Request the ActivityManager to kill the process(only for existing packages)
7938        // so that we do not end up in a confused state while the user is still using the older
7939        // version of the application while the new one gets installed.
7940        IActivityManager am = ActivityManagerNative.getDefault();
7941        if (am != null) {
7942            try {
7943                am.killApplicationWithAppId(pkgName, appId, reason);
7944            } catch (RemoteException e) {
7945            }
7946        }
7947    }
7948
7949    void removePackageLI(PackageSetting ps, boolean chatty) {
7950        if (DEBUG_INSTALL) {
7951            if (chatty)
7952                Log.d(TAG, "Removing package " + ps.name);
7953        }
7954
7955        // writer
7956        synchronized (mPackages) {
7957            mPackages.remove(ps.name);
7958            final PackageParser.Package pkg = ps.pkg;
7959            if (pkg != null) {
7960                cleanPackageDataStructuresLILPw(pkg, chatty);
7961            }
7962        }
7963    }
7964
7965    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7966        if (DEBUG_INSTALL) {
7967            if (chatty)
7968                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7969        }
7970
7971        // writer
7972        synchronized (mPackages) {
7973            mPackages.remove(pkg.applicationInfo.packageName);
7974            cleanPackageDataStructuresLILPw(pkg, chatty);
7975        }
7976    }
7977
7978    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7979        int N = pkg.providers.size();
7980        StringBuilder r = null;
7981        int i;
7982        for (i=0; i<N; i++) {
7983            PackageParser.Provider p = pkg.providers.get(i);
7984            mProviders.removeProvider(p);
7985            if (p.info.authority == null) {
7986
7987                /* There was another ContentProvider with this authority when
7988                 * this app was installed so this authority is null,
7989                 * Ignore it as we don't have to unregister the provider.
7990                 */
7991                continue;
7992            }
7993            String names[] = p.info.authority.split(";");
7994            for (int j = 0; j < names.length; j++) {
7995                if (mProvidersByAuthority.get(names[j]) == p) {
7996                    mProvidersByAuthority.remove(names[j]);
7997                    if (DEBUG_REMOVE) {
7998                        if (chatty)
7999                            Log.d(TAG, "Unregistered content provider: " + names[j]
8000                                    + ", className = " + p.info.name + ", isSyncable = "
8001                                    + p.info.isSyncable);
8002                    }
8003                }
8004            }
8005            if (DEBUG_REMOVE && chatty) {
8006                if (r == null) {
8007                    r = new StringBuilder(256);
8008                } else {
8009                    r.append(' ');
8010                }
8011                r.append(p.info.name);
8012            }
8013        }
8014        if (r != null) {
8015            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8016        }
8017
8018        N = pkg.services.size();
8019        r = null;
8020        for (i=0; i<N; i++) {
8021            PackageParser.Service s = pkg.services.get(i);
8022            mServices.removeService(s);
8023            if (chatty) {
8024                if (r == null) {
8025                    r = new StringBuilder(256);
8026                } else {
8027                    r.append(' ');
8028                }
8029                r.append(s.info.name);
8030            }
8031        }
8032        if (r != null) {
8033            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8034        }
8035
8036        N = pkg.receivers.size();
8037        r = null;
8038        for (i=0; i<N; i++) {
8039            PackageParser.Activity a = pkg.receivers.get(i);
8040            mReceivers.removeActivity(a, "receiver");
8041            if (DEBUG_REMOVE && chatty) {
8042                if (r == null) {
8043                    r = new StringBuilder(256);
8044                } else {
8045                    r.append(' ');
8046                }
8047                r.append(a.info.name);
8048            }
8049        }
8050        if (r != null) {
8051            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8052        }
8053
8054        N = pkg.activities.size();
8055        r = null;
8056        for (i=0; i<N; i++) {
8057            PackageParser.Activity a = pkg.activities.get(i);
8058            mActivities.removeActivity(a, "activity");
8059            if (DEBUG_REMOVE && chatty) {
8060                if (r == null) {
8061                    r = new StringBuilder(256);
8062                } else {
8063                    r.append(' ');
8064                }
8065                r.append(a.info.name);
8066            }
8067        }
8068        if (r != null) {
8069            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8070        }
8071
8072        N = pkg.permissions.size();
8073        r = null;
8074        for (i=0; i<N; i++) {
8075            PackageParser.Permission p = pkg.permissions.get(i);
8076            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8077            if (bp == null) {
8078                bp = mSettings.mPermissionTrees.get(p.info.name);
8079            }
8080            if (bp != null && bp.perm == p) {
8081                bp.perm = null;
8082                if (DEBUG_REMOVE && chatty) {
8083                    if (r == null) {
8084                        r = new StringBuilder(256);
8085                    } else {
8086                        r.append(' ');
8087                    }
8088                    r.append(p.info.name);
8089                }
8090            }
8091            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8092                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8093                if (appOpPerms != null) {
8094                    appOpPerms.remove(pkg.packageName);
8095                }
8096            }
8097        }
8098        if (r != null) {
8099            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8100        }
8101
8102        N = pkg.requestedPermissions.size();
8103        r = null;
8104        for (i=0; i<N; i++) {
8105            String perm = pkg.requestedPermissions.get(i);
8106            BasePermission bp = mSettings.mPermissions.get(perm);
8107            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8108                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8109                if (appOpPerms != null) {
8110                    appOpPerms.remove(pkg.packageName);
8111                    if (appOpPerms.isEmpty()) {
8112                        mAppOpPermissionPackages.remove(perm);
8113                    }
8114                }
8115            }
8116        }
8117        if (r != null) {
8118            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8119        }
8120
8121        N = pkg.instrumentation.size();
8122        r = null;
8123        for (i=0; i<N; i++) {
8124            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8125            mInstrumentation.remove(a.getComponentName());
8126            if (DEBUG_REMOVE && chatty) {
8127                if (r == null) {
8128                    r = new StringBuilder(256);
8129                } else {
8130                    r.append(' ');
8131                }
8132                r.append(a.info.name);
8133            }
8134        }
8135        if (r != null) {
8136            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8137        }
8138
8139        r = null;
8140        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8141            // Only system apps can hold shared libraries.
8142            if (pkg.libraryNames != null) {
8143                for (i=0; i<pkg.libraryNames.size(); i++) {
8144                    String name = pkg.libraryNames.get(i);
8145                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8146                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8147                        mSharedLibraries.remove(name);
8148                        if (DEBUG_REMOVE && chatty) {
8149                            if (r == null) {
8150                                r = new StringBuilder(256);
8151                            } else {
8152                                r.append(' ');
8153                            }
8154                            r.append(name);
8155                        }
8156                    }
8157                }
8158            }
8159        }
8160        if (r != null) {
8161            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8162        }
8163    }
8164
8165    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8166        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8167            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8168                return true;
8169            }
8170        }
8171        return false;
8172    }
8173
8174    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8175    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8176    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8177
8178    private void updatePermissionsLPw(String changingPkg,
8179            PackageParser.Package pkgInfo, int flags) {
8180        // Make sure there are no dangling permission trees.
8181        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8182        while (it.hasNext()) {
8183            final BasePermission bp = it.next();
8184            if (bp.packageSetting == null) {
8185                // We may not yet have parsed the package, so just see if
8186                // we still know about its settings.
8187                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8188            }
8189            if (bp.packageSetting == null) {
8190                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8191                        + " from package " + bp.sourcePackage);
8192                it.remove();
8193            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8194                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8195                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8196                            + " from package " + bp.sourcePackage);
8197                    flags |= UPDATE_PERMISSIONS_ALL;
8198                    it.remove();
8199                }
8200            }
8201        }
8202
8203        // Make sure all dynamic permissions have been assigned to a package,
8204        // and make sure there are no dangling permissions.
8205        it = mSettings.mPermissions.values().iterator();
8206        while (it.hasNext()) {
8207            final BasePermission bp = it.next();
8208            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8209                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8210                        + bp.name + " pkg=" + bp.sourcePackage
8211                        + " info=" + bp.pendingInfo);
8212                if (bp.packageSetting == null && bp.pendingInfo != null) {
8213                    final BasePermission tree = findPermissionTreeLP(bp.name);
8214                    if (tree != null && tree.perm != null) {
8215                        bp.packageSetting = tree.packageSetting;
8216                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8217                                new PermissionInfo(bp.pendingInfo));
8218                        bp.perm.info.packageName = tree.perm.info.packageName;
8219                        bp.perm.info.name = bp.name;
8220                        bp.uid = tree.uid;
8221                    }
8222                }
8223            }
8224            if (bp.packageSetting == null) {
8225                // We may not yet have parsed the package, so just see if
8226                // we still know about its settings.
8227                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8228            }
8229            if (bp.packageSetting == null) {
8230                Slog.w(TAG, "Removing dangling permission: " + bp.name
8231                        + " from package " + bp.sourcePackage);
8232                it.remove();
8233            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8234                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8235                    Slog.i(TAG, "Removing old permission: " + bp.name
8236                            + " from package " + bp.sourcePackage);
8237                    flags |= UPDATE_PERMISSIONS_ALL;
8238                    it.remove();
8239                }
8240            }
8241        }
8242
8243        // Now update the permissions for all packages, in particular
8244        // replace the granted permissions of the system packages.
8245        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8246            for (PackageParser.Package pkg : mPackages.values()) {
8247                if (pkg != pkgInfo) {
8248                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8249                            changingPkg);
8250                }
8251            }
8252        }
8253
8254        if (pkgInfo != null) {
8255            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8256        }
8257    }
8258
8259    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8260            String packageOfInterest) {
8261        // IMPORTANT: There are two types of permissions: install and runtime.
8262        // Install time permissions are granted when the app is installed to
8263        // all device users and users added in the future. Runtime permissions
8264        // are granted at runtime explicitly to specific users. Normal and signature
8265        // protected permissions are install time permissions. Dangerous permissions
8266        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8267        // otherwise they are runtime permissions. This function does not manage
8268        // runtime permissions except for the case an app targeting Lollipop MR1
8269        // being upgraded to target a newer SDK, in which case dangerous permissions
8270        // are transformed from install time to runtime ones.
8271
8272        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8273        if (ps == null) {
8274            return;
8275        }
8276
8277        PermissionsState permissionsState = ps.getPermissionsState();
8278        PermissionsState origPermissions = permissionsState;
8279
8280        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8281
8282        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8283
8284        boolean changedInstallPermission = false;
8285
8286        if (replace) {
8287            ps.installPermissionsFixed = false;
8288            if (!ps.isSharedUser()) {
8289                origPermissions = new PermissionsState(permissionsState);
8290                permissionsState.reset();
8291            }
8292        }
8293
8294        permissionsState.setGlobalGids(mGlobalGids);
8295
8296        final int N = pkg.requestedPermissions.size();
8297        for (int i=0; i<N; i++) {
8298            final String name = pkg.requestedPermissions.get(i);
8299            final BasePermission bp = mSettings.mPermissions.get(name);
8300
8301            if (DEBUG_INSTALL) {
8302                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8303            }
8304
8305            if (bp == null || bp.packageSetting == null) {
8306                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8307                    Slog.w(TAG, "Unknown permission " + name
8308                            + " in package " + pkg.packageName);
8309                }
8310                continue;
8311            }
8312
8313            final String perm = bp.name;
8314            boolean allowedSig = false;
8315            int grant = GRANT_DENIED;
8316
8317            // Keep track of app op permissions.
8318            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8319                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8320                if (pkgs == null) {
8321                    pkgs = new ArraySet<>();
8322                    mAppOpPermissionPackages.put(bp.name, pkgs);
8323                }
8324                pkgs.add(pkg.packageName);
8325            }
8326
8327            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8328            switch (level) {
8329                case PermissionInfo.PROTECTION_NORMAL: {
8330                    // For all apps normal permissions are install time ones.
8331                    grant = GRANT_INSTALL;
8332                } break;
8333
8334                case PermissionInfo.PROTECTION_DANGEROUS: {
8335                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8336                        // For legacy apps dangerous permissions are install time ones.
8337                        grant = GRANT_INSTALL_LEGACY;
8338                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8339                        // For legacy apps that became modern, install becomes runtime.
8340                        grant = GRANT_UPGRADE;
8341                    } else {
8342                        // For modern apps keep runtime permissions unchanged.
8343                        grant = GRANT_RUNTIME;
8344                    }
8345                } break;
8346
8347                case PermissionInfo.PROTECTION_SIGNATURE: {
8348                    // For all apps signature permissions are install time ones.
8349                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8350                    if (allowedSig) {
8351                        grant = GRANT_INSTALL;
8352                    }
8353                } break;
8354            }
8355
8356            if (DEBUG_INSTALL) {
8357                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8358            }
8359
8360            if (grant != GRANT_DENIED) {
8361                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8362                    // If this is an existing, non-system package, then
8363                    // we can't add any new permissions to it.
8364                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8365                        // Except...  if this is a permission that was added
8366                        // to the platform (note: need to only do this when
8367                        // updating the platform).
8368                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8369                            grant = GRANT_DENIED;
8370                        }
8371                    }
8372                }
8373
8374                switch (grant) {
8375                    case GRANT_INSTALL: {
8376                        // Revoke this as runtime permission to handle the case of
8377                        // a runtime permission being downgraded to an install one.
8378                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8379                            if (origPermissions.getRuntimePermissionState(
8380                                    bp.name, userId) != null) {
8381                                // Revoke the runtime permission and clear the flags.
8382                                origPermissions.revokeRuntimePermission(bp, userId);
8383                                origPermissions.updatePermissionFlags(bp, userId,
8384                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8385                                // If we revoked a permission permission, we have to write.
8386                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8387                                        changedRuntimePermissionUserIds, userId);
8388                            }
8389                        }
8390                        // Grant an install permission.
8391                        if (permissionsState.grantInstallPermission(bp) !=
8392                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8393                            changedInstallPermission = true;
8394                        }
8395                    } break;
8396
8397                    case GRANT_INSTALL_LEGACY: {
8398                        // Grant an install permission.
8399                        if (permissionsState.grantInstallPermission(bp) !=
8400                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8401                            changedInstallPermission = true;
8402                        }
8403                    } break;
8404
8405                    case GRANT_RUNTIME: {
8406                        // Grant previously granted runtime permissions.
8407                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8408                            PermissionState permissionState = origPermissions
8409                                    .getRuntimePermissionState(bp.name, userId);
8410                            final int flags = permissionState != null
8411                                    ? permissionState.getFlags() : 0;
8412                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8413                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8414                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8415                                    // If we cannot put the permission as it was, we have to write.
8416                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8417                                            changedRuntimePermissionUserIds, userId);
8418                                }
8419                            }
8420                            // Propagate the permission flags.
8421                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8422                        }
8423                    } break;
8424
8425                    case GRANT_UPGRADE: {
8426                        // Grant runtime permissions for a previously held install permission.
8427                        PermissionState permissionState = origPermissions
8428                                .getInstallPermissionState(bp.name);
8429                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8430
8431                        if (origPermissions.revokeInstallPermission(bp)
8432                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8433                            // We will be transferring the permission flags, so clear them.
8434                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8435                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8436                            changedInstallPermission = true;
8437                        }
8438
8439                        // If the permission is not to be promoted to runtime we ignore it and
8440                        // also its other flags as they are not applicable to install permissions.
8441                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8442                            for (int userId : currentUserIds) {
8443                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8444                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8445                                    // Transfer the permission flags.
8446                                    permissionsState.updatePermissionFlags(bp, userId,
8447                                            flags, flags);
8448                                    // If we granted the permission, we have to write.
8449                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8450                                            changedRuntimePermissionUserIds, userId);
8451                                }
8452                            }
8453                        }
8454                    } break;
8455
8456                    default: {
8457                        if (packageOfInterest == null
8458                                || packageOfInterest.equals(pkg.packageName)) {
8459                            Slog.w(TAG, "Not granting permission " + perm
8460                                    + " to package " + pkg.packageName
8461                                    + " because it was previously installed without");
8462                        }
8463                    } break;
8464                }
8465            } else {
8466                if (permissionsState.revokeInstallPermission(bp) !=
8467                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8468                    // Also drop the permission flags.
8469                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8470                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8471                    changedInstallPermission = true;
8472                    Slog.i(TAG, "Un-granting permission " + perm
8473                            + " from package " + pkg.packageName
8474                            + " (protectionLevel=" + bp.protectionLevel
8475                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8476                            + ")");
8477                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8478                    // Don't print warning for app op permissions, since it is fine for them
8479                    // not to be granted, there is a UI for the user to decide.
8480                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8481                        Slog.w(TAG, "Not granting permission " + perm
8482                                + " to package " + pkg.packageName
8483                                + " (protectionLevel=" + bp.protectionLevel
8484                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8485                                + ")");
8486                    }
8487                }
8488            }
8489        }
8490
8491        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8492                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8493            // This is the first that we have heard about this package, so the
8494            // permissions we have now selected are fixed until explicitly
8495            // changed.
8496            ps.installPermissionsFixed = true;
8497        }
8498
8499        // Persist the runtime permissions state for users with changes.
8500        for (int userId : changedRuntimePermissionUserIds) {
8501            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8502        }
8503    }
8504
8505    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8506        boolean allowed = false;
8507        final int NP = PackageParser.NEW_PERMISSIONS.length;
8508        for (int ip=0; ip<NP; ip++) {
8509            final PackageParser.NewPermissionInfo npi
8510                    = PackageParser.NEW_PERMISSIONS[ip];
8511            if (npi.name.equals(perm)
8512                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8513                allowed = true;
8514                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8515                        + pkg.packageName);
8516                break;
8517            }
8518        }
8519        return allowed;
8520    }
8521
8522    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8523            BasePermission bp, PermissionsState origPermissions) {
8524        boolean allowed;
8525        allowed = (compareSignatures(
8526                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8527                        == PackageManager.SIGNATURE_MATCH)
8528                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8529                        == PackageManager.SIGNATURE_MATCH);
8530        if (!allowed && (bp.protectionLevel
8531                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8532            if (isSystemApp(pkg)) {
8533                // For updated system applications, a system permission
8534                // is granted only if it had been defined by the original application.
8535                if (pkg.isUpdatedSystemApp()) {
8536                    final PackageSetting sysPs = mSettings
8537                            .getDisabledSystemPkgLPr(pkg.packageName);
8538                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8539                        // If the original was granted this permission, we take
8540                        // that grant decision as read and propagate it to the
8541                        // update.
8542                        if (sysPs.isPrivileged()) {
8543                            allowed = true;
8544                        }
8545                    } else {
8546                        // The system apk may have been updated with an older
8547                        // version of the one on the data partition, but which
8548                        // granted a new system permission that it didn't have
8549                        // before.  In this case we do want to allow the app to
8550                        // now get the new permission if the ancestral apk is
8551                        // privileged to get it.
8552                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8553                            for (int j=0;
8554                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8555                                if (perm.equals(
8556                                        sysPs.pkg.requestedPermissions.get(j))) {
8557                                    allowed = true;
8558                                    break;
8559                                }
8560                            }
8561                        }
8562                    }
8563                } else {
8564                    allowed = isPrivilegedApp(pkg);
8565                }
8566            }
8567        }
8568        if (!allowed) {
8569            if (!allowed && (bp.protectionLevel
8570                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8571                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8572                // If this was a previously normal/dangerous permission that got moved
8573                // to a system permission as part of the runtime permission redesign, then
8574                // we still want to blindly grant it to old apps.
8575                allowed = true;
8576            }
8577            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8578                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8579                // If this permission is to be granted to the system installer and
8580                // this app is an installer, then it gets the permission.
8581                allowed = true;
8582            }
8583            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8584                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8585                // If this permission is to be granted to the system verifier and
8586                // this app is a verifier, then it gets the permission.
8587                allowed = true;
8588            }
8589            if (!allowed && (bp.protectionLevel
8590                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8591                    && isSystemApp(pkg)) {
8592                // Any pre-installed system app is allowed to get this permission.
8593                allowed = true;
8594            }
8595            if (!allowed && (bp.protectionLevel
8596                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8597                // For development permissions, a development permission
8598                // is granted only if it was already granted.
8599                allowed = origPermissions.hasInstallPermission(perm);
8600            }
8601        }
8602        return allowed;
8603    }
8604
8605    final class ActivityIntentResolver
8606            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8607        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8608                boolean defaultOnly, int userId) {
8609            if (!sUserManager.exists(userId)) return null;
8610            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8611            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8612        }
8613
8614        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8615                int userId) {
8616            if (!sUserManager.exists(userId)) return null;
8617            mFlags = flags;
8618            return super.queryIntent(intent, resolvedType,
8619                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8620        }
8621
8622        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8623                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8624            if (!sUserManager.exists(userId)) return null;
8625            if (packageActivities == null) {
8626                return null;
8627            }
8628            mFlags = flags;
8629            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8630            final int N = packageActivities.size();
8631            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8632                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8633
8634            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8635            for (int i = 0; i < N; ++i) {
8636                intentFilters = packageActivities.get(i).intents;
8637                if (intentFilters != null && intentFilters.size() > 0) {
8638                    PackageParser.ActivityIntentInfo[] array =
8639                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8640                    intentFilters.toArray(array);
8641                    listCut.add(array);
8642                }
8643            }
8644            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8645        }
8646
8647        public final void addActivity(PackageParser.Activity a, String type) {
8648            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8649            mActivities.put(a.getComponentName(), a);
8650            if (DEBUG_SHOW_INFO)
8651                Log.v(
8652                TAG, "  " + type + " " +
8653                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8654            if (DEBUG_SHOW_INFO)
8655                Log.v(TAG, "    Class=" + a.info.name);
8656            final int NI = a.intents.size();
8657            for (int j=0; j<NI; j++) {
8658                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8659                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8660                    intent.setPriority(0);
8661                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8662                            + a.className + " with priority > 0, forcing to 0");
8663                }
8664                if (DEBUG_SHOW_INFO) {
8665                    Log.v(TAG, "    IntentFilter:");
8666                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8667                }
8668                if (!intent.debugCheck()) {
8669                    Log.w(TAG, "==> For Activity " + a.info.name);
8670                }
8671                addFilter(intent);
8672            }
8673        }
8674
8675        public final void removeActivity(PackageParser.Activity a, String type) {
8676            mActivities.remove(a.getComponentName());
8677            if (DEBUG_SHOW_INFO) {
8678                Log.v(TAG, "  " + type + " "
8679                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8680                                : a.info.name) + ":");
8681                Log.v(TAG, "    Class=" + a.info.name);
8682            }
8683            final int NI = a.intents.size();
8684            for (int j=0; j<NI; j++) {
8685                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8686                if (DEBUG_SHOW_INFO) {
8687                    Log.v(TAG, "    IntentFilter:");
8688                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8689                }
8690                removeFilter(intent);
8691            }
8692        }
8693
8694        @Override
8695        protected boolean allowFilterResult(
8696                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8697            ActivityInfo filterAi = filter.activity.info;
8698            for (int i=dest.size()-1; i>=0; i--) {
8699                ActivityInfo destAi = dest.get(i).activityInfo;
8700                if (destAi.name == filterAi.name
8701                        && destAi.packageName == filterAi.packageName) {
8702                    return false;
8703                }
8704            }
8705            return true;
8706        }
8707
8708        @Override
8709        protected ActivityIntentInfo[] newArray(int size) {
8710            return new ActivityIntentInfo[size];
8711        }
8712
8713        @Override
8714        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8715            if (!sUserManager.exists(userId)) return true;
8716            PackageParser.Package p = filter.activity.owner;
8717            if (p != null) {
8718                PackageSetting ps = (PackageSetting)p.mExtras;
8719                if (ps != null) {
8720                    // System apps are never considered stopped for purposes of
8721                    // filtering, because there may be no way for the user to
8722                    // actually re-launch them.
8723                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8724                            && ps.getStopped(userId);
8725                }
8726            }
8727            return false;
8728        }
8729
8730        @Override
8731        protected boolean isPackageForFilter(String packageName,
8732                PackageParser.ActivityIntentInfo info) {
8733            return packageName.equals(info.activity.owner.packageName);
8734        }
8735
8736        @Override
8737        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8738                int match, int userId) {
8739            if (!sUserManager.exists(userId)) return null;
8740            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8741                return null;
8742            }
8743            final PackageParser.Activity activity = info.activity;
8744            if (mSafeMode && (activity.info.applicationInfo.flags
8745                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8746                return null;
8747            }
8748            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8749            if (ps == null) {
8750                return null;
8751            }
8752            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8753                    ps.readUserState(userId), userId);
8754            if (ai == null) {
8755                return null;
8756            }
8757            final ResolveInfo res = new ResolveInfo();
8758            res.activityInfo = ai;
8759            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8760                res.filter = info;
8761            }
8762            if (info != null) {
8763                res.handleAllWebDataURI = info.handleAllWebDataURI();
8764            }
8765            res.priority = info.getPriority();
8766            res.preferredOrder = activity.owner.mPreferredOrder;
8767            //System.out.println("Result: " + res.activityInfo.className +
8768            //                   " = " + res.priority);
8769            res.match = match;
8770            res.isDefault = info.hasDefault;
8771            res.labelRes = info.labelRes;
8772            res.nonLocalizedLabel = info.nonLocalizedLabel;
8773            if (userNeedsBadging(userId)) {
8774                res.noResourceId = true;
8775            } else {
8776                res.icon = info.icon;
8777            }
8778            res.iconResourceId = info.icon;
8779            res.system = res.activityInfo.applicationInfo.isSystemApp();
8780            return res;
8781        }
8782
8783        @Override
8784        protected void sortResults(List<ResolveInfo> results) {
8785            Collections.sort(results, mResolvePrioritySorter);
8786        }
8787
8788        @Override
8789        protected void dumpFilter(PrintWriter out, String prefix,
8790                PackageParser.ActivityIntentInfo filter) {
8791            out.print(prefix); out.print(
8792                    Integer.toHexString(System.identityHashCode(filter.activity)));
8793                    out.print(' ');
8794                    filter.activity.printComponentShortName(out);
8795                    out.print(" filter ");
8796                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8797        }
8798
8799        @Override
8800        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8801            return filter.activity;
8802        }
8803
8804        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8805            PackageParser.Activity activity = (PackageParser.Activity)label;
8806            out.print(prefix); out.print(
8807                    Integer.toHexString(System.identityHashCode(activity)));
8808                    out.print(' ');
8809                    activity.printComponentShortName(out);
8810            if (count > 1) {
8811                out.print(" ("); out.print(count); out.print(" filters)");
8812            }
8813            out.println();
8814        }
8815
8816//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8817//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8818//            final List<ResolveInfo> retList = Lists.newArrayList();
8819//            while (i.hasNext()) {
8820//                final ResolveInfo resolveInfo = i.next();
8821//                if (isEnabledLP(resolveInfo.activityInfo)) {
8822//                    retList.add(resolveInfo);
8823//                }
8824//            }
8825//            return retList;
8826//        }
8827
8828        // Keys are String (activity class name), values are Activity.
8829        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8830                = new ArrayMap<ComponentName, PackageParser.Activity>();
8831        private int mFlags;
8832    }
8833
8834    private final class ServiceIntentResolver
8835            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8836        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8837                boolean defaultOnly, int userId) {
8838            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8839            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8840        }
8841
8842        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8843                int userId) {
8844            if (!sUserManager.exists(userId)) return null;
8845            mFlags = flags;
8846            return super.queryIntent(intent, resolvedType,
8847                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8848        }
8849
8850        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8851                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8852            if (!sUserManager.exists(userId)) return null;
8853            if (packageServices == null) {
8854                return null;
8855            }
8856            mFlags = flags;
8857            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8858            final int N = packageServices.size();
8859            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8860                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8861
8862            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8863            for (int i = 0; i < N; ++i) {
8864                intentFilters = packageServices.get(i).intents;
8865                if (intentFilters != null && intentFilters.size() > 0) {
8866                    PackageParser.ServiceIntentInfo[] array =
8867                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8868                    intentFilters.toArray(array);
8869                    listCut.add(array);
8870                }
8871            }
8872            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8873        }
8874
8875        public final void addService(PackageParser.Service s) {
8876            mServices.put(s.getComponentName(), s);
8877            if (DEBUG_SHOW_INFO) {
8878                Log.v(TAG, "  "
8879                        + (s.info.nonLocalizedLabel != null
8880                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8881                Log.v(TAG, "    Class=" + s.info.name);
8882            }
8883            final int NI = s.intents.size();
8884            int j;
8885            for (j=0; j<NI; j++) {
8886                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8887                if (DEBUG_SHOW_INFO) {
8888                    Log.v(TAG, "    IntentFilter:");
8889                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8890                }
8891                if (!intent.debugCheck()) {
8892                    Log.w(TAG, "==> For Service " + s.info.name);
8893                }
8894                addFilter(intent);
8895            }
8896        }
8897
8898        public final void removeService(PackageParser.Service s) {
8899            mServices.remove(s.getComponentName());
8900            if (DEBUG_SHOW_INFO) {
8901                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8902                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8903                Log.v(TAG, "    Class=" + s.info.name);
8904            }
8905            final int NI = s.intents.size();
8906            int j;
8907            for (j=0; j<NI; j++) {
8908                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8909                if (DEBUG_SHOW_INFO) {
8910                    Log.v(TAG, "    IntentFilter:");
8911                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8912                }
8913                removeFilter(intent);
8914            }
8915        }
8916
8917        @Override
8918        protected boolean allowFilterResult(
8919                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8920            ServiceInfo filterSi = filter.service.info;
8921            for (int i=dest.size()-1; i>=0; i--) {
8922                ServiceInfo destAi = dest.get(i).serviceInfo;
8923                if (destAi.name == filterSi.name
8924                        && destAi.packageName == filterSi.packageName) {
8925                    return false;
8926                }
8927            }
8928            return true;
8929        }
8930
8931        @Override
8932        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8933            return new PackageParser.ServiceIntentInfo[size];
8934        }
8935
8936        @Override
8937        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8938            if (!sUserManager.exists(userId)) return true;
8939            PackageParser.Package p = filter.service.owner;
8940            if (p != null) {
8941                PackageSetting ps = (PackageSetting)p.mExtras;
8942                if (ps != null) {
8943                    // System apps are never considered stopped for purposes of
8944                    // filtering, because there may be no way for the user to
8945                    // actually re-launch them.
8946                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8947                            && ps.getStopped(userId);
8948                }
8949            }
8950            return false;
8951        }
8952
8953        @Override
8954        protected boolean isPackageForFilter(String packageName,
8955                PackageParser.ServiceIntentInfo info) {
8956            return packageName.equals(info.service.owner.packageName);
8957        }
8958
8959        @Override
8960        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8961                int match, int userId) {
8962            if (!sUserManager.exists(userId)) return null;
8963            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8964            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8965                return null;
8966            }
8967            final PackageParser.Service service = info.service;
8968            if (mSafeMode && (service.info.applicationInfo.flags
8969                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8970                return null;
8971            }
8972            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8973            if (ps == null) {
8974                return null;
8975            }
8976            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8977                    ps.readUserState(userId), userId);
8978            if (si == null) {
8979                return null;
8980            }
8981            final ResolveInfo res = new ResolveInfo();
8982            res.serviceInfo = si;
8983            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8984                res.filter = filter;
8985            }
8986            res.priority = info.getPriority();
8987            res.preferredOrder = service.owner.mPreferredOrder;
8988            res.match = match;
8989            res.isDefault = info.hasDefault;
8990            res.labelRes = info.labelRes;
8991            res.nonLocalizedLabel = info.nonLocalizedLabel;
8992            res.icon = info.icon;
8993            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8994            return res;
8995        }
8996
8997        @Override
8998        protected void sortResults(List<ResolveInfo> results) {
8999            Collections.sort(results, mResolvePrioritySorter);
9000        }
9001
9002        @Override
9003        protected void dumpFilter(PrintWriter out, String prefix,
9004                PackageParser.ServiceIntentInfo filter) {
9005            out.print(prefix); out.print(
9006                    Integer.toHexString(System.identityHashCode(filter.service)));
9007                    out.print(' ');
9008                    filter.service.printComponentShortName(out);
9009                    out.print(" filter ");
9010                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9011        }
9012
9013        @Override
9014        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9015            return filter.service;
9016        }
9017
9018        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9019            PackageParser.Service service = (PackageParser.Service)label;
9020            out.print(prefix); out.print(
9021                    Integer.toHexString(System.identityHashCode(service)));
9022                    out.print(' ');
9023                    service.printComponentShortName(out);
9024            if (count > 1) {
9025                out.print(" ("); out.print(count); out.print(" filters)");
9026            }
9027            out.println();
9028        }
9029
9030//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9031//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9032//            final List<ResolveInfo> retList = Lists.newArrayList();
9033//            while (i.hasNext()) {
9034//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9035//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9036//                    retList.add(resolveInfo);
9037//                }
9038//            }
9039//            return retList;
9040//        }
9041
9042        // Keys are String (activity class name), values are Activity.
9043        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9044                = new ArrayMap<ComponentName, PackageParser.Service>();
9045        private int mFlags;
9046    };
9047
9048    private final class ProviderIntentResolver
9049            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9050        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9051                boolean defaultOnly, int userId) {
9052            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9053            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9054        }
9055
9056        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9057                int userId) {
9058            if (!sUserManager.exists(userId))
9059                return null;
9060            mFlags = flags;
9061            return super.queryIntent(intent, resolvedType,
9062                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9063        }
9064
9065        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9066                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9067            if (!sUserManager.exists(userId))
9068                return null;
9069            if (packageProviders == null) {
9070                return null;
9071            }
9072            mFlags = flags;
9073            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9074            final int N = packageProviders.size();
9075            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9076                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9077
9078            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9079            for (int i = 0; i < N; ++i) {
9080                intentFilters = packageProviders.get(i).intents;
9081                if (intentFilters != null && intentFilters.size() > 0) {
9082                    PackageParser.ProviderIntentInfo[] array =
9083                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9084                    intentFilters.toArray(array);
9085                    listCut.add(array);
9086                }
9087            }
9088            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9089        }
9090
9091        public final void addProvider(PackageParser.Provider p) {
9092            if (mProviders.containsKey(p.getComponentName())) {
9093                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9094                return;
9095            }
9096
9097            mProviders.put(p.getComponentName(), p);
9098            if (DEBUG_SHOW_INFO) {
9099                Log.v(TAG, "  "
9100                        + (p.info.nonLocalizedLabel != null
9101                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9102                Log.v(TAG, "    Class=" + p.info.name);
9103            }
9104            final int NI = p.intents.size();
9105            int j;
9106            for (j = 0; j < NI; j++) {
9107                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9108                if (DEBUG_SHOW_INFO) {
9109                    Log.v(TAG, "    IntentFilter:");
9110                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9111                }
9112                if (!intent.debugCheck()) {
9113                    Log.w(TAG, "==> For Provider " + p.info.name);
9114                }
9115                addFilter(intent);
9116            }
9117        }
9118
9119        public final void removeProvider(PackageParser.Provider p) {
9120            mProviders.remove(p.getComponentName());
9121            if (DEBUG_SHOW_INFO) {
9122                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9123                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9124                Log.v(TAG, "    Class=" + p.info.name);
9125            }
9126            final int NI = p.intents.size();
9127            int j;
9128            for (j = 0; j < NI; j++) {
9129                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9130                if (DEBUG_SHOW_INFO) {
9131                    Log.v(TAG, "    IntentFilter:");
9132                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9133                }
9134                removeFilter(intent);
9135            }
9136        }
9137
9138        @Override
9139        protected boolean allowFilterResult(
9140                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9141            ProviderInfo filterPi = filter.provider.info;
9142            for (int i = dest.size() - 1; i >= 0; i--) {
9143                ProviderInfo destPi = dest.get(i).providerInfo;
9144                if (destPi.name == filterPi.name
9145                        && destPi.packageName == filterPi.packageName) {
9146                    return false;
9147                }
9148            }
9149            return true;
9150        }
9151
9152        @Override
9153        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9154            return new PackageParser.ProviderIntentInfo[size];
9155        }
9156
9157        @Override
9158        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9159            if (!sUserManager.exists(userId))
9160                return true;
9161            PackageParser.Package p = filter.provider.owner;
9162            if (p != null) {
9163                PackageSetting ps = (PackageSetting) p.mExtras;
9164                if (ps != null) {
9165                    // System apps are never considered stopped for purposes of
9166                    // filtering, because there may be no way for the user to
9167                    // actually re-launch them.
9168                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9169                            && ps.getStopped(userId);
9170                }
9171            }
9172            return false;
9173        }
9174
9175        @Override
9176        protected boolean isPackageForFilter(String packageName,
9177                PackageParser.ProviderIntentInfo info) {
9178            return packageName.equals(info.provider.owner.packageName);
9179        }
9180
9181        @Override
9182        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9183                int match, int userId) {
9184            if (!sUserManager.exists(userId))
9185                return null;
9186            final PackageParser.ProviderIntentInfo info = filter;
9187            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9188                return null;
9189            }
9190            final PackageParser.Provider provider = info.provider;
9191            if (mSafeMode && (provider.info.applicationInfo.flags
9192                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9193                return null;
9194            }
9195            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9196            if (ps == null) {
9197                return null;
9198            }
9199            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9200                    ps.readUserState(userId), userId);
9201            if (pi == null) {
9202                return null;
9203            }
9204            final ResolveInfo res = new ResolveInfo();
9205            res.providerInfo = pi;
9206            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9207                res.filter = filter;
9208            }
9209            res.priority = info.getPriority();
9210            res.preferredOrder = provider.owner.mPreferredOrder;
9211            res.match = match;
9212            res.isDefault = info.hasDefault;
9213            res.labelRes = info.labelRes;
9214            res.nonLocalizedLabel = info.nonLocalizedLabel;
9215            res.icon = info.icon;
9216            res.system = res.providerInfo.applicationInfo.isSystemApp();
9217            return res;
9218        }
9219
9220        @Override
9221        protected void sortResults(List<ResolveInfo> results) {
9222            Collections.sort(results, mResolvePrioritySorter);
9223        }
9224
9225        @Override
9226        protected void dumpFilter(PrintWriter out, String prefix,
9227                PackageParser.ProviderIntentInfo filter) {
9228            out.print(prefix);
9229            out.print(
9230                    Integer.toHexString(System.identityHashCode(filter.provider)));
9231            out.print(' ');
9232            filter.provider.printComponentShortName(out);
9233            out.print(" filter ");
9234            out.println(Integer.toHexString(System.identityHashCode(filter)));
9235        }
9236
9237        @Override
9238        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9239            return filter.provider;
9240        }
9241
9242        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9243            PackageParser.Provider provider = (PackageParser.Provider)label;
9244            out.print(prefix); out.print(
9245                    Integer.toHexString(System.identityHashCode(provider)));
9246                    out.print(' ');
9247                    provider.printComponentShortName(out);
9248            if (count > 1) {
9249                out.print(" ("); out.print(count); out.print(" filters)");
9250            }
9251            out.println();
9252        }
9253
9254        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9255                = new ArrayMap<ComponentName, PackageParser.Provider>();
9256        private int mFlags;
9257    };
9258
9259    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9260            new Comparator<ResolveInfo>() {
9261        public int compare(ResolveInfo r1, ResolveInfo r2) {
9262            int v1 = r1.priority;
9263            int v2 = r2.priority;
9264            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9265            if (v1 != v2) {
9266                return (v1 > v2) ? -1 : 1;
9267            }
9268            v1 = r1.preferredOrder;
9269            v2 = r2.preferredOrder;
9270            if (v1 != v2) {
9271                return (v1 > v2) ? -1 : 1;
9272            }
9273            if (r1.isDefault != r2.isDefault) {
9274                return r1.isDefault ? -1 : 1;
9275            }
9276            v1 = r1.match;
9277            v2 = r2.match;
9278            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9279            if (v1 != v2) {
9280                return (v1 > v2) ? -1 : 1;
9281            }
9282            if (r1.system != r2.system) {
9283                return r1.system ? -1 : 1;
9284            }
9285            return 0;
9286        }
9287    };
9288
9289    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9290            new Comparator<ProviderInfo>() {
9291        public int compare(ProviderInfo p1, ProviderInfo p2) {
9292            final int v1 = p1.initOrder;
9293            final int v2 = p2.initOrder;
9294            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9295        }
9296    };
9297
9298    final void sendPackageBroadcast(final String action, final String pkg,
9299            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9300            final int[] userIds) {
9301        mHandler.post(new Runnable() {
9302            @Override
9303            public void run() {
9304                try {
9305                    final IActivityManager am = ActivityManagerNative.getDefault();
9306                    if (am == null) return;
9307                    final int[] resolvedUserIds;
9308                    if (userIds == null) {
9309                        resolvedUserIds = am.getRunningUserIds();
9310                    } else {
9311                        resolvedUserIds = userIds;
9312                    }
9313                    for (int id : resolvedUserIds) {
9314                        final Intent intent = new Intent(action,
9315                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9316                        if (extras != null) {
9317                            intent.putExtras(extras);
9318                        }
9319                        if (targetPkg != null) {
9320                            intent.setPackage(targetPkg);
9321                        }
9322                        // Modify the UID when posting to other users
9323                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9324                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9325                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9326                            intent.putExtra(Intent.EXTRA_UID, uid);
9327                        }
9328                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9329                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9330                        if (DEBUG_BROADCASTS) {
9331                            RuntimeException here = new RuntimeException("here");
9332                            here.fillInStackTrace();
9333                            Slog.d(TAG, "Sending to user " + id + ": "
9334                                    + intent.toShortString(false, true, false, false)
9335                                    + " " + intent.getExtras(), here);
9336                        }
9337                        am.broadcastIntent(null, intent, null, finishedReceiver,
9338                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9339                                null, finishedReceiver != null, false, id);
9340                    }
9341                } catch (RemoteException ex) {
9342                }
9343            }
9344        });
9345    }
9346
9347    /**
9348     * Check if the external storage media is available. This is true if there
9349     * is a mounted external storage medium or if the external storage is
9350     * emulated.
9351     */
9352    private boolean isExternalMediaAvailable() {
9353        return mMediaMounted || Environment.isExternalStorageEmulated();
9354    }
9355
9356    @Override
9357    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9358        // writer
9359        synchronized (mPackages) {
9360            if (!isExternalMediaAvailable()) {
9361                // If the external storage is no longer mounted at this point,
9362                // the caller may not have been able to delete all of this
9363                // packages files and can not delete any more.  Bail.
9364                return null;
9365            }
9366            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9367            if (lastPackage != null) {
9368                pkgs.remove(lastPackage);
9369            }
9370            if (pkgs.size() > 0) {
9371                return pkgs.get(0);
9372            }
9373        }
9374        return null;
9375    }
9376
9377    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9378        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9379                userId, andCode ? 1 : 0, packageName);
9380        if (mSystemReady) {
9381            msg.sendToTarget();
9382        } else {
9383            if (mPostSystemReadyMessages == null) {
9384                mPostSystemReadyMessages = new ArrayList<>();
9385            }
9386            mPostSystemReadyMessages.add(msg);
9387        }
9388    }
9389
9390    void startCleaningPackages() {
9391        // reader
9392        synchronized (mPackages) {
9393            if (!isExternalMediaAvailable()) {
9394                return;
9395            }
9396            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9397                return;
9398            }
9399        }
9400        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9401        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9402        IActivityManager am = ActivityManagerNative.getDefault();
9403        if (am != null) {
9404            try {
9405                am.startService(null, intent, null, mContext.getOpPackageName(),
9406                        UserHandle.USER_OWNER);
9407            } catch (RemoteException e) {
9408            }
9409        }
9410    }
9411
9412    @Override
9413    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9414            int installFlags, String installerPackageName, VerificationParams verificationParams,
9415            String packageAbiOverride) {
9416        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9417                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9418    }
9419
9420    @Override
9421    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9422            int installFlags, String installerPackageName, VerificationParams verificationParams,
9423            String packageAbiOverride, int userId) {
9424        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9425
9426        final int callingUid = Binder.getCallingUid();
9427        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9428
9429        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9430            try {
9431                if (observer != null) {
9432                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9433                }
9434            } catch (RemoteException re) {
9435            }
9436            return;
9437        }
9438
9439        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9440            installFlags |= PackageManager.INSTALL_FROM_ADB;
9441
9442        } else {
9443            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9444            // about installerPackageName.
9445
9446            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9447            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9448        }
9449
9450        UserHandle user;
9451        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9452            user = UserHandle.ALL;
9453        } else {
9454            user = new UserHandle(userId);
9455        }
9456
9457        // Only system components can circumvent runtime permissions when installing.
9458        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9459                && mContext.checkCallingOrSelfPermission(Manifest.permission
9460                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9461            throw new SecurityException("You need the "
9462                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9463                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9464        }
9465
9466        verificationParams.setInstallerUid(callingUid);
9467
9468        final File originFile = new File(originPath);
9469        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9470
9471        final Message msg = mHandler.obtainMessage(INIT_COPY);
9472        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9473                null, verificationParams, user, packageAbiOverride, null);
9474        mHandler.sendMessage(msg);
9475    }
9476
9477    void installStage(String packageName, File stagedDir, String stagedCid,
9478            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9479            String installerPackageName, int installerUid, UserHandle user) {
9480        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9481                params.referrerUri, installerUid, null);
9482        verifParams.setInstallerUid(installerUid);
9483
9484        final OriginInfo origin;
9485        if (stagedDir != null) {
9486            origin = OriginInfo.fromStagedFile(stagedDir);
9487        } else {
9488            origin = OriginInfo.fromStagedContainer(stagedCid);
9489        }
9490
9491        final Message msg = mHandler.obtainMessage(INIT_COPY);
9492        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9493                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9494                params.grantedRuntimePermissions);
9495        mHandler.sendMessage(msg);
9496    }
9497
9498    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9499        Bundle extras = new Bundle(1);
9500        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9501
9502        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9503                packageName, extras, null, null, new int[] {userId});
9504        try {
9505            IActivityManager am = ActivityManagerNative.getDefault();
9506            final boolean isSystem =
9507                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9508            if (isSystem && am.isUserRunning(userId, false)) {
9509                // The just-installed/enabled app is bundled on the system, so presumed
9510                // to be able to run automatically without needing an explicit launch.
9511                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9512                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9513                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9514                        .setPackage(packageName);
9515                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9516                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9517            }
9518        } catch (RemoteException e) {
9519            // shouldn't happen
9520            Slog.w(TAG, "Unable to bootstrap installed package", e);
9521        }
9522    }
9523
9524    @Override
9525    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9526            int userId) {
9527        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9528        PackageSetting pkgSetting;
9529        final int uid = Binder.getCallingUid();
9530        enforceCrossUserPermission(uid, userId, true, true,
9531                "setApplicationHiddenSetting for user " + userId);
9532
9533        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9534            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9535            return false;
9536        }
9537
9538        long callingId = Binder.clearCallingIdentity();
9539        try {
9540            boolean sendAdded = false;
9541            boolean sendRemoved = false;
9542            // writer
9543            synchronized (mPackages) {
9544                pkgSetting = mSettings.mPackages.get(packageName);
9545                if (pkgSetting == null) {
9546                    return false;
9547                }
9548                if (pkgSetting.getHidden(userId) != hidden) {
9549                    pkgSetting.setHidden(hidden, userId);
9550                    mSettings.writePackageRestrictionsLPr(userId);
9551                    if (hidden) {
9552                        sendRemoved = true;
9553                    } else {
9554                        sendAdded = true;
9555                    }
9556                }
9557            }
9558            if (sendAdded) {
9559                sendPackageAddedForUser(packageName, pkgSetting, userId);
9560                return true;
9561            }
9562            if (sendRemoved) {
9563                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9564                        "hiding pkg");
9565                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9566            }
9567        } finally {
9568            Binder.restoreCallingIdentity(callingId);
9569        }
9570        return false;
9571    }
9572
9573    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9574            int userId) {
9575        final PackageRemovedInfo info = new PackageRemovedInfo();
9576        info.removedPackage = packageName;
9577        info.removedUsers = new int[] {userId};
9578        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9579        info.sendBroadcast(false, false, false);
9580    }
9581
9582    /**
9583     * Returns true if application is not found or there was an error. Otherwise it returns
9584     * the hidden state of the package for the given user.
9585     */
9586    @Override
9587    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9588        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9589        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9590                false, "getApplicationHidden for user " + userId);
9591        PackageSetting pkgSetting;
9592        long callingId = Binder.clearCallingIdentity();
9593        try {
9594            // writer
9595            synchronized (mPackages) {
9596                pkgSetting = mSettings.mPackages.get(packageName);
9597                if (pkgSetting == null) {
9598                    return true;
9599                }
9600                return pkgSetting.getHidden(userId);
9601            }
9602        } finally {
9603            Binder.restoreCallingIdentity(callingId);
9604        }
9605    }
9606
9607    /**
9608     * @hide
9609     */
9610    @Override
9611    public int installExistingPackageAsUser(String packageName, int userId) {
9612        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9613                null);
9614        PackageSetting pkgSetting;
9615        final int uid = Binder.getCallingUid();
9616        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9617                + userId);
9618        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9619            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9620        }
9621
9622        long callingId = Binder.clearCallingIdentity();
9623        try {
9624            boolean sendAdded = false;
9625
9626            // writer
9627            synchronized (mPackages) {
9628                pkgSetting = mSettings.mPackages.get(packageName);
9629                if (pkgSetting == null) {
9630                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9631                }
9632                if (!pkgSetting.getInstalled(userId)) {
9633                    pkgSetting.setInstalled(true, userId);
9634                    pkgSetting.setHidden(false, userId);
9635                    mSettings.writePackageRestrictionsLPr(userId);
9636                    sendAdded = true;
9637                }
9638            }
9639
9640            if (sendAdded) {
9641                sendPackageAddedForUser(packageName, pkgSetting, userId);
9642            }
9643        } finally {
9644            Binder.restoreCallingIdentity(callingId);
9645        }
9646
9647        return PackageManager.INSTALL_SUCCEEDED;
9648    }
9649
9650    boolean isUserRestricted(int userId, String restrictionKey) {
9651        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9652        if (restrictions.getBoolean(restrictionKey, false)) {
9653            Log.w(TAG, "User is restricted: " + restrictionKey);
9654            return true;
9655        }
9656        return false;
9657    }
9658
9659    @Override
9660    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9661        mContext.enforceCallingOrSelfPermission(
9662                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9663                "Only package verification agents can verify applications");
9664
9665        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9666        final PackageVerificationResponse response = new PackageVerificationResponse(
9667                verificationCode, Binder.getCallingUid());
9668        msg.arg1 = id;
9669        msg.obj = response;
9670        mHandler.sendMessage(msg);
9671    }
9672
9673    @Override
9674    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9675            long millisecondsToDelay) {
9676        mContext.enforceCallingOrSelfPermission(
9677                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9678                "Only package verification agents can extend verification timeouts");
9679
9680        final PackageVerificationState state = mPendingVerification.get(id);
9681        final PackageVerificationResponse response = new PackageVerificationResponse(
9682                verificationCodeAtTimeout, Binder.getCallingUid());
9683
9684        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9685            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9686        }
9687        if (millisecondsToDelay < 0) {
9688            millisecondsToDelay = 0;
9689        }
9690        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9691                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9692            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9693        }
9694
9695        if ((state != null) && !state.timeoutExtended()) {
9696            state.extendTimeout();
9697
9698            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9699            msg.arg1 = id;
9700            msg.obj = response;
9701            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9702        }
9703    }
9704
9705    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9706            int verificationCode, UserHandle user) {
9707        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9708        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9709        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9710        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9711        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9712
9713        mContext.sendBroadcastAsUser(intent, user,
9714                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9715    }
9716
9717    private ComponentName matchComponentForVerifier(String packageName,
9718            List<ResolveInfo> receivers) {
9719        ActivityInfo targetReceiver = null;
9720
9721        final int NR = receivers.size();
9722        for (int i = 0; i < NR; i++) {
9723            final ResolveInfo info = receivers.get(i);
9724            if (info.activityInfo == null) {
9725                continue;
9726            }
9727
9728            if (packageName.equals(info.activityInfo.packageName)) {
9729                targetReceiver = info.activityInfo;
9730                break;
9731            }
9732        }
9733
9734        if (targetReceiver == null) {
9735            return null;
9736        }
9737
9738        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9739    }
9740
9741    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9742            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9743        if (pkgInfo.verifiers.length == 0) {
9744            return null;
9745        }
9746
9747        final int N = pkgInfo.verifiers.length;
9748        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9749        for (int i = 0; i < N; i++) {
9750            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9751
9752            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9753                    receivers);
9754            if (comp == null) {
9755                continue;
9756            }
9757
9758            final int verifierUid = getUidForVerifier(verifierInfo);
9759            if (verifierUid == -1) {
9760                continue;
9761            }
9762
9763            if (DEBUG_VERIFY) {
9764                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9765                        + " with the correct signature");
9766            }
9767            sufficientVerifiers.add(comp);
9768            verificationState.addSufficientVerifier(verifierUid);
9769        }
9770
9771        return sufficientVerifiers;
9772    }
9773
9774    private int getUidForVerifier(VerifierInfo verifierInfo) {
9775        synchronized (mPackages) {
9776            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9777            if (pkg == null) {
9778                return -1;
9779            } else if (pkg.mSignatures.length != 1) {
9780                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9781                        + " has more than one signature; ignoring");
9782                return -1;
9783            }
9784
9785            /*
9786             * If the public key of the package's signature does not match
9787             * our expected public key, then this is a different package and
9788             * we should skip.
9789             */
9790
9791            final byte[] expectedPublicKey;
9792            try {
9793                final Signature verifierSig = pkg.mSignatures[0];
9794                final PublicKey publicKey = verifierSig.getPublicKey();
9795                expectedPublicKey = publicKey.getEncoded();
9796            } catch (CertificateException e) {
9797                return -1;
9798            }
9799
9800            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9801
9802            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9803                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9804                        + " does not have the expected public key; ignoring");
9805                return -1;
9806            }
9807
9808            return pkg.applicationInfo.uid;
9809        }
9810    }
9811
9812    @Override
9813    public void finishPackageInstall(int token) {
9814        enforceSystemOrRoot("Only the system is allowed to finish installs");
9815
9816        if (DEBUG_INSTALL) {
9817            Slog.v(TAG, "BM finishing package install for " + token);
9818        }
9819
9820        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9821        mHandler.sendMessage(msg);
9822    }
9823
9824    /**
9825     * Get the verification agent timeout.
9826     *
9827     * @return verification timeout in milliseconds
9828     */
9829    private long getVerificationTimeout() {
9830        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9831                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9832                DEFAULT_VERIFICATION_TIMEOUT);
9833    }
9834
9835    /**
9836     * Get the default verification agent response code.
9837     *
9838     * @return default verification response code
9839     */
9840    private int getDefaultVerificationResponse() {
9841        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9842                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9843                DEFAULT_VERIFICATION_RESPONSE);
9844    }
9845
9846    /**
9847     * Check whether or not package verification has been enabled.
9848     *
9849     * @return true if verification should be performed
9850     */
9851    private boolean isVerificationEnabled(int userId, int installFlags) {
9852        if (!DEFAULT_VERIFY_ENABLE) {
9853            return false;
9854        }
9855
9856        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9857
9858        // Check if installing from ADB
9859        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9860            // Do not run verification in a test harness environment
9861            if (ActivityManager.isRunningInTestHarness()) {
9862                return false;
9863            }
9864            if (ensureVerifyAppsEnabled) {
9865                return true;
9866            }
9867            // Check if the developer does not want package verification for ADB installs
9868            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9869                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9870                return false;
9871            }
9872        }
9873
9874        if (ensureVerifyAppsEnabled) {
9875            return true;
9876        }
9877
9878        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9879                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9880    }
9881
9882    @Override
9883    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9884            throws RemoteException {
9885        mContext.enforceCallingOrSelfPermission(
9886                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9887                "Only intentfilter verification agents can verify applications");
9888
9889        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9890        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9891                Binder.getCallingUid(), verificationCode, failedDomains);
9892        msg.arg1 = id;
9893        msg.obj = response;
9894        mHandler.sendMessage(msg);
9895    }
9896
9897    @Override
9898    public int getIntentVerificationStatus(String packageName, int userId) {
9899        synchronized (mPackages) {
9900            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9901        }
9902    }
9903
9904    @Override
9905    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9906        mContext.enforceCallingOrSelfPermission(
9907                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9908
9909        boolean result = false;
9910        synchronized (mPackages) {
9911            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9912        }
9913        if (result) {
9914            scheduleWritePackageRestrictionsLocked(userId);
9915        }
9916        return result;
9917    }
9918
9919    @Override
9920    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9921        synchronized (mPackages) {
9922            return mSettings.getIntentFilterVerificationsLPr(packageName);
9923        }
9924    }
9925
9926    @Override
9927    public List<IntentFilter> getAllIntentFilters(String packageName) {
9928        if (TextUtils.isEmpty(packageName)) {
9929            return Collections.<IntentFilter>emptyList();
9930        }
9931        synchronized (mPackages) {
9932            PackageParser.Package pkg = mPackages.get(packageName);
9933            if (pkg == null || pkg.activities == null) {
9934                return Collections.<IntentFilter>emptyList();
9935            }
9936            final int count = pkg.activities.size();
9937            ArrayList<IntentFilter> result = new ArrayList<>();
9938            for (int n=0; n<count; n++) {
9939                PackageParser.Activity activity = pkg.activities.get(n);
9940                if (activity.intents != null || activity.intents.size() > 0) {
9941                    result.addAll(activity.intents);
9942                }
9943            }
9944            return result;
9945        }
9946    }
9947
9948    @Override
9949    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9950        mContext.enforceCallingOrSelfPermission(
9951                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9952
9953        synchronized (mPackages) {
9954            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9955            if (packageName != null) {
9956                result |= updateIntentVerificationStatus(packageName,
9957                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9958                        userId);
9959                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9960                        packageName, userId);
9961            }
9962            return result;
9963        }
9964    }
9965
9966    @Override
9967    public String getDefaultBrowserPackageName(int userId) {
9968        synchronized (mPackages) {
9969            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9970        }
9971    }
9972
9973    /**
9974     * Get the "allow unknown sources" setting.
9975     *
9976     * @return the current "allow unknown sources" setting
9977     */
9978    private int getUnknownSourcesSettings() {
9979        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9980                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9981                -1);
9982    }
9983
9984    @Override
9985    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9986        final int uid = Binder.getCallingUid();
9987        // writer
9988        synchronized (mPackages) {
9989            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9990            if (targetPackageSetting == null) {
9991                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9992            }
9993
9994            PackageSetting installerPackageSetting;
9995            if (installerPackageName != null) {
9996                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9997                if (installerPackageSetting == null) {
9998                    throw new IllegalArgumentException("Unknown installer package: "
9999                            + installerPackageName);
10000                }
10001            } else {
10002                installerPackageSetting = null;
10003            }
10004
10005            Signature[] callerSignature;
10006            Object obj = mSettings.getUserIdLPr(uid);
10007            if (obj != null) {
10008                if (obj instanceof SharedUserSetting) {
10009                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10010                } else if (obj instanceof PackageSetting) {
10011                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10012                } else {
10013                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10014                }
10015            } else {
10016                throw new SecurityException("Unknown calling uid " + uid);
10017            }
10018
10019            // Verify: can't set installerPackageName to a package that is
10020            // not signed with the same cert as the caller.
10021            if (installerPackageSetting != null) {
10022                if (compareSignatures(callerSignature,
10023                        installerPackageSetting.signatures.mSignatures)
10024                        != PackageManager.SIGNATURE_MATCH) {
10025                    throw new SecurityException(
10026                            "Caller does not have same cert as new installer package "
10027                            + installerPackageName);
10028                }
10029            }
10030
10031            // Verify: if target already has an installer package, it must
10032            // be signed with the same cert as the caller.
10033            if (targetPackageSetting.installerPackageName != null) {
10034                PackageSetting setting = mSettings.mPackages.get(
10035                        targetPackageSetting.installerPackageName);
10036                // If the currently set package isn't valid, then it's always
10037                // okay to change it.
10038                if (setting != null) {
10039                    if (compareSignatures(callerSignature,
10040                            setting.signatures.mSignatures)
10041                            != PackageManager.SIGNATURE_MATCH) {
10042                        throw new SecurityException(
10043                                "Caller does not have same cert as old installer package "
10044                                + targetPackageSetting.installerPackageName);
10045                    }
10046                }
10047            }
10048
10049            // Okay!
10050            targetPackageSetting.installerPackageName = installerPackageName;
10051            scheduleWriteSettingsLocked();
10052        }
10053    }
10054
10055    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10056        // Queue up an async operation since the package installation may take a little while.
10057        mHandler.post(new Runnable() {
10058            public void run() {
10059                mHandler.removeCallbacks(this);
10060                 // Result object to be returned
10061                PackageInstalledInfo res = new PackageInstalledInfo();
10062                res.returnCode = currentStatus;
10063                res.uid = -1;
10064                res.pkg = null;
10065                res.removedInfo = new PackageRemovedInfo();
10066                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10067                    args.doPreInstall(res.returnCode);
10068                    synchronized (mInstallLock) {
10069                        installPackageLI(args, res);
10070                    }
10071                    args.doPostInstall(res.returnCode, res.uid);
10072                }
10073
10074                // A restore should be performed at this point if (a) the install
10075                // succeeded, (b) the operation is not an update, and (c) the new
10076                // package has not opted out of backup participation.
10077                final boolean update = res.removedInfo.removedPackage != null;
10078                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10079                boolean doRestore = !update
10080                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10081
10082                // Set up the post-install work request bookkeeping.  This will be used
10083                // and cleaned up by the post-install event handling regardless of whether
10084                // there's a restore pass performed.  Token values are >= 1.
10085                int token;
10086                if (mNextInstallToken < 0) mNextInstallToken = 1;
10087                token = mNextInstallToken++;
10088
10089                PostInstallData data = new PostInstallData(args, res);
10090                mRunningInstalls.put(token, data);
10091                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10092
10093                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10094                    // Pass responsibility to the Backup Manager.  It will perform a
10095                    // restore if appropriate, then pass responsibility back to the
10096                    // Package Manager to run the post-install observer callbacks
10097                    // and broadcasts.
10098                    IBackupManager bm = IBackupManager.Stub.asInterface(
10099                            ServiceManager.getService(Context.BACKUP_SERVICE));
10100                    if (bm != null) {
10101                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10102                                + " to BM for possible restore");
10103                        try {
10104                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10105                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10106                            } else {
10107                                doRestore = false;
10108                            }
10109                        } catch (RemoteException e) {
10110                            // can't happen; the backup manager is local
10111                        } catch (Exception e) {
10112                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10113                            doRestore = false;
10114                        }
10115                    } else {
10116                        Slog.e(TAG, "Backup Manager not found!");
10117                        doRestore = false;
10118                    }
10119                }
10120
10121                if (!doRestore) {
10122                    // No restore possible, or the Backup Manager was mysteriously not
10123                    // available -- just fire the post-install work request directly.
10124                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10125                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10126                    mHandler.sendMessage(msg);
10127                }
10128            }
10129        });
10130    }
10131
10132    private abstract class HandlerParams {
10133        private static final int MAX_RETRIES = 4;
10134
10135        /**
10136         * Number of times startCopy() has been attempted and had a non-fatal
10137         * error.
10138         */
10139        private int mRetries = 0;
10140
10141        /** User handle for the user requesting the information or installation. */
10142        private final UserHandle mUser;
10143
10144        HandlerParams(UserHandle user) {
10145            mUser = user;
10146        }
10147
10148        UserHandle getUser() {
10149            return mUser;
10150        }
10151
10152        final boolean startCopy() {
10153            boolean res;
10154            try {
10155                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10156
10157                if (++mRetries > MAX_RETRIES) {
10158                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10159                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10160                    handleServiceError();
10161                    return false;
10162                } else {
10163                    handleStartCopy();
10164                    res = true;
10165                }
10166            } catch (RemoteException e) {
10167                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10168                mHandler.sendEmptyMessage(MCS_RECONNECT);
10169                res = false;
10170            }
10171            handleReturnCode();
10172            return res;
10173        }
10174
10175        final void serviceError() {
10176            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10177            handleServiceError();
10178            handleReturnCode();
10179        }
10180
10181        abstract void handleStartCopy() throws RemoteException;
10182        abstract void handleServiceError();
10183        abstract void handleReturnCode();
10184    }
10185
10186    class MeasureParams extends HandlerParams {
10187        private final PackageStats mStats;
10188        private boolean mSuccess;
10189
10190        private final IPackageStatsObserver mObserver;
10191
10192        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10193            super(new UserHandle(stats.userHandle));
10194            mObserver = observer;
10195            mStats = stats;
10196        }
10197
10198        @Override
10199        public String toString() {
10200            return "MeasureParams{"
10201                + Integer.toHexString(System.identityHashCode(this))
10202                + " " + mStats.packageName + "}";
10203        }
10204
10205        @Override
10206        void handleStartCopy() throws RemoteException {
10207            synchronized (mInstallLock) {
10208                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10209            }
10210
10211            if (mSuccess) {
10212                final boolean mounted;
10213                if (Environment.isExternalStorageEmulated()) {
10214                    mounted = true;
10215                } else {
10216                    final String status = Environment.getExternalStorageState();
10217                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10218                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10219                }
10220
10221                if (mounted) {
10222                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10223
10224                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10225                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10226
10227                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10228                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10229
10230                    // Always subtract cache size, since it's a subdirectory
10231                    mStats.externalDataSize -= mStats.externalCacheSize;
10232
10233                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10234                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10235
10236                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10237                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10238                }
10239            }
10240        }
10241
10242        @Override
10243        void handleReturnCode() {
10244            if (mObserver != null) {
10245                try {
10246                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10247                } catch (RemoteException e) {
10248                    Slog.i(TAG, "Observer no longer exists.");
10249                }
10250            }
10251        }
10252
10253        @Override
10254        void handleServiceError() {
10255            Slog.e(TAG, "Could not measure application " + mStats.packageName
10256                            + " external storage");
10257        }
10258    }
10259
10260    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10261            throws RemoteException {
10262        long result = 0;
10263        for (File path : paths) {
10264            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10265        }
10266        return result;
10267    }
10268
10269    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10270        for (File path : paths) {
10271            try {
10272                mcs.clearDirectory(path.getAbsolutePath());
10273            } catch (RemoteException e) {
10274            }
10275        }
10276    }
10277
10278    static class OriginInfo {
10279        /**
10280         * Location where install is coming from, before it has been
10281         * copied/renamed into place. This could be a single monolithic APK
10282         * file, or a cluster directory. This location may be untrusted.
10283         */
10284        final File file;
10285        final String cid;
10286
10287        /**
10288         * Flag indicating that {@link #file} or {@link #cid} has already been
10289         * staged, meaning downstream users don't need to defensively copy the
10290         * contents.
10291         */
10292        final boolean staged;
10293
10294        /**
10295         * Flag indicating that {@link #file} or {@link #cid} is an already
10296         * installed app that is being moved.
10297         */
10298        final boolean existing;
10299
10300        final String resolvedPath;
10301        final File resolvedFile;
10302
10303        static OriginInfo fromNothing() {
10304            return new OriginInfo(null, null, false, false);
10305        }
10306
10307        static OriginInfo fromUntrustedFile(File file) {
10308            return new OriginInfo(file, null, false, false);
10309        }
10310
10311        static OriginInfo fromExistingFile(File file) {
10312            return new OriginInfo(file, null, false, true);
10313        }
10314
10315        static OriginInfo fromStagedFile(File file) {
10316            return new OriginInfo(file, null, true, false);
10317        }
10318
10319        static OriginInfo fromStagedContainer(String cid) {
10320            return new OriginInfo(null, cid, true, false);
10321        }
10322
10323        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10324            this.file = file;
10325            this.cid = cid;
10326            this.staged = staged;
10327            this.existing = existing;
10328
10329            if (cid != null) {
10330                resolvedPath = PackageHelper.getSdDir(cid);
10331                resolvedFile = new File(resolvedPath);
10332            } else if (file != null) {
10333                resolvedPath = file.getAbsolutePath();
10334                resolvedFile = file;
10335            } else {
10336                resolvedPath = null;
10337                resolvedFile = null;
10338            }
10339        }
10340    }
10341
10342    class MoveInfo {
10343        final int moveId;
10344        final String fromUuid;
10345        final String toUuid;
10346        final String packageName;
10347        final String dataAppName;
10348        final int appId;
10349        final String seinfo;
10350
10351        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10352                String dataAppName, int appId, String seinfo) {
10353            this.moveId = moveId;
10354            this.fromUuid = fromUuid;
10355            this.toUuid = toUuid;
10356            this.packageName = packageName;
10357            this.dataAppName = dataAppName;
10358            this.appId = appId;
10359            this.seinfo = seinfo;
10360        }
10361    }
10362
10363    class InstallParams extends HandlerParams {
10364        final OriginInfo origin;
10365        final MoveInfo move;
10366        final IPackageInstallObserver2 observer;
10367        int installFlags;
10368        final String installerPackageName;
10369        final String volumeUuid;
10370        final VerificationParams verificationParams;
10371        private InstallArgs mArgs;
10372        private int mRet;
10373        final String packageAbiOverride;
10374        final String[] grantedRuntimePermissions;
10375
10376
10377        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10378                int installFlags, String installerPackageName, String volumeUuid,
10379                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10380                String[] grantedPermissions) {
10381            super(user);
10382            this.origin = origin;
10383            this.move = move;
10384            this.observer = observer;
10385            this.installFlags = installFlags;
10386            this.installerPackageName = installerPackageName;
10387            this.volumeUuid = volumeUuid;
10388            this.verificationParams = verificationParams;
10389            this.packageAbiOverride = packageAbiOverride;
10390            this.grantedRuntimePermissions = grantedPermissions;
10391        }
10392
10393        @Override
10394        public String toString() {
10395            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10396                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10397        }
10398
10399        public ManifestDigest getManifestDigest() {
10400            if (verificationParams == null) {
10401                return null;
10402            }
10403            return verificationParams.getManifestDigest();
10404        }
10405
10406        private int installLocationPolicy(PackageInfoLite pkgLite) {
10407            String packageName = pkgLite.packageName;
10408            int installLocation = pkgLite.installLocation;
10409            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10410            // reader
10411            synchronized (mPackages) {
10412                PackageParser.Package pkg = mPackages.get(packageName);
10413                if (pkg != null) {
10414                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10415                        // Check for downgrading.
10416                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10417                            try {
10418                                checkDowngrade(pkg, pkgLite);
10419                            } catch (PackageManagerException e) {
10420                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10421                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10422                            }
10423                        }
10424                        // Check for updated system application.
10425                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10426                            if (onSd) {
10427                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10428                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10429                            }
10430                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10431                        } else {
10432                            if (onSd) {
10433                                // Install flag overrides everything.
10434                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10435                            }
10436                            // If current upgrade specifies particular preference
10437                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10438                                // Application explicitly specified internal.
10439                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10440                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10441                                // App explictly prefers external. Let policy decide
10442                            } else {
10443                                // Prefer previous location
10444                                if (isExternal(pkg)) {
10445                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10446                                }
10447                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10448                            }
10449                        }
10450                    } else {
10451                        // Invalid install. Return error code
10452                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10453                    }
10454                }
10455            }
10456            // All the special cases have been taken care of.
10457            // Return result based on recommended install location.
10458            if (onSd) {
10459                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10460            }
10461            return pkgLite.recommendedInstallLocation;
10462        }
10463
10464        /*
10465         * Invoke remote method to get package information and install
10466         * location values. Override install location based on default
10467         * policy if needed and then create install arguments based
10468         * on the install location.
10469         */
10470        public void handleStartCopy() throws RemoteException {
10471            int ret = PackageManager.INSTALL_SUCCEEDED;
10472
10473            // If we're already staged, we've firmly committed to an install location
10474            if (origin.staged) {
10475                if (origin.file != null) {
10476                    installFlags |= PackageManager.INSTALL_INTERNAL;
10477                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10478                } else if (origin.cid != null) {
10479                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10480                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10481                } else {
10482                    throw new IllegalStateException("Invalid stage location");
10483                }
10484            }
10485
10486            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10487            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10488
10489            PackageInfoLite pkgLite = null;
10490
10491            if (onInt && onSd) {
10492                // Check if both bits are set.
10493                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10494                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10495            } else {
10496                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10497                        packageAbiOverride);
10498
10499                /*
10500                 * If we have too little free space, try to free cache
10501                 * before giving up.
10502                 */
10503                if (!origin.staged && pkgLite.recommendedInstallLocation
10504                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10505                    // TODO: focus freeing disk space on the target device
10506                    final StorageManager storage = StorageManager.from(mContext);
10507                    final long lowThreshold = storage.getStorageLowBytes(
10508                            Environment.getDataDirectory());
10509
10510                    final long sizeBytes = mContainerService.calculateInstalledSize(
10511                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10512
10513                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10514                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10515                                installFlags, packageAbiOverride);
10516                    }
10517
10518                    /*
10519                     * The cache free must have deleted the file we
10520                     * downloaded to install.
10521                     *
10522                     * TODO: fix the "freeCache" call to not delete
10523                     *       the file we care about.
10524                     */
10525                    if (pkgLite.recommendedInstallLocation
10526                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10527                        pkgLite.recommendedInstallLocation
10528                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10529                    }
10530                }
10531            }
10532
10533            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10534                int loc = pkgLite.recommendedInstallLocation;
10535                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10536                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10537                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10538                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10539                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10540                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10541                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10542                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10543                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10544                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10545                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10546                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10547                } else {
10548                    // Override with defaults if needed.
10549                    loc = installLocationPolicy(pkgLite);
10550                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10551                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10552                    } else if (!onSd && !onInt) {
10553                        // Override install location with flags
10554                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10555                            // Set the flag to install on external media.
10556                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10557                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10558                        } else {
10559                            // Make sure the flag for installing on external
10560                            // media is unset
10561                            installFlags |= PackageManager.INSTALL_INTERNAL;
10562                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10563                        }
10564                    }
10565                }
10566            }
10567
10568            final InstallArgs args = createInstallArgs(this);
10569            mArgs = args;
10570
10571            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10572                 /*
10573                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10574                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10575                 */
10576                int userIdentifier = getUser().getIdentifier();
10577                if (userIdentifier == UserHandle.USER_ALL
10578                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10579                    userIdentifier = UserHandle.USER_OWNER;
10580                }
10581
10582                /*
10583                 * Determine if we have any installed package verifiers. If we
10584                 * do, then we'll defer to them to verify the packages.
10585                 */
10586                final int requiredUid = mRequiredVerifierPackage == null ? -1
10587                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10588                if (!origin.existing && requiredUid != -1
10589                        && isVerificationEnabled(userIdentifier, installFlags)) {
10590                    final Intent verification = new Intent(
10591                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10592                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10593                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10594                            PACKAGE_MIME_TYPE);
10595                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10596
10597                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10598                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10599                            0 /* TODO: Which userId? */);
10600
10601                    if (DEBUG_VERIFY) {
10602                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10603                                + verification.toString() + " with " + pkgLite.verifiers.length
10604                                + " optional verifiers");
10605                    }
10606
10607                    final int verificationId = mPendingVerificationToken++;
10608
10609                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10610
10611                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10612                            installerPackageName);
10613
10614                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10615                            installFlags);
10616
10617                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10618                            pkgLite.packageName);
10619
10620                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10621                            pkgLite.versionCode);
10622
10623                    if (verificationParams != null) {
10624                        if (verificationParams.getVerificationURI() != null) {
10625                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10626                                 verificationParams.getVerificationURI());
10627                        }
10628                        if (verificationParams.getOriginatingURI() != null) {
10629                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10630                                  verificationParams.getOriginatingURI());
10631                        }
10632                        if (verificationParams.getReferrer() != null) {
10633                            verification.putExtra(Intent.EXTRA_REFERRER,
10634                                  verificationParams.getReferrer());
10635                        }
10636                        if (verificationParams.getOriginatingUid() >= 0) {
10637                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10638                                  verificationParams.getOriginatingUid());
10639                        }
10640                        if (verificationParams.getInstallerUid() >= 0) {
10641                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10642                                  verificationParams.getInstallerUid());
10643                        }
10644                    }
10645
10646                    final PackageVerificationState verificationState = new PackageVerificationState(
10647                            requiredUid, args);
10648
10649                    mPendingVerification.append(verificationId, verificationState);
10650
10651                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10652                            receivers, verificationState);
10653
10654                    // Apps installed for "all" users use the device owner to verify the app
10655                    UserHandle verifierUser = getUser();
10656                    if (verifierUser == UserHandle.ALL) {
10657                        verifierUser = UserHandle.OWNER;
10658                    }
10659
10660                    /*
10661                     * If any sufficient verifiers were listed in the package
10662                     * manifest, attempt to ask them.
10663                     */
10664                    if (sufficientVerifiers != null) {
10665                        final int N = sufficientVerifiers.size();
10666                        if (N == 0) {
10667                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10668                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10669                        } else {
10670                            for (int i = 0; i < N; i++) {
10671                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10672
10673                                final Intent sufficientIntent = new Intent(verification);
10674                                sufficientIntent.setComponent(verifierComponent);
10675                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10676                            }
10677                        }
10678                    }
10679
10680                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10681                            mRequiredVerifierPackage, receivers);
10682                    if (ret == PackageManager.INSTALL_SUCCEEDED
10683                            && mRequiredVerifierPackage != null) {
10684                        /*
10685                         * Send the intent to the required verification agent,
10686                         * but only start the verification timeout after the
10687                         * target BroadcastReceivers have run.
10688                         */
10689                        verification.setComponent(requiredVerifierComponent);
10690                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10691                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10692                                new BroadcastReceiver() {
10693                                    @Override
10694                                    public void onReceive(Context context, Intent intent) {
10695                                        final Message msg = mHandler
10696                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10697                                        msg.arg1 = verificationId;
10698                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10699                                    }
10700                                }, null, 0, null, null);
10701
10702                        /*
10703                         * We don't want the copy to proceed until verification
10704                         * succeeds, so null out this field.
10705                         */
10706                        mArgs = null;
10707                    }
10708                } else {
10709                    /*
10710                     * No package verification is enabled, so immediately start
10711                     * the remote call to initiate copy using temporary file.
10712                     */
10713                    ret = args.copyApk(mContainerService, true);
10714                }
10715            }
10716
10717            mRet = ret;
10718        }
10719
10720        @Override
10721        void handleReturnCode() {
10722            // If mArgs is null, then MCS couldn't be reached. When it
10723            // reconnects, it will try again to install. At that point, this
10724            // will succeed.
10725            if (mArgs != null) {
10726                processPendingInstall(mArgs, mRet);
10727            }
10728        }
10729
10730        @Override
10731        void handleServiceError() {
10732            mArgs = createInstallArgs(this);
10733            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10734        }
10735
10736        public boolean isForwardLocked() {
10737            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10738        }
10739    }
10740
10741    /**
10742     * Used during creation of InstallArgs
10743     *
10744     * @param installFlags package installation flags
10745     * @return true if should be installed on external storage
10746     */
10747    private static boolean installOnExternalAsec(int installFlags) {
10748        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10749            return false;
10750        }
10751        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10752            return true;
10753        }
10754        return false;
10755    }
10756
10757    /**
10758     * Used during creation of InstallArgs
10759     *
10760     * @param installFlags package installation flags
10761     * @return true if should be installed as forward locked
10762     */
10763    private static boolean installForwardLocked(int installFlags) {
10764        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10765    }
10766
10767    private InstallArgs createInstallArgs(InstallParams params) {
10768        if (params.move != null) {
10769            return new MoveInstallArgs(params);
10770        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10771            return new AsecInstallArgs(params);
10772        } else {
10773            return new FileInstallArgs(params);
10774        }
10775    }
10776
10777    /**
10778     * Create args that describe an existing installed package. Typically used
10779     * when cleaning up old installs, or used as a move source.
10780     */
10781    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10782            String resourcePath, String[] instructionSets) {
10783        final boolean isInAsec;
10784        if (installOnExternalAsec(installFlags)) {
10785            /* Apps on SD card are always in ASEC containers. */
10786            isInAsec = true;
10787        } else if (installForwardLocked(installFlags)
10788                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10789            /*
10790             * Forward-locked apps are only in ASEC containers if they're the
10791             * new style
10792             */
10793            isInAsec = true;
10794        } else {
10795            isInAsec = false;
10796        }
10797
10798        if (isInAsec) {
10799            return new AsecInstallArgs(codePath, instructionSets,
10800                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10801        } else {
10802            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10803        }
10804    }
10805
10806    static abstract class InstallArgs {
10807        /** @see InstallParams#origin */
10808        final OriginInfo origin;
10809        /** @see InstallParams#move */
10810        final MoveInfo move;
10811
10812        final IPackageInstallObserver2 observer;
10813        // Always refers to PackageManager flags only
10814        final int installFlags;
10815        final String installerPackageName;
10816        final String volumeUuid;
10817        final ManifestDigest manifestDigest;
10818        final UserHandle user;
10819        final String abiOverride;
10820        final String[] installGrantPermissions;
10821
10822        // The list of instruction sets supported by this app. This is currently
10823        // only used during the rmdex() phase to clean up resources. We can get rid of this
10824        // if we move dex files under the common app path.
10825        /* nullable */ String[] instructionSets;
10826
10827        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10828                int installFlags, String installerPackageName, String volumeUuid,
10829                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10830                String abiOverride, String[] installGrantPermissions) {
10831            this.origin = origin;
10832            this.move = move;
10833            this.installFlags = installFlags;
10834            this.observer = observer;
10835            this.installerPackageName = installerPackageName;
10836            this.volumeUuid = volumeUuid;
10837            this.manifestDigest = manifestDigest;
10838            this.user = user;
10839            this.instructionSets = instructionSets;
10840            this.abiOverride = abiOverride;
10841            this.installGrantPermissions = installGrantPermissions;
10842        }
10843
10844        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10845        abstract int doPreInstall(int status);
10846
10847        /**
10848         * Rename package into final resting place. All paths on the given
10849         * scanned package should be updated to reflect the rename.
10850         */
10851        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10852        abstract int doPostInstall(int status, int uid);
10853
10854        /** @see PackageSettingBase#codePathString */
10855        abstract String getCodePath();
10856        /** @see PackageSettingBase#resourcePathString */
10857        abstract String getResourcePath();
10858
10859        // Need installer lock especially for dex file removal.
10860        abstract void cleanUpResourcesLI();
10861        abstract boolean doPostDeleteLI(boolean delete);
10862
10863        /**
10864         * Called before the source arguments are copied. This is used mostly
10865         * for MoveParams when it needs to read the source file to put it in the
10866         * destination.
10867         */
10868        int doPreCopy() {
10869            return PackageManager.INSTALL_SUCCEEDED;
10870        }
10871
10872        /**
10873         * Called after the source arguments are copied. This is used mostly for
10874         * MoveParams when it needs to read the source file to put it in the
10875         * destination.
10876         *
10877         * @return
10878         */
10879        int doPostCopy(int uid) {
10880            return PackageManager.INSTALL_SUCCEEDED;
10881        }
10882
10883        protected boolean isFwdLocked() {
10884            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10885        }
10886
10887        protected boolean isExternalAsec() {
10888            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10889        }
10890
10891        UserHandle getUser() {
10892            return user;
10893        }
10894    }
10895
10896    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10897        if (!allCodePaths.isEmpty()) {
10898            if (instructionSets == null) {
10899                throw new IllegalStateException("instructionSet == null");
10900            }
10901            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10902            for (String codePath : allCodePaths) {
10903                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10904                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10905                    if (retCode < 0) {
10906                        Slog.w(TAG, "Couldn't remove dex file for package: "
10907                                + " at location " + codePath + ", retcode=" + retCode);
10908                        // we don't consider this to be a failure of the core package deletion
10909                    }
10910                }
10911            }
10912        }
10913    }
10914
10915    /**
10916     * Logic to handle installation of non-ASEC applications, including copying
10917     * and renaming logic.
10918     */
10919    class FileInstallArgs extends InstallArgs {
10920        private File codeFile;
10921        private File resourceFile;
10922
10923        // Example topology:
10924        // /data/app/com.example/base.apk
10925        // /data/app/com.example/split_foo.apk
10926        // /data/app/com.example/lib/arm/libfoo.so
10927        // /data/app/com.example/lib/arm64/libfoo.so
10928        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10929
10930        /** New install */
10931        FileInstallArgs(InstallParams params) {
10932            super(params.origin, params.move, params.observer, params.installFlags,
10933                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10934                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10935                    params.grantedRuntimePermissions);
10936            if (isFwdLocked()) {
10937                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10938            }
10939        }
10940
10941        /** Existing install */
10942        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10943            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10944                    null, null);
10945            this.codeFile = (codePath != null) ? new File(codePath) : null;
10946            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10947        }
10948
10949        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10950            if (origin.staged) {
10951                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10952                codeFile = origin.file;
10953                resourceFile = origin.file;
10954                return PackageManager.INSTALL_SUCCEEDED;
10955            }
10956
10957            try {
10958                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10959                codeFile = tempDir;
10960                resourceFile = tempDir;
10961            } catch (IOException e) {
10962                Slog.w(TAG, "Failed to create copy file: " + e);
10963                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10964            }
10965
10966            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10967                @Override
10968                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10969                    if (!FileUtils.isValidExtFilename(name)) {
10970                        throw new IllegalArgumentException("Invalid filename: " + name);
10971                    }
10972                    try {
10973                        final File file = new File(codeFile, name);
10974                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10975                                O_RDWR | O_CREAT, 0644);
10976                        Os.chmod(file.getAbsolutePath(), 0644);
10977                        return new ParcelFileDescriptor(fd);
10978                    } catch (ErrnoException e) {
10979                        throw new RemoteException("Failed to open: " + e.getMessage());
10980                    }
10981                }
10982            };
10983
10984            int ret = PackageManager.INSTALL_SUCCEEDED;
10985            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10986            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10987                Slog.e(TAG, "Failed to copy package");
10988                return ret;
10989            }
10990
10991            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10992            NativeLibraryHelper.Handle handle = null;
10993            try {
10994                handle = NativeLibraryHelper.Handle.create(codeFile);
10995                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10996                        abiOverride);
10997            } catch (IOException e) {
10998                Slog.e(TAG, "Copying native libraries failed", e);
10999                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11000            } finally {
11001                IoUtils.closeQuietly(handle);
11002            }
11003
11004            return ret;
11005        }
11006
11007        int doPreInstall(int status) {
11008            if (status != PackageManager.INSTALL_SUCCEEDED) {
11009                cleanUp();
11010            }
11011            return status;
11012        }
11013
11014        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11015            if (status != PackageManager.INSTALL_SUCCEEDED) {
11016                cleanUp();
11017                return false;
11018            }
11019
11020            final File targetDir = codeFile.getParentFile();
11021            final File beforeCodeFile = codeFile;
11022            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11023
11024            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11025            try {
11026                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11027            } catch (ErrnoException e) {
11028                Slog.w(TAG, "Failed to rename", e);
11029                return false;
11030            }
11031
11032            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11033                Slog.w(TAG, "Failed to restorecon");
11034                return false;
11035            }
11036
11037            // Reflect the rename internally
11038            codeFile = afterCodeFile;
11039            resourceFile = afterCodeFile;
11040
11041            // Reflect the rename in scanned details
11042            pkg.codePath = afterCodeFile.getAbsolutePath();
11043            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11044                    pkg.baseCodePath);
11045            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11046                    pkg.splitCodePaths);
11047
11048            // Reflect the rename in app info
11049            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11050            pkg.applicationInfo.setCodePath(pkg.codePath);
11051            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11052            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11053            pkg.applicationInfo.setResourcePath(pkg.codePath);
11054            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11055            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11056
11057            return true;
11058        }
11059
11060        int doPostInstall(int status, int uid) {
11061            if (status != PackageManager.INSTALL_SUCCEEDED) {
11062                cleanUp();
11063            }
11064            return status;
11065        }
11066
11067        @Override
11068        String getCodePath() {
11069            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11070        }
11071
11072        @Override
11073        String getResourcePath() {
11074            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11075        }
11076
11077        private boolean cleanUp() {
11078            if (codeFile == null || !codeFile.exists()) {
11079                return false;
11080            }
11081
11082            if (codeFile.isDirectory()) {
11083                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11084            } else {
11085                codeFile.delete();
11086            }
11087
11088            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11089                resourceFile.delete();
11090            }
11091
11092            return true;
11093        }
11094
11095        void cleanUpResourcesLI() {
11096            // Try enumerating all code paths before deleting
11097            List<String> allCodePaths = Collections.EMPTY_LIST;
11098            if (codeFile != null && codeFile.exists()) {
11099                try {
11100                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11101                    allCodePaths = pkg.getAllCodePaths();
11102                } catch (PackageParserException e) {
11103                    // Ignored; we tried our best
11104                }
11105            }
11106
11107            cleanUp();
11108            removeDexFiles(allCodePaths, instructionSets);
11109        }
11110
11111        boolean doPostDeleteLI(boolean delete) {
11112            // XXX err, shouldn't we respect the delete flag?
11113            cleanUpResourcesLI();
11114            return true;
11115        }
11116    }
11117
11118    private boolean isAsecExternal(String cid) {
11119        final String asecPath = PackageHelper.getSdFilesystem(cid);
11120        return !asecPath.startsWith(mAsecInternalPath);
11121    }
11122
11123    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11124            PackageManagerException {
11125        if (copyRet < 0) {
11126            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11127                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11128                throw new PackageManagerException(copyRet, message);
11129            }
11130        }
11131    }
11132
11133    /**
11134     * Extract the MountService "container ID" from the full code path of an
11135     * .apk.
11136     */
11137    static String cidFromCodePath(String fullCodePath) {
11138        int eidx = fullCodePath.lastIndexOf("/");
11139        String subStr1 = fullCodePath.substring(0, eidx);
11140        int sidx = subStr1.lastIndexOf("/");
11141        return subStr1.substring(sidx+1, eidx);
11142    }
11143
11144    /**
11145     * Logic to handle installation of ASEC applications, including copying and
11146     * renaming logic.
11147     */
11148    class AsecInstallArgs extends InstallArgs {
11149        static final String RES_FILE_NAME = "pkg.apk";
11150        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11151
11152        String cid;
11153        String packagePath;
11154        String resourcePath;
11155
11156        /** New install */
11157        AsecInstallArgs(InstallParams params) {
11158            super(params.origin, params.move, params.observer, params.installFlags,
11159                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11160                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11161                    params.grantedRuntimePermissions);
11162        }
11163
11164        /** Existing install */
11165        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11166                        boolean isExternal, boolean isForwardLocked) {
11167            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11168                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11169                    instructionSets, null, null);
11170            // Hackily pretend we're still looking at a full code path
11171            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11172                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11173            }
11174
11175            // Extract cid from fullCodePath
11176            int eidx = fullCodePath.lastIndexOf("/");
11177            String subStr1 = fullCodePath.substring(0, eidx);
11178            int sidx = subStr1.lastIndexOf("/");
11179            cid = subStr1.substring(sidx+1, eidx);
11180            setMountPath(subStr1);
11181        }
11182
11183        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11184            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11185                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11186                    instructionSets, null, null);
11187            this.cid = cid;
11188            setMountPath(PackageHelper.getSdDir(cid));
11189        }
11190
11191        void createCopyFile() {
11192            cid = mInstallerService.allocateExternalStageCidLegacy();
11193        }
11194
11195        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11196            if (origin.staged) {
11197                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11198                cid = origin.cid;
11199                setMountPath(PackageHelper.getSdDir(cid));
11200                return PackageManager.INSTALL_SUCCEEDED;
11201            }
11202
11203            if (temp) {
11204                createCopyFile();
11205            } else {
11206                /*
11207                 * Pre-emptively destroy the container since it's destroyed if
11208                 * copying fails due to it existing anyway.
11209                 */
11210                PackageHelper.destroySdDir(cid);
11211            }
11212
11213            final String newMountPath = imcs.copyPackageToContainer(
11214                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11215                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11216
11217            if (newMountPath != null) {
11218                setMountPath(newMountPath);
11219                return PackageManager.INSTALL_SUCCEEDED;
11220            } else {
11221                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11222            }
11223        }
11224
11225        @Override
11226        String getCodePath() {
11227            return packagePath;
11228        }
11229
11230        @Override
11231        String getResourcePath() {
11232            return resourcePath;
11233        }
11234
11235        int doPreInstall(int status) {
11236            if (status != PackageManager.INSTALL_SUCCEEDED) {
11237                // Destroy container
11238                PackageHelper.destroySdDir(cid);
11239            } else {
11240                boolean mounted = PackageHelper.isContainerMounted(cid);
11241                if (!mounted) {
11242                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11243                            Process.SYSTEM_UID);
11244                    if (newMountPath != null) {
11245                        setMountPath(newMountPath);
11246                    } else {
11247                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11248                    }
11249                }
11250            }
11251            return status;
11252        }
11253
11254        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11255            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11256            String newMountPath = null;
11257            if (PackageHelper.isContainerMounted(cid)) {
11258                // Unmount the container
11259                if (!PackageHelper.unMountSdDir(cid)) {
11260                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11261                    return false;
11262                }
11263            }
11264            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11265                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11266                        " which might be stale. Will try to clean up.");
11267                // Clean up the stale container and proceed to recreate.
11268                if (!PackageHelper.destroySdDir(newCacheId)) {
11269                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11270                    return false;
11271                }
11272                // Successfully cleaned up stale container. Try to rename again.
11273                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11274                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11275                            + " inspite of cleaning it up.");
11276                    return false;
11277                }
11278            }
11279            if (!PackageHelper.isContainerMounted(newCacheId)) {
11280                Slog.w(TAG, "Mounting container " + newCacheId);
11281                newMountPath = PackageHelper.mountSdDir(newCacheId,
11282                        getEncryptKey(), Process.SYSTEM_UID);
11283            } else {
11284                newMountPath = PackageHelper.getSdDir(newCacheId);
11285            }
11286            if (newMountPath == null) {
11287                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11288                return false;
11289            }
11290            Log.i(TAG, "Succesfully renamed " + cid +
11291                    " to " + newCacheId +
11292                    " at new path: " + newMountPath);
11293            cid = newCacheId;
11294
11295            final File beforeCodeFile = new File(packagePath);
11296            setMountPath(newMountPath);
11297            final File afterCodeFile = new File(packagePath);
11298
11299            // Reflect the rename in scanned details
11300            pkg.codePath = afterCodeFile.getAbsolutePath();
11301            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11302                    pkg.baseCodePath);
11303            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11304                    pkg.splitCodePaths);
11305
11306            // Reflect the rename in app info
11307            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11308            pkg.applicationInfo.setCodePath(pkg.codePath);
11309            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11310            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11311            pkg.applicationInfo.setResourcePath(pkg.codePath);
11312            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11313            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11314
11315            return true;
11316        }
11317
11318        private void setMountPath(String mountPath) {
11319            final File mountFile = new File(mountPath);
11320
11321            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11322            if (monolithicFile.exists()) {
11323                packagePath = monolithicFile.getAbsolutePath();
11324                if (isFwdLocked()) {
11325                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11326                } else {
11327                    resourcePath = packagePath;
11328                }
11329            } else {
11330                packagePath = mountFile.getAbsolutePath();
11331                resourcePath = packagePath;
11332            }
11333        }
11334
11335        int doPostInstall(int status, int uid) {
11336            if (status != PackageManager.INSTALL_SUCCEEDED) {
11337                cleanUp();
11338            } else {
11339                final int groupOwner;
11340                final String protectedFile;
11341                if (isFwdLocked()) {
11342                    groupOwner = UserHandle.getSharedAppGid(uid);
11343                    protectedFile = RES_FILE_NAME;
11344                } else {
11345                    groupOwner = -1;
11346                    protectedFile = null;
11347                }
11348
11349                if (uid < Process.FIRST_APPLICATION_UID
11350                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11351                    Slog.e(TAG, "Failed to finalize " + cid);
11352                    PackageHelper.destroySdDir(cid);
11353                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11354                }
11355
11356                boolean mounted = PackageHelper.isContainerMounted(cid);
11357                if (!mounted) {
11358                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11359                }
11360            }
11361            return status;
11362        }
11363
11364        private void cleanUp() {
11365            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11366
11367            // Destroy secure container
11368            PackageHelper.destroySdDir(cid);
11369        }
11370
11371        private List<String> getAllCodePaths() {
11372            final File codeFile = new File(getCodePath());
11373            if (codeFile != null && codeFile.exists()) {
11374                try {
11375                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11376                    return pkg.getAllCodePaths();
11377                } catch (PackageParserException e) {
11378                    // Ignored; we tried our best
11379                }
11380            }
11381            return Collections.EMPTY_LIST;
11382        }
11383
11384        void cleanUpResourcesLI() {
11385            // Enumerate all code paths before deleting
11386            cleanUpResourcesLI(getAllCodePaths());
11387        }
11388
11389        private void cleanUpResourcesLI(List<String> allCodePaths) {
11390            cleanUp();
11391            removeDexFiles(allCodePaths, instructionSets);
11392        }
11393
11394        String getPackageName() {
11395            return getAsecPackageName(cid);
11396        }
11397
11398        boolean doPostDeleteLI(boolean delete) {
11399            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11400            final List<String> allCodePaths = getAllCodePaths();
11401            boolean mounted = PackageHelper.isContainerMounted(cid);
11402            if (mounted) {
11403                // Unmount first
11404                if (PackageHelper.unMountSdDir(cid)) {
11405                    mounted = false;
11406                }
11407            }
11408            if (!mounted && delete) {
11409                cleanUpResourcesLI(allCodePaths);
11410            }
11411            return !mounted;
11412        }
11413
11414        @Override
11415        int doPreCopy() {
11416            if (isFwdLocked()) {
11417                if (!PackageHelper.fixSdPermissions(cid,
11418                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11419                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11420                }
11421            }
11422
11423            return PackageManager.INSTALL_SUCCEEDED;
11424        }
11425
11426        @Override
11427        int doPostCopy(int uid) {
11428            if (isFwdLocked()) {
11429                if (uid < Process.FIRST_APPLICATION_UID
11430                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11431                                RES_FILE_NAME)) {
11432                    Slog.e(TAG, "Failed to finalize " + cid);
11433                    PackageHelper.destroySdDir(cid);
11434                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11435                }
11436            }
11437
11438            return PackageManager.INSTALL_SUCCEEDED;
11439        }
11440    }
11441
11442    /**
11443     * Logic to handle movement of existing installed applications.
11444     */
11445    class MoveInstallArgs extends InstallArgs {
11446        private File codeFile;
11447        private File resourceFile;
11448
11449        /** New install */
11450        MoveInstallArgs(InstallParams params) {
11451            super(params.origin, params.move, params.observer, params.installFlags,
11452                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11453                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11454                    params.grantedRuntimePermissions);
11455        }
11456
11457        int copyApk(IMediaContainerService imcs, boolean temp) {
11458            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11459                    + move.fromUuid + " to " + move.toUuid);
11460            synchronized (mInstaller) {
11461                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11462                        move.dataAppName, move.appId, move.seinfo) != 0) {
11463                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11464                }
11465            }
11466
11467            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11468            resourceFile = codeFile;
11469            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11470
11471            return PackageManager.INSTALL_SUCCEEDED;
11472        }
11473
11474        int doPreInstall(int status) {
11475            if (status != PackageManager.INSTALL_SUCCEEDED) {
11476                cleanUp(move.toUuid);
11477            }
11478            return status;
11479        }
11480
11481        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11482            if (status != PackageManager.INSTALL_SUCCEEDED) {
11483                cleanUp(move.toUuid);
11484                return false;
11485            }
11486
11487            // Reflect the move in app info
11488            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11489            pkg.applicationInfo.setCodePath(pkg.codePath);
11490            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11491            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11492            pkg.applicationInfo.setResourcePath(pkg.codePath);
11493            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11494            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11495
11496            return true;
11497        }
11498
11499        int doPostInstall(int status, int uid) {
11500            if (status == PackageManager.INSTALL_SUCCEEDED) {
11501                cleanUp(move.fromUuid);
11502            } else {
11503                cleanUp(move.toUuid);
11504            }
11505            return status;
11506        }
11507
11508        @Override
11509        String getCodePath() {
11510            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11511        }
11512
11513        @Override
11514        String getResourcePath() {
11515            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11516        }
11517
11518        private boolean cleanUp(String volumeUuid) {
11519            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11520                    move.dataAppName);
11521            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11522            synchronized (mInstallLock) {
11523                // Clean up both app data and code
11524                removeDataDirsLI(volumeUuid, move.packageName);
11525                if (codeFile.isDirectory()) {
11526                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11527                } else {
11528                    codeFile.delete();
11529                }
11530            }
11531            return true;
11532        }
11533
11534        void cleanUpResourcesLI() {
11535            throw new UnsupportedOperationException();
11536        }
11537
11538        boolean doPostDeleteLI(boolean delete) {
11539            throw new UnsupportedOperationException();
11540        }
11541    }
11542
11543    static String getAsecPackageName(String packageCid) {
11544        int idx = packageCid.lastIndexOf("-");
11545        if (idx == -1) {
11546            return packageCid;
11547        }
11548        return packageCid.substring(0, idx);
11549    }
11550
11551    // Utility method used to create code paths based on package name and available index.
11552    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11553        String idxStr = "";
11554        int idx = 1;
11555        // Fall back to default value of idx=1 if prefix is not
11556        // part of oldCodePath
11557        if (oldCodePath != null) {
11558            String subStr = oldCodePath;
11559            // Drop the suffix right away
11560            if (suffix != null && subStr.endsWith(suffix)) {
11561                subStr = subStr.substring(0, subStr.length() - suffix.length());
11562            }
11563            // If oldCodePath already contains prefix find out the
11564            // ending index to either increment or decrement.
11565            int sidx = subStr.lastIndexOf(prefix);
11566            if (sidx != -1) {
11567                subStr = subStr.substring(sidx + prefix.length());
11568                if (subStr != null) {
11569                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11570                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11571                    }
11572                    try {
11573                        idx = Integer.parseInt(subStr);
11574                        if (idx <= 1) {
11575                            idx++;
11576                        } else {
11577                            idx--;
11578                        }
11579                    } catch(NumberFormatException e) {
11580                    }
11581                }
11582            }
11583        }
11584        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11585        return prefix + idxStr;
11586    }
11587
11588    private File getNextCodePath(File targetDir, String packageName) {
11589        int suffix = 1;
11590        File result;
11591        do {
11592            result = new File(targetDir, packageName + "-" + suffix);
11593            suffix++;
11594        } while (result.exists());
11595        return result;
11596    }
11597
11598    // Utility method that returns the relative package path with respect
11599    // to the installation directory. Like say for /data/data/com.test-1.apk
11600    // string com.test-1 is returned.
11601    static String deriveCodePathName(String codePath) {
11602        if (codePath == null) {
11603            return null;
11604        }
11605        final File codeFile = new File(codePath);
11606        final String name = codeFile.getName();
11607        if (codeFile.isDirectory()) {
11608            return name;
11609        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11610            final int lastDot = name.lastIndexOf('.');
11611            return name.substring(0, lastDot);
11612        } else {
11613            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11614            return null;
11615        }
11616    }
11617
11618    class PackageInstalledInfo {
11619        String name;
11620        int uid;
11621        // The set of users that originally had this package installed.
11622        int[] origUsers;
11623        // The set of users that now have this package installed.
11624        int[] newUsers;
11625        PackageParser.Package pkg;
11626        int returnCode;
11627        String returnMsg;
11628        PackageRemovedInfo removedInfo;
11629
11630        public void setError(int code, String msg) {
11631            returnCode = code;
11632            returnMsg = msg;
11633            Slog.w(TAG, msg);
11634        }
11635
11636        public void setError(String msg, PackageParserException e) {
11637            returnCode = e.error;
11638            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11639            Slog.w(TAG, msg, e);
11640        }
11641
11642        public void setError(String msg, PackageManagerException e) {
11643            returnCode = e.error;
11644            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11645            Slog.w(TAG, msg, e);
11646        }
11647
11648        // In some error cases we want to convey more info back to the observer
11649        String origPackage;
11650        String origPermission;
11651    }
11652
11653    /*
11654     * Install a non-existing package.
11655     */
11656    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11657            UserHandle user, String installerPackageName, String volumeUuid,
11658            PackageInstalledInfo res) {
11659        // Remember this for later, in case we need to rollback this install
11660        String pkgName = pkg.packageName;
11661
11662        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11663        final boolean dataDirExists = Environment
11664                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11665        synchronized(mPackages) {
11666            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11667                // A package with the same name is already installed, though
11668                // it has been renamed to an older name.  The package we
11669                // are trying to install should be installed as an update to
11670                // the existing one, but that has not been requested, so bail.
11671                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11672                        + " without first uninstalling package running as "
11673                        + mSettings.mRenamedPackages.get(pkgName));
11674                return;
11675            }
11676            if (mPackages.containsKey(pkgName)) {
11677                // Don't allow installation over an existing package with the same name.
11678                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11679                        + " without first uninstalling.");
11680                return;
11681            }
11682        }
11683
11684        try {
11685            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11686                    System.currentTimeMillis(), user);
11687
11688            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11689            // delete the partially installed application. the data directory will have to be
11690            // restored if it was already existing
11691            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11692                // remove package from internal structures.  Note that we want deletePackageX to
11693                // delete the package data and cache directories that it created in
11694                // scanPackageLocked, unless those directories existed before we even tried to
11695                // install.
11696                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11697                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11698                                res.removedInfo, true);
11699            }
11700
11701        } catch (PackageManagerException e) {
11702            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11703        }
11704    }
11705
11706    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11707        // Can't rotate keys during boot or if sharedUser.
11708        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11709                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11710            return false;
11711        }
11712        // app is using upgradeKeySets; make sure all are valid
11713        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11714        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11715        for (int i = 0; i < upgradeKeySets.length; i++) {
11716            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11717                Slog.wtf(TAG, "Package "
11718                         + (oldPs.name != null ? oldPs.name : "<null>")
11719                         + " contains upgrade-key-set reference to unknown key-set: "
11720                         + upgradeKeySets[i]
11721                         + " reverting to signatures check.");
11722                return false;
11723            }
11724        }
11725        return true;
11726    }
11727
11728    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11729        // Upgrade keysets are being used.  Determine if new package has a superset of the
11730        // required keys.
11731        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11732        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11733        for (int i = 0; i < upgradeKeySets.length; i++) {
11734            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11735            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11736                return true;
11737            }
11738        }
11739        return false;
11740    }
11741
11742    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11743            UserHandle user, String installerPackageName, String volumeUuid,
11744            PackageInstalledInfo res) {
11745        final PackageParser.Package oldPackage;
11746        final String pkgName = pkg.packageName;
11747        final int[] allUsers;
11748        final boolean[] perUserInstalled;
11749        final boolean weFroze;
11750
11751        // First find the old package info and check signatures
11752        synchronized(mPackages) {
11753            oldPackage = mPackages.get(pkgName);
11754            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11755            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11756            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11757                if(!checkUpgradeKeySetLP(ps, pkg)) {
11758                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11759                            "New package not signed by keys specified by upgrade-keysets: "
11760                            + pkgName);
11761                    return;
11762                }
11763            } else {
11764                // default to original signature matching
11765                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11766                    != PackageManager.SIGNATURE_MATCH) {
11767                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11768                            "New package has a different signature: " + pkgName);
11769                    return;
11770                }
11771            }
11772
11773            // In case of rollback, remember per-user/profile install state
11774            allUsers = sUserManager.getUserIds();
11775            perUserInstalled = new boolean[allUsers.length];
11776            for (int i = 0; i < allUsers.length; i++) {
11777                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11778            }
11779
11780            // Mark the app as frozen to prevent launching during the upgrade
11781            // process, and then kill all running instances
11782            if (!ps.frozen) {
11783                ps.frozen = true;
11784                weFroze = true;
11785            } else {
11786                weFroze = false;
11787            }
11788        }
11789
11790        // Now that we're guarded by frozen state, kill app during upgrade
11791        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11792
11793        try {
11794            boolean sysPkg = (isSystemApp(oldPackage));
11795            if (sysPkg) {
11796                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11797                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11798            } else {
11799                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11800                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11801            }
11802        } finally {
11803            // Regardless of success or failure of upgrade steps above, always
11804            // unfreeze the package if we froze it
11805            if (weFroze) {
11806                unfreezePackage(pkgName);
11807            }
11808        }
11809    }
11810
11811    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11812            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11813            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11814            String volumeUuid, PackageInstalledInfo res) {
11815        String pkgName = deletedPackage.packageName;
11816        boolean deletedPkg = true;
11817        boolean updatedSettings = false;
11818
11819        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11820                + deletedPackage);
11821        long origUpdateTime;
11822        if (pkg.mExtras != null) {
11823            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11824        } else {
11825            origUpdateTime = 0;
11826        }
11827
11828        // First delete the existing package while retaining the data directory
11829        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11830                res.removedInfo, true)) {
11831            // If the existing package wasn't successfully deleted
11832            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11833            deletedPkg = false;
11834        } else {
11835            // Successfully deleted the old package; proceed with replace.
11836
11837            // If deleted package lived in a container, give users a chance to
11838            // relinquish resources before killing.
11839            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11840                if (DEBUG_INSTALL) {
11841                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11842                }
11843                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11844                final ArrayList<String> pkgList = new ArrayList<String>(1);
11845                pkgList.add(deletedPackage.applicationInfo.packageName);
11846                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11847            }
11848
11849            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11850            try {
11851                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11852                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11853                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11854                        perUserInstalled, res, user);
11855                updatedSettings = true;
11856            } catch (PackageManagerException e) {
11857                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11858            }
11859        }
11860
11861        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11862            // remove package from internal structures.  Note that we want deletePackageX to
11863            // delete the package data and cache directories that it created in
11864            // scanPackageLocked, unless those directories existed before we even tried to
11865            // install.
11866            if(updatedSettings) {
11867                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11868                deletePackageLI(
11869                        pkgName, null, true, allUsers, perUserInstalled,
11870                        PackageManager.DELETE_KEEP_DATA,
11871                                res.removedInfo, true);
11872            }
11873            // Since we failed to install the new package we need to restore the old
11874            // package that we deleted.
11875            if (deletedPkg) {
11876                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11877                File restoreFile = new File(deletedPackage.codePath);
11878                // Parse old package
11879                boolean oldExternal = isExternal(deletedPackage);
11880                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11881                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11882                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11883                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11884                try {
11885                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11886                } catch (PackageManagerException e) {
11887                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11888                            + e.getMessage());
11889                    return;
11890                }
11891                // Restore of old package succeeded. Update permissions.
11892                // writer
11893                synchronized (mPackages) {
11894                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11895                            UPDATE_PERMISSIONS_ALL);
11896                    // can downgrade to reader
11897                    mSettings.writeLPr();
11898                }
11899                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11900            }
11901        }
11902    }
11903
11904    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11905            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11906            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11907            String volumeUuid, PackageInstalledInfo res) {
11908        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11909                + ", old=" + deletedPackage);
11910        boolean disabledSystem = false;
11911        boolean updatedSettings = false;
11912        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11913        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11914                != 0) {
11915            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11916        }
11917        String packageName = deletedPackage.packageName;
11918        if (packageName == null) {
11919            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11920                    "Attempt to delete null packageName.");
11921            return;
11922        }
11923        PackageParser.Package oldPkg;
11924        PackageSetting oldPkgSetting;
11925        // reader
11926        synchronized (mPackages) {
11927            oldPkg = mPackages.get(packageName);
11928            oldPkgSetting = mSettings.mPackages.get(packageName);
11929            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11930                    (oldPkgSetting == null)) {
11931                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11932                        "Couldn't find package:" + packageName + " information");
11933                return;
11934            }
11935        }
11936
11937        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11938        res.removedInfo.removedPackage = packageName;
11939        // Remove existing system package
11940        removePackageLI(oldPkgSetting, true);
11941        // writer
11942        synchronized (mPackages) {
11943            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11944            if (!disabledSystem && deletedPackage != null) {
11945                // We didn't need to disable the .apk as a current system package,
11946                // which means we are replacing another update that is already
11947                // installed.  We need to make sure to delete the older one's .apk.
11948                res.removedInfo.args = createInstallArgsForExisting(0,
11949                        deletedPackage.applicationInfo.getCodePath(),
11950                        deletedPackage.applicationInfo.getResourcePath(),
11951                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11952            } else {
11953                res.removedInfo.args = null;
11954            }
11955        }
11956
11957        // Successfully disabled the old package. Now proceed with re-installation
11958        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11959
11960        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11961        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11962
11963        PackageParser.Package newPackage = null;
11964        try {
11965            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11966            if (newPackage.mExtras != null) {
11967                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11968                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11969                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11970
11971                // is the update attempting to change shared user? that isn't going to work...
11972                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11973                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11974                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11975                            + " to " + newPkgSetting.sharedUser);
11976                    updatedSettings = true;
11977                }
11978            }
11979
11980            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11981                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11982                        perUserInstalled, res, user);
11983                updatedSettings = true;
11984            }
11985
11986        } catch (PackageManagerException e) {
11987            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11988        }
11989
11990        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11991            // Re installation failed. Restore old information
11992            // Remove new pkg information
11993            if (newPackage != null) {
11994                removeInstalledPackageLI(newPackage, true);
11995            }
11996            // Add back the old system package
11997            try {
11998                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11999            } catch (PackageManagerException e) {
12000                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12001            }
12002            // Restore the old system information in Settings
12003            synchronized (mPackages) {
12004                if (disabledSystem) {
12005                    mSettings.enableSystemPackageLPw(packageName);
12006                }
12007                if (updatedSettings) {
12008                    mSettings.setInstallerPackageName(packageName,
12009                            oldPkgSetting.installerPackageName);
12010                }
12011                mSettings.writeLPr();
12012            }
12013        }
12014    }
12015
12016    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12017            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12018            UserHandle user) {
12019        String pkgName = newPackage.packageName;
12020        synchronized (mPackages) {
12021            //write settings. the installStatus will be incomplete at this stage.
12022            //note that the new package setting would have already been
12023            //added to mPackages. It hasn't been persisted yet.
12024            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12025            mSettings.writeLPr();
12026        }
12027
12028        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12029
12030        synchronized (mPackages) {
12031            updatePermissionsLPw(newPackage.packageName, newPackage,
12032                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12033                            ? UPDATE_PERMISSIONS_ALL : 0));
12034            // For system-bundled packages, we assume that installing an upgraded version
12035            // of the package implies that the user actually wants to run that new code,
12036            // so we enable the package.
12037            PackageSetting ps = mSettings.mPackages.get(pkgName);
12038            if (ps != null) {
12039                if (isSystemApp(newPackage)) {
12040                    // NB: implicit assumption that system package upgrades apply to all users
12041                    if (DEBUG_INSTALL) {
12042                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12043                    }
12044                    if (res.origUsers != null) {
12045                        for (int userHandle : res.origUsers) {
12046                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12047                                    userHandle, installerPackageName);
12048                        }
12049                    }
12050                    // Also convey the prior install/uninstall state
12051                    if (allUsers != null && perUserInstalled != null) {
12052                        for (int i = 0; i < allUsers.length; i++) {
12053                            if (DEBUG_INSTALL) {
12054                                Slog.d(TAG, "    user " + allUsers[i]
12055                                        + " => " + perUserInstalled[i]);
12056                            }
12057                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12058                        }
12059                        // these install state changes will be persisted in the
12060                        // upcoming call to mSettings.writeLPr().
12061                    }
12062                }
12063                // It's implied that when a user requests installation, they want the app to be
12064                // installed and enabled.
12065                int userId = user.getIdentifier();
12066                if (userId != UserHandle.USER_ALL) {
12067                    ps.setInstalled(true, userId);
12068                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12069                }
12070            }
12071            res.name = pkgName;
12072            res.uid = newPackage.applicationInfo.uid;
12073            res.pkg = newPackage;
12074            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12075            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12076            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12077            //to update install status
12078            mSettings.writeLPr();
12079        }
12080    }
12081
12082    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12083        final int installFlags = args.installFlags;
12084        final String installerPackageName = args.installerPackageName;
12085        final String volumeUuid = args.volumeUuid;
12086        final File tmpPackageFile = new File(args.getCodePath());
12087        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12088        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12089                || (args.volumeUuid != null));
12090        boolean replace = false;
12091        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12092        if (args.move != null) {
12093            // moving a complete application; perfom an initial scan on the new install location
12094            scanFlags |= SCAN_INITIAL;
12095        }
12096        // Result object to be returned
12097        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12098
12099        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12100        // Retrieve PackageSettings and parse package
12101        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12102                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12103                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12104        PackageParser pp = new PackageParser();
12105        pp.setSeparateProcesses(mSeparateProcesses);
12106        pp.setDisplayMetrics(mMetrics);
12107
12108        final PackageParser.Package pkg;
12109        try {
12110            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12111        } catch (PackageParserException e) {
12112            res.setError("Failed parse during installPackageLI", e);
12113            return;
12114        }
12115
12116        // Mark that we have an install time CPU ABI override.
12117        pkg.cpuAbiOverride = args.abiOverride;
12118
12119        String pkgName = res.name = pkg.packageName;
12120        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12121            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12122                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12123                return;
12124            }
12125        }
12126
12127        try {
12128            pp.collectCertificates(pkg, parseFlags);
12129            pp.collectManifestDigest(pkg);
12130        } catch (PackageParserException e) {
12131            res.setError("Failed collect during installPackageLI", e);
12132            return;
12133        }
12134
12135        /* If the installer passed in a manifest digest, compare it now. */
12136        if (args.manifestDigest != null) {
12137            if (DEBUG_INSTALL) {
12138                final String parsedManifest = pkg.manifestDigest == null ? "null"
12139                        : pkg.manifestDigest.toString();
12140                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12141                        + parsedManifest);
12142            }
12143
12144            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12145                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12146                return;
12147            }
12148        } else if (DEBUG_INSTALL) {
12149            final String parsedManifest = pkg.manifestDigest == null
12150                    ? "null" : pkg.manifestDigest.toString();
12151            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12152        }
12153
12154        // Get rid of all references to package scan path via parser.
12155        pp = null;
12156        String oldCodePath = null;
12157        boolean systemApp = false;
12158        synchronized (mPackages) {
12159            // Check if installing already existing package
12160            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12161                String oldName = mSettings.mRenamedPackages.get(pkgName);
12162                if (pkg.mOriginalPackages != null
12163                        && pkg.mOriginalPackages.contains(oldName)
12164                        && mPackages.containsKey(oldName)) {
12165                    // This package is derived from an original package,
12166                    // and this device has been updating from that original
12167                    // name.  We must continue using the original name, so
12168                    // rename the new package here.
12169                    pkg.setPackageName(oldName);
12170                    pkgName = pkg.packageName;
12171                    replace = true;
12172                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12173                            + oldName + " pkgName=" + pkgName);
12174                } else if (mPackages.containsKey(pkgName)) {
12175                    // This package, under its official name, already exists
12176                    // on the device; we should replace it.
12177                    replace = true;
12178                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12179                }
12180
12181                // Prevent apps opting out from runtime permissions
12182                if (replace) {
12183                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12184                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12185                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12186                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12187                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12188                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12189                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12190                                        + " doesn't support runtime permissions but the old"
12191                                        + " target SDK " + oldTargetSdk + " does.");
12192                        return;
12193                    }
12194                }
12195            }
12196
12197            PackageSetting ps = mSettings.mPackages.get(pkgName);
12198            if (ps != null) {
12199                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12200
12201                // Quick sanity check that we're signed correctly if updating;
12202                // we'll check this again later when scanning, but we want to
12203                // bail early here before tripping over redefined permissions.
12204                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12205                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12206                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12207                                + pkg.packageName + " upgrade keys do not match the "
12208                                + "previously installed version");
12209                        return;
12210                    }
12211                } else {
12212                    try {
12213                        verifySignaturesLP(ps, pkg);
12214                    } catch (PackageManagerException e) {
12215                        res.setError(e.error, e.getMessage());
12216                        return;
12217                    }
12218                }
12219
12220                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12221                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12222                    systemApp = (ps.pkg.applicationInfo.flags &
12223                            ApplicationInfo.FLAG_SYSTEM) != 0;
12224                }
12225                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12226            }
12227
12228            // Check whether the newly-scanned package wants to define an already-defined perm
12229            int N = pkg.permissions.size();
12230            for (int i = N-1; i >= 0; i--) {
12231                PackageParser.Permission perm = pkg.permissions.get(i);
12232                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12233                if (bp != null) {
12234                    // If the defining package is signed with our cert, it's okay.  This
12235                    // also includes the "updating the same package" case, of course.
12236                    // "updating same package" could also involve key-rotation.
12237                    final boolean sigsOk;
12238                    if (bp.sourcePackage.equals(pkg.packageName)
12239                            && (bp.packageSetting instanceof PackageSetting)
12240                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12241                                    scanFlags))) {
12242                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12243                    } else {
12244                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12245                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12246                    }
12247                    if (!sigsOk) {
12248                        // If the owning package is the system itself, we log but allow
12249                        // install to proceed; we fail the install on all other permission
12250                        // redefinitions.
12251                        if (!bp.sourcePackage.equals("android")) {
12252                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12253                                    + pkg.packageName + " attempting to redeclare permission "
12254                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12255                            res.origPermission = perm.info.name;
12256                            res.origPackage = bp.sourcePackage;
12257                            return;
12258                        } else {
12259                            Slog.w(TAG, "Package " + pkg.packageName
12260                                    + " attempting to redeclare system permission "
12261                                    + perm.info.name + "; ignoring new declaration");
12262                            pkg.permissions.remove(i);
12263                        }
12264                    }
12265                }
12266            }
12267
12268        }
12269
12270        if (systemApp && onExternal) {
12271            // Disable updates to system apps on sdcard
12272            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12273                    "Cannot install updates to system apps on sdcard");
12274            return;
12275        }
12276
12277        if (args.move != null) {
12278            // We did an in-place move, so dex is ready to roll
12279            scanFlags |= SCAN_NO_DEX;
12280            scanFlags |= SCAN_MOVE;
12281
12282            synchronized (mPackages) {
12283                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12284                if (ps == null) {
12285                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12286                            "Missing settings for moved package " + pkgName);
12287                }
12288
12289                // We moved the entire application as-is, so bring over the
12290                // previously derived ABI information.
12291                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12292                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12293            }
12294
12295        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12296            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12297            scanFlags |= SCAN_NO_DEX;
12298
12299            try {
12300                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12301                        true /* extract libs */);
12302            } catch (PackageManagerException pme) {
12303                Slog.e(TAG, "Error deriving application ABI", pme);
12304                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12305                return;
12306            }
12307
12308            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12309            int result = mPackageDexOptimizer
12310                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12311                            false /* defer */, false /* inclDependencies */);
12312            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12313                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12314                return;
12315            }
12316        }
12317
12318        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12319            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12320            return;
12321        }
12322
12323        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12324
12325        if (replace) {
12326            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12327                    installerPackageName, volumeUuid, res);
12328        } else {
12329            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12330                    args.user, installerPackageName, volumeUuid, res);
12331        }
12332        synchronized (mPackages) {
12333            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12334            if (ps != null) {
12335                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12336            }
12337        }
12338    }
12339
12340    private void startIntentFilterVerifications(int userId, boolean replacing,
12341            PackageParser.Package pkg) {
12342        if (mIntentFilterVerifierComponent == null) {
12343            Slog.w(TAG, "No IntentFilter verification will not be done as "
12344                    + "there is no IntentFilterVerifier available!");
12345            return;
12346        }
12347
12348        final int verifierUid = getPackageUid(
12349                mIntentFilterVerifierComponent.getPackageName(),
12350                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12351
12352        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12353        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12354        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12355        mHandler.sendMessage(msg);
12356    }
12357
12358    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12359            PackageParser.Package pkg) {
12360        int size = pkg.activities.size();
12361        if (size == 0) {
12362            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12363                    "No activity, so no need to verify any IntentFilter!");
12364            return;
12365        }
12366
12367        final boolean hasDomainURLs = hasDomainURLs(pkg);
12368        if (!hasDomainURLs) {
12369            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12370                    "No domain URLs, so no need to verify any IntentFilter!");
12371            return;
12372        }
12373
12374        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12375                + " if any IntentFilter from the " + size
12376                + " Activities needs verification ...");
12377
12378        int count = 0;
12379        final String packageName = pkg.packageName;
12380
12381        synchronized (mPackages) {
12382            // If this is a new install and we see that we've already run verification for this
12383            // package, we have nothing to do: it means the state was restored from backup.
12384            if (!replacing) {
12385                IntentFilterVerificationInfo ivi =
12386                        mSettings.getIntentFilterVerificationLPr(packageName);
12387                if (ivi != null) {
12388                    if (DEBUG_DOMAIN_VERIFICATION) {
12389                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12390                                + ivi.getStatusString());
12391                    }
12392                    return;
12393                }
12394            }
12395
12396            // If any filters need to be verified, then all need to be.
12397            boolean needToVerify = false;
12398            for (PackageParser.Activity a : pkg.activities) {
12399                for (ActivityIntentInfo filter : a.intents) {
12400                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12401                        if (DEBUG_DOMAIN_VERIFICATION) {
12402                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12403                        }
12404                        needToVerify = true;
12405                        break;
12406                    }
12407                }
12408            }
12409
12410            if (needToVerify) {
12411                final int verificationId = mIntentFilterVerificationToken++;
12412                for (PackageParser.Activity a : pkg.activities) {
12413                    for (ActivityIntentInfo filter : a.intents) {
12414                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12415                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12416                                    "Verification needed for IntentFilter:" + filter.toString());
12417                            mIntentFilterVerifier.addOneIntentFilterVerification(
12418                                    verifierUid, userId, verificationId, filter, packageName);
12419                            count++;
12420                        }
12421                    }
12422                }
12423            }
12424        }
12425
12426        if (count > 0) {
12427            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12428                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12429                    +  " for userId:" + userId);
12430            mIntentFilterVerifier.startVerifications(userId);
12431        } else {
12432            if (DEBUG_DOMAIN_VERIFICATION) {
12433                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12434            }
12435        }
12436    }
12437
12438    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12439        final ComponentName cn  = filter.activity.getComponentName();
12440        final String packageName = cn.getPackageName();
12441
12442        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12443                packageName);
12444        if (ivi == null) {
12445            return true;
12446        }
12447        int status = ivi.getStatus();
12448        switch (status) {
12449            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12450            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12451                return true;
12452
12453            default:
12454                // Nothing to do
12455                return false;
12456        }
12457    }
12458
12459    private static boolean isMultiArch(PackageSetting ps) {
12460        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12461    }
12462
12463    private static boolean isMultiArch(ApplicationInfo info) {
12464        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12465    }
12466
12467    private static boolean isExternal(PackageParser.Package pkg) {
12468        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12469    }
12470
12471    private static boolean isExternal(PackageSetting ps) {
12472        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12473    }
12474
12475    private static boolean isExternal(ApplicationInfo info) {
12476        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12477    }
12478
12479    private static boolean isSystemApp(PackageParser.Package pkg) {
12480        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12481    }
12482
12483    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12484        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12485    }
12486
12487    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12488        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12489    }
12490
12491    private static boolean isSystemApp(PackageSetting ps) {
12492        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12493    }
12494
12495    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12496        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12497    }
12498
12499    private int packageFlagsToInstallFlags(PackageSetting ps) {
12500        int installFlags = 0;
12501        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12502            // This existing package was an external ASEC install when we have
12503            // the external flag without a UUID
12504            installFlags |= PackageManager.INSTALL_EXTERNAL;
12505        }
12506        if (ps.isForwardLocked()) {
12507            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12508        }
12509        return installFlags;
12510    }
12511
12512    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12513        if (isExternal(pkg)) {
12514            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12515                return mSettings.getExternalVersion();
12516            } else {
12517                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12518            }
12519        } else {
12520            return mSettings.getInternalVersion();
12521        }
12522    }
12523
12524    private void deleteTempPackageFiles() {
12525        final FilenameFilter filter = new FilenameFilter() {
12526            public boolean accept(File dir, String name) {
12527                return name.startsWith("vmdl") && name.endsWith(".tmp");
12528            }
12529        };
12530        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12531            file.delete();
12532        }
12533    }
12534
12535    @Override
12536    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12537            int flags) {
12538        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12539                flags);
12540    }
12541
12542    @Override
12543    public void deletePackage(final String packageName,
12544            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12545        mContext.enforceCallingOrSelfPermission(
12546                android.Manifest.permission.DELETE_PACKAGES, null);
12547        Preconditions.checkNotNull(packageName);
12548        Preconditions.checkNotNull(observer);
12549        final int uid = Binder.getCallingUid();
12550        if (UserHandle.getUserId(uid) != userId) {
12551            mContext.enforceCallingPermission(
12552                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12553                    "deletePackage for user " + userId);
12554        }
12555        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12556            try {
12557                observer.onPackageDeleted(packageName,
12558                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12559            } catch (RemoteException re) {
12560            }
12561            return;
12562        }
12563
12564        boolean uninstallBlocked = false;
12565        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12566            int[] users = sUserManager.getUserIds();
12567            for (int i = 0; i < users.length; ++i) {
12568                if (getBlockUninstallForUser(packageName, users[i])) {
12569                    uninstallBlocked = true;
12570                    break;
12571                }
12572            }
12573        } else {
12574            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12575        }
12576        if (uninstallBlocked) {
12577            try {
12578                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12579                        null);
12580            } catch (RemoteException re) {
12581            }
12582            return;
12583        }
12584
12585        if (DEBUG_REMOVE) {
12586            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12587        }
12588        // Queue up an async operation since the package deletion may take a little while.
12589        mHandler.post(new Runnable() {
12590            public void run() {
12591                mHandler.removeCallbacks(this);
12592                final int returnCode = deletePackageX(packageName, userId, flags);
12593                if (observer != null) {
12594                    try {
12595                        observer.onPackageDeleted(packageName, returnCode, null);
12596                    } catch (RemoteException e) {
12597                        Log.i(TAG, "Observer no longer exists.");
12598                    } //end catch
12599                } //end if
12600            } //end run
12601        });
12602    }
12603
12604    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12605        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12606                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12607        try {
12608            if (dpm != null) {
12609                if (dpm.isDeviceOwner(packageName)) {
12610                    return true;
12611                }
12612                int[] users;
12613                if (userId == UserHandle.USER_ALL) {
12614                    users = sUserManager.getUserIds();
12615                } else {
12616                    users = new int[]{userId};
12617                }
12618                for (int i = 0; i < users.length; ++i) {
12619                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12620                        return true;
12621                    }
12622                }
12623            }
12624        } catch (RemoteException e) {
12625        }
12626        return false;
12627    }
12628
12629    /**
12630     *  This method is an internal method that could be get invoked either
12631     *  to delete an installed package or to clean up a failed installation.
12632     *  After deleting an installed package, a broadcast is sent to notify any
12633     *  listeners that the package has been installed. For cleaning up a failed
12634     *  installation, the broadcast is not necessary since the package's
12635     *  installation wouldn't have sent the initial broadcast either
12636     *  The key steps in deleting a package are
12637     *  deleting the package information in internal structures like mPackages,
12638     *  deleting the packages base directories through installd
12639     *  updating mSettings to reflect current status
12640     *  persisting settings for later use
12641     *  sending a broadcast if necessary
12642     */
12643    private int deletePackageX(String packageName, int userId, int flags) {
12644        final PackageRemovedInfo info = new PackageRemovedInfo();
12645        final boolean res;
12646
12647        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12648                ? UserHandle.ALL : new UserHandle(userId);
12649
12650        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12651            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12652            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12653        }
12654
12655        boolean removedForAllUsers = false;
12656        boolean systemUpdate = false;
12657
12658        // for the uninstall-updates case and restricted profiles, remember the per-
12659        // userhandle installed state
12660        int[] allUsers;
12661        boolean[] perUserInstalled;
12662        synchronized (mPackages) {
12663            PackageSetting ps = mSettings.mPackages.get(packageName);
12664            allUsers = sUserManager.getUserIds();
12665            perUserInstalled = new boolean[allUsers.length];
12666            for (int i = 0; i < allUsers.length; i++) {
12667                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12668            }
12669        }
12670
12671        synchronized (mInstallLock) {
12672            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12673            res = deletePackageLI(packageName, removeForUser,
12674                    true, allUsers, perUserInstalled,
12675                    flags | REMOVE_CHATTY, info, true);
12676            systemUpdate = info.isRemovedPackageSystemUpdate;
12677            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12678                removedForAllUsers = true;
12679            }
12680            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12681                    + " removedForAllUsers=" + removedForAllUsers);
12682        }
12683
12684        if (res) {
12685            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12686
12687            // If the removed package was a system update, the old system package
12688            // was re-enabled; we need to broadcast this information
12689            if (systemUpdate) {
12690                Bundle extras = new Bundle(1);
12691                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12692                        ? info.removedAppId : info.uid);
12693                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12694
12695                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12696                        extras, null, null, null);
12697                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12698                        extras, null, null, null);
12699                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12700                        null, packageName, null, null);
12701            }
12702        }
12703        // Force a gc here.
12704        Runtime.getRuntime().gc();
12705        // Delete the resources here after sending the broadcast to let
12706        // other processes clean up before deleting resources.
12707        if (info.args != null) {
12708            synchronized (mInstallLock) {
12709                info.args.doPostDeleteLI(true);
12710            }
12711        }
12712
12713        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12714    }
12715
12716    class PackageRemovedInfo {
12717        String removedPackage;
12718        int uid = -1;
12719        int removedAppId = -1;
12720        int[] removedUsers = null;
12721        boolean isRemovedPackageSystemUpdate = false;
12722        // Clean up resources deleted packages.
12723        InstallArgs args = null;
12724
12725        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12726            Bundle extras = new Bundle(1);
12727            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12728            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12729            if (replacing) {
12730                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12731            }
12732            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12733            if (removedPackage != null) {
12734                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12735                        extras, null, null, removedUsers);
12736                if (fullRemove && !replacing) {
12737                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12738                            extras, null, null, removedUsers);
12739                }
12740            }
12741            if (removedAppId >= 0) {
12742                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12743                        removedUsers);
12744            }
12745        }
12746    }
12747
12748    /*
12749     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12750     * flag is not set, the data directory is removed as well.
12751     * make sure this flag is set for partially installed apps. If not its meaningless to
12752     * delete a partially installed application.
12753     */
12754    private void removePackageDataLI(PackageSetting ps,
12755            int[] allUserHandles, boolean[] perUserInstalled,
12756            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12757        String packageName = ps.name;
12758        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12759        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12760        // Retrieve object to delete permissions for shared user later on
12761        final PackageSetting deletedPs;
12762        // reader
12763        synchronized (mPackages) {
12764            deletedPs = mSettings.mPackages.get(packageName);
12765            if (outInfo != null) {
12766                outInfo.removedPackage = packageName;
12767                outInfo.removedUsers = deletedPs != null
12768                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12769                        : null;
12770            }
12771        }
12772        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12773            removeDataDirsLI(ps.volumeUuid, packageName);
12774            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12775        }
12776        // writer
12777        synchronized (mPackages) {
12778            if (deletedPs != null) {
12779                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12780                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12781                    clearDefaultBrowserIfNeeded(packageName);
12782                    if (outInfo != null) {
12783                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12784                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12785                    }
12786                    updatePermissionsLPw(deletedPs.name, null, 0);
12787                    if (deletedPs.sharedUser != null) {
12788                        // Remove permissions associated with package. Since runtime
12789                        // permissions are per user we have to kill the removed package
12790                        // or packages running under the shared user of the removed
12791                        // package if revoking the permissions requested only by the removed
12792                        // package is successful and this causes a change in gids.
12793                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12794                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12795                                    userId);
12796                            if (userIdToKill == UserHandle.USER_ALL
12797                                    || userIdToKill >= UserHandle.USER_OWNER) {
12798                                // If gids changed for this user, kill all affected packages.
12799                                mHandler.post(new Runnable() {
12800                                    @Override
12801                                    public void run() {
12802                                        // This has to happen with no lock held.
12803                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12804                                                KILL_APP_REASON_GIDS_CHANGED);
12805                                    }
12806                                });
12807                                break;
12808                            }
12809                        }
12810                    }
12811                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12812                }
12813                // make sure to preserve per-user disabled state if this removal was just
12814                // a downgrade of a system app to the factory package
12815                if (allUserHandles != null && perUserInstalled != null) {
12816                    if (DEBUG_REMOVE) {
12817                        Slog.d(TAG, "Propagating install state across downgrade");
12818                    }
12819                    for (int i = 0; i < allUserHandles.length; i++) {
12820                        if (DEBUG_REMOVE) {
12821                            Slog.d(TAG, "    user " + allUserHandles[i]
12822                                    + " => " + perUserInstalled[i]);
12823                        }
12824                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12825                    }
12826                }
12827            }
12828            // can downgrade to reader
12829            if (writeSettings) {
12830                // Save settings now
12831                mSettings.writeLPr();
12832            }
12833        }
12834        if (outInfo != null) {
12835            // A user ID was deleted here. Go through all users and remove it
12836            // from KeyStore.
12837            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12838        }
12839    }
12840
12841    static boolean locationIsPrivileged(File path) {
12842        try {
12843            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12844                    .getCanonicalPath();
12845            return path.getCanonicalPath().startsWith(privilegedAppDir);
12846        } catch (IOException e) {
12847            Slog.e(TAG, "Unable to access code path " + path);
12848        }
12849        return false;
12850    }
12851
12852    /*
12853     * Tries to delete system package.
12854     */
12855    private boolean deleteSystemPackageLI(PackageSetting newPs,
12856            int[] allUserHandles, boolean[] perUserInstalled,
12857            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12858        final boolean applyUserRestrictions
12859                = (allUserHandles != null) && (perUserInstalled != null);
12860        PackageSetting disabledPs = null;
12861        // Confirm if the system package has been updated
12862        // An updated system app can be deleted. This will also have to restore
12863        // the system pkg from system partition
12864        // reader
12865        synchronized (mPackages) {
12866            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12867        }
12868        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12869                + " disabledPs=" + disabledPs);
12870        if (disabledPs == null) {
12871            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12872            return false;
12873        } else if (DEBUG_REMOVE) {
12874            Slog.d(TAG, "Deleting system pkg from data partition");
12875        }
12876        if (DEBUG_REMOVE) {
12877            if (applyUserRestrictions) {
12878                Slog.d(TAG, "Remembering install states:");
12879                for (int i = 0; i < allUserHandles.length; i++) {
12880                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12881                }
12882            }
12883        }
12884        // Delete the updated package
12885        outInfo.isRemovedPackageSystemUpdate = true;
12886        if (disabledPs.versionCode < newPs.versionCode) {
12887            // Delete data for downgrades
12888            flags &= ~PackageManager.DELETE_KEEP_DATA;
12889        } else {
12890            // Preserve data by setting flag
12891            flags |= PackageManager.DELETE_KEEP_DATA;
12892        }
12893        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12894                allUserHandles, perUserInstalled, outInfo, writeSettings);
12895        if (!ret) {
12896            return false;
12897        }
12898        // writer
12899        synchronized (mPackages) {
12900            // Reinstate the old system package
12901            mSettings.enableSystemPackageLPw(newPs.name);
12902            // Remove any native libraries from the upgraded package.
12903            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12904        }
12905        // Install the system package
12906        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12907        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12908        if (locationIsPrivileged(disabledPs.codePath)) {
12909            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12910        }
12911
12912        final PackageParser.Package newPkg;
12913        try {
12914            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12915        } catch (PackageManagerException e) {
12916            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12917            return false;
12918        }
12919
12920        // writer
12921        synchronized (mPackages) {
12922            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12923
12924            // Propagate the permissions state as we do want to drop on the floor
12925            // runtime permissions. The update permissions method below will take
12926            // care of removing obsolete permissions and grant install permissions.
12927            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12928            updatePermissionsLPw(newPkg.packageName, newPkg,
12929                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12930
12931            if (applyUserRestrictions) {
12932                if (DEBUG_REMOVE) {
12933                    Slog.d(TAG, "Propagating install state across reinstall");
12934                }
12935                for (int i = 0; i < allUserHandles.length; i++) {
12936                    if (DEBUG_REMOVE) {
12937                        Slog.d(TAG, "    user " + allUserHandles[i]
12938                                + " => " + perUserInstalled[i]);
12939                    }
12940                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12941                }
12942                // Regardless of writeSettings we need to ensure that this restriction
12943                // state propagation is persisted
12944                mSettings.writeAllUsersPackageRestrictionsLPr();
12945            }
12946            // can downgrade to reader here
12947            if (writeSettings) {
12948                mSettings.writeLPr();
12949            }
12950        }
12951        return true;
12952    }
12953
12954    private boolean deleteInstalledPackageLI(PackageSetting ps,
12955            boolean deleteCodeAndResources, int flags,
12956            int[] allUserHandles, boolean[] perUserInstalled,
12957            PackageRemovedInfo outInfo, boolean writeSettings) {
12958        if (outInfo != null) {
12959            outInfo.uid = ps.appId;
12960        }
12961
12962        // Delete package data from internal structures and also remove data if flag is set
12963        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12964
12965        // Delete application code and resources
12966        if (deleteCodeAndResources && (outInfo != null)) {
12967            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12968                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12969            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12970        }
12971        return true;
12972    }
12973
12974    @Override
12975    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12976            int userId) {
12977        mContext.enforceCallingOrSelfPermission(
12978                android.Manifest.permission.DELETE_PACKAGES, null);
12979        synchronized (mPackages) {
12980            PackageSetting ps = mSettings.mPackages.get(packageName);
12981            if (ps == null) {
12982                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12983                return false;
12984            }
12985            if (!ps.getInstalled(userId)) {
12986                // Can't block uninstall for an app that is not installed or enabled.
12987                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12988                return false;
12989            }
12990            ps.setBlockUninstall(blockUninstall, userId);
12991            mSettings.writePackageRestrictionsLPr(userId);
12992        }
12993        return true;
12994    }
12995
12996    @Override
12997    public boolean getBlockUninstallForUser(String packageName, int userId) {
12998        synchronized (mPackages) {
12999            PackageSetting ps = mSettings.mPackages.get(packageName);
13000            if (ps == null) {
13001                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13002                return false;
13003            }
13004            return ps.getBlockUninstall(userId);
13005        }
13006    }
13007
13008    /*
13009     * This method handles package deletion in general
13010     */
13011    private boolean deletePackageLI(String packageName, UserHandle user,
13012            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13013            int flags, PackageRemovedInfo outInfo,
13014            boolean writeSettings) {
13015        if (packageName == null) {
13016            Slog.w(TAG, "Attempt to delete null packageName.");
13017            return false;
13018        }
13019        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13020        PackageSetting ps;
13021        boolean dataOnly = false;
13022        int removeUser = -1;
13023        int appId = -1;
13024        synchronized (mPackages) {
13025            ps = mSettings.mPackages.get(packageName);
13026            if (ps == null) {
13027                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13028                return false;
13029            }
13030            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13031                    && user.getIdentifier() != UserHandle.USER_ALL) {
13032                // The caller is asking that the package only be deleted for a single
13033                // user.  To do this, we just mark its uninstalled state and delete
13034                // its data.  If this is a system app, we only allow this to happen if
13035                // they have set the special DELETE_SYSTEM_APP which requests different
13036                // semantics than normal for uninstalling system apps.
13037                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13038                ps.setUserState(user.getIdentifier(),
13039                        COMPONENT_ENABLED_STATE_DEFAULT,
13040                        false, //installed
13041                        true,  //stopped
13042                        true,  //notLaunched
13043                        false, //hidden
13044                        null, null, null,
13045                        false, // blockUninstall
13046                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13047                if (!isSystemApp(ps)) {
13048                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13049                        // Other user still have this package installed, so all
13050                        // we need to do is clear this user's data and save that
13051                        // it is uninstalled.
13052                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13053                        removeUser = user.getIdentifier();
13054                        appId = ps.appId;
13055                        scheduleWritePackageRestrictionsLocked(removeUser);
13056                    } else {
13057                        // We need to set it back to 'installed' so the uninstall
13058                        // broadcasts will be sent correctly.
13059                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13060                        ps.setInstalled(true, user.getIdentifier());
13061                    }
13062                } else {
13063                    // This is a system app, so we assume that the
13064                    // other users still have this package installed, so all
13065                    // we need to do is clear this user's data and save that
13066                    // it is uninstalled.
13067                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13068                    removeUser = user.getIdentifier();
13069                    appId = ps.appId;
13070                    scheduleWritePackageRestrictionsLocked(removeUser);
13071                }
13072            }
13073        }
13074
13075        if (removeUser >= 0) {
13076            // From above, we determined that we are deleting this only
13077            // for a single user.  Continue the work here.
13078            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13079            if (outInfo != null) {
13080                outInfo.removedPackage = packageName;
13081                outInfo.removedAppId = appId;
13082                outInfo.removedUsers = new int[] {removeUser};
13083            }
13084            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13085            removeKeystoreDataIfNeeded(removeUser, appId);
13086            schedulePackageCleaning(packageName, removeUser, false);
13087            synchronized (mPackages) {
13088                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13089                    scheduleWritePackageRestrictionsLocked(removeUser);
13090                }
13091                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13092            }
13093            return true;
13094        }
13095
13096        if (dataOnly) {
13097            // Delete application data first
13098            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13099            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13100            return true;
13101        }
13102
13103        boolean ret = false;
13104        if (isSystemApp(ps)) {
13105            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13106            // When an updated system application is deleted we delete the existing resources as well and
13107            // fall back to existing code in system partition
13108            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13109                    flags, outInfo, writeSettings);
13110        } else {
13111            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13112            // Kill application pre-emptively especially for apps on sd.
13113            killApplication(packageName, ps.appId, "uninstall pkg");
13114            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13115                    allUserHandles, perUserInstalled,
13116                    outInfo, writeSettings);
13117        }
13118
13119        return ret;
13120    }
13121
13122    private final class ClearStorageConnection implements ServiceConnection {
13123        IMediaContainerService mContainerService;
13124
13125        @Override
13126        public void onServiceConnected(ComponentName name, IBinder service) {
13127            synchronized (this) {
13128                mContainerService = IMediaContainerService.Stub.asInterface(service);
13129                notifyAll();
13130            }
13131        }
13132
13133        @Override
13134        public void onServiceDisconnected(ComponentName name) {
13135        }
13136    }
13137
13138    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13139        final boolean mounted;
13140        if (Environment.isExternalStorageEmulated()) {
13141            mounted = true;
13142        } else {
13143            final String status = Environment.getExternalStorageState();
13144
13145            mounted = status.equals(Environment.MEDIA_MOUNTED)
13146                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13147        }
13148
13149        if (!mounted) {
13150            return;
13151        }
13152
13153        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13154        int[] users;
13155        if (userId == UserHandle.USER_ALL) {
13156            users = sUserManager.getUserIds();
13157        } else {
13158            users = new int[] { userId };
13159        }
13160        final ClearStorageConnection conn = new ClearStorageConnection();
13161        if (mContext.bindServiceAsUser(
13162                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13163            try {
13164                for (int curUser : users) {
13165                    long timeout = SystemClock.uptimeMillis() + 5000;
13166                    synchronized (conn) {
13167                        long now = SystemClock.uptimeMillis();
13168                        while (conn.mContainerService == null && now < timeout) {
13169                            try {
13170                                conn.wait(timeout - now);
13171                            } catch (InterruptedException e) {
13172                            }
13173                        }
13174                    }
13175                    if (conn.mContainerService == null) {
13176                        return;
13177                    }
13178
13179                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13180                    clearDirectory(conn.mContainerService,
13181                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13182                    if (allData) {
13183                        clearDirectory(conn.mContainerService,
13184                                userEnv.buildExternalStorageAppDataDirs(packageName));
13185                        clearDirectory(conn.mContainerService,
13186                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13187                    }
13188                }
13189            } finally {
13190                mContext.unbindService(conn);
13191            }
13192        }
13193    }
13194
13195    @Override
13196    public void clearApplicationUserData(final String packageName,
13197            final IPackageDataObserver observer, final int userId) {
13198        mContext.enforceCallingOrSelfPermission(
13199                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13200        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13201        // Queue up an async operation since the package deletion may take a little while.
13202        mHandler.post(new Runnable() {
13203            public void run() {
13204                mHandler.removeCallbacks(this);
13205                final boolean succeeded;
13206                synchronized (mInstallLock) {
13207                    succeeded = clearApplicationUserDataLI(packageName, userId);
13208                }
13209                clearExternalStorageDataSync(packageName, userId, true);
13210                if (succeeded) {
13211                    // invoke DeviceStorageMonitor's update method to clear any notifications
13212                    DeviceStorageMonitorInternal
13213                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13214                    if (dsm != null) {
13215                        dsm.checkMemory();
13216                    }
13217                }
13218                if(observer != null) {
13219                    try {
13220                        observer.onRemoveCompleted(packageName, succeeded);
13221                    } catch (RemoteException e) {
13222                        Log.i(TAG, "Observer no longer exists.");
13223                    }
13224                } //end if observer
13225            } //end run
13226        });
13227    }
13228
13229    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13230        if (packageName == null) {
13231            Slog.w(TAG, "Attempt to delete null packageName.");
13232            return false;
13233        }
13234
13235        // Try finding details about the requested package
13236        PackageParser.Package pkg;
13237        synchronized (mPackages) {
13238            pkg = mPackages.get(packageName);
13239            if (pkg == null) {
13240                final PackageSetting ps = mSettings.mPackages.get(packageName);
13241                if (ps != null) {
13242                    pkg = ps.pkg;
13243                }
13244            }
13245
13246            if (pkg == null) {
13247                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13248                return false;
13249            }
13250
13251            PackageSetting ps = (PackageSetting) pkg.mExtras;
13252            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13253        }
13254
13255        // Always delete data directories for package, even if we found no other
13256        // record of app. This helps users recover from UID mismatches without
13257        // resorting to a full data wipe.
13258        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13259        if (retCode < 0) {
13260            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13261            return false;
13262        }
13263
13264        final int appId = pkg.applicationInfo.uid;
13265        removeKeystoreDataIfNeeded(userId, appId);
13266
13267        // Create a native library symlink only if we have native libraries
13268        // and if the native libraries are 32 bit libraries. We do not provide
13269        // this symlink for 64 bit libraries.
13270        if (pkg.applicationInfo.primaryCpuAbi != null &&
13271                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13272            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13273            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13274                    nativeLibPath, userId) < 0) {
13275                Slog.w(TAG, "Failed linking native library dir");
13276                return false;
13277            }
13278        }
13279
13280        return true;
13281    }
13282
13283    /**
13284     * Reverts user permission state changes (permissions and flags).
13285     *
13286     * @param ps The package for which to reset.
13287     * @param userId The device user for which to do a reset.
13288     */
13289    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13290            final PackageSetting ps, final int userId) {
13291        if (ps.pkg == null) {
13292            return;
13293        }
13294
13295        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13296                | FLAG_PERMISSION_USER_FIXED
13297                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13298
13299        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13300                | FLAG_PERMISSION_POLICY_FIXED;
13301
13302        boolean writeInstallPermissions = false;
13303        boolean writeRuntimePermissions = false;
13304
13305        final int permissionCount = ps.pkg.requestedPermissions.size();
13306        for (int i = 0; i < permissionCount; i++) {
13307            String permission = ps.pkg.requestedPermissions.get(i);
13308
13309            BasePermission bp = mSettings.mPermissions.get(permission);
13310            if (bp == null) {
13311                continue;
13312            }
13313
13314            // If shared user we just reset the state to which only this app contributed.
13315            if (ps.sharedUser != null) {
13316                boolean used = false;
13317                final int packageCount = ps.sharedUser.packages.size();
13318                for (int j = 0; j < packageCount; j++) {
13319                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13320                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13321                            && pkg.pkg.requestedPermissions.contains(permission)) {
13322                        used = true;
13323                        break;
13324                    }
13325                }
13326                if (used) {
13327                    continue;
13328                }
13329            }
13330
13331            PermissionsState permissionsState = ps.getPermissionsState();
13332
13333            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13334
13335            // Always clear the user settable flags.
13336            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13337                    bp.name) != null;
13338            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13339                if (hasInstallState) {
13340                    writeInstallPermissions = true;
13341                } else {
13342                    writeRuntimePermissions = true;
13343                }
13344            }
13345
13346            // Below is only runtime permission handling.
13347            if (!bp.isRuntime()) {
13348                continue;
13349            }
13350
13351            // Never clobber system or policy.
13352            if ((oldFlags & policyOrSystemFlags) != 0) {
13353                continue;
13354            }
13355
13356            // If this permission was granted by default, make sure it is.
13357            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13358                if (permissionsState.grantRuntimePermission(bp, userId)
13359                        != PERMISSION_OPERATION_FAILURE) {
13360                    writeRuntimePermissions = true;
13361                }
13362            } else {
13363                // Otherwise, reset the permission.
13364                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13365                switch (revokeResult) {
13366                    case PERMISSION_OPERATION_SUCCESS: {
13367                        writeRuntimePermissions = true;
13368                    } break;
13369
13370                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13371                        writeRuntimePermissions = true;
13372                        // If gids changed for this user, kill all affected packages.
13373                        mHandler.post(new Runnable() {
13374                            @Override
13375                            public void run() {
13376                                // This has to happen with no lock held.
13377                                killSettingPackagesForUser(ps, userId,
13378                                        KILL_APP_REASON_GIDS_CHANGED);
13379                            }
13380                        });
13381                    } break;
13382                }
13383            }
13384        }
13385
13386        // Synchronously write as we are taking permissions away.
13387        if (writeRuntimePermissions) {
13388            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13389        }
13390
13391        // Synchronously write as we are taking permissions away.
13392        if (writeInstallPermissions) {
13393            mSettings.writeLPr();
13394        }
13395    }
13396
13397    /**
13398     * Remove entries from the keystore daemon. Will only remove it if the
13399     * {@code appId} is valid.
13400     */
13401    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13402        if (appId < 0) {
13403            return;
13404        }
13405
13406        final KeyStore keyStore = KeyStore.getInstance();
13407        if (keyStore != null) {
13408            if (userId == UserHandle.USER_ALL) {
13409                for (final int individual : sUserManager.getUserIds()) {
13410                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13411                }
13412            } else {
13413                keyStore.clearUid(UserHandle.getUid(userId, appId));
13414            }
13415        } else {
13416            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13417        }
13418    }
13419
13420    @Override
13421    public void deleteApplicationCacheFiles(final String packageName,
13422            final IPackageDataObserver observer) {
13423        mContext.enforceCallingOrSelfPermission(
13424                android.Manifest.permission.DELETE_CACHE_FILES, null);
13425        // Queue up an async operation since the package deletion may take a little while.
13426        final int userId = UserHandle.getCallingUserId();
13427        mHandler.post(new Runnable() {
13428            public void run() {
13429                mHandler.removeCallbacks(this);
13430                final boolean succeded;
13431                synchronized (mInstallLock) {
13432                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13433                }
13434                clearExternalStorageDataSync(packageName, userId, false);
13435                if (observer != null) {
13436                    try {
13437                        observer.onRemoveCompleted(packageName, succeded);
13438                    } catch (RemoteException e) {
13439                        Log.i(TAG, "Observer no longer exists.");
13440                    }
13441                } //end if observer
13442            } //end run
13443        });
13444    }
13445
13446    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13447        if (packageName == null) {
13448            Slog.w(TAG, "Attempt to delete null packageName.");
13449            return false;
13450        }
13451        PackageParser.Package p;
13452        synchronized (mPackages) {
13453            p = mPackages.get(packageName);
13454        }
13455        if (p == null) {
13456            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13457            return false;
13458        }
13459        final ApplicationInfo applicationInfo = p.applicationInfo;
13460        if (applicationInfo == null) {
13461            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13462            return false;
13463        }
13464        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13465        if (retCode < 0) {
13466            Slog.w(TAG, "Couldn't remove cache files for package: "
13467                       + packageName + " u" + userId);
13468            return false;
13469        }
13470        return true;
13471    }
13472
13473    @Override
13474    public void getPackageSizeInfo(final String packageName, int userHandle,
13475            final IPackageStatsObserver observer) {
13476        mContext.enforceCallingOrSelfPermission(
13477                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13478        if (packageName == null) {
13479            throw new IllegalArgumentException("Attempt to get size of null packageName");
13480        }
13481
13482        PackageStats stats = new PackageStats(packageName, userHandle);
13483
13484        /*
13485         * Queue up an async operation since the package measurement may take a
13486         * little while.
13487         */
13488        Message msg = mHandler.obtainMessage(INIT_COPY);
13489        msg.obj = new MeasureParams(stats, observer);
13490        mHandler.sendMessage(msg);
13491    }
13492
13493    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13494            PackageStats pStats) {
13495        if (packageName == null) {
13496            Slog.w(TAG, "Attempt to get size of null packageName.");
13497            return false;
13498        }
13499        PackageParser.Package p;
13500        boolean dataOnly = false;
13501        String libDirRoot = null;
13502        String asecPath = null;
13503        PackageSetting ps = null;
13504        synchronized (mPackages) {
13505            p = mPackages.get(packageName);
13506            ps = mSettings.mPackages.get(packageName);
13507            if(p == null) {
13508                dataOnly = true;
13509                if((ps == null) || (ps.pkg == null)) {
13510                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13511                    return false;
13512                }
13513                p = ps.pkg;
13514            }
13515            if (ps != null) {
13516                libDirRoot = ps.legacyNativeLibraryPathString;
13517            }
13518            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13519                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13520                if (secureContainerId != null) {
13521                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13522                }
13523            }
13524        }
13525        String publicSrcDir = null;
13526        if(!dataOnly) {
13527            final ApplicationInfo applicationInfo = p.applicationInfo;
13528            if (applicationInfo == null) {
13529                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13530                return false;
13531            }
13532            if (p.isForwardLocked()) {
13533                publicSrcDir = applicationInfo.getBaseResourcePath();
13534            }
13535        }
13536        // TODO: extend to measure size of split APKs
13537        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13538        // not just the first level.
13539        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13540        // just the primary.
13541        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13542        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13543                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13544        if (res < 0) {
13545            return false;
13546        }
13547
13548        // Fix-up for forward-locked applications in ASEC containers.
13549        if (!isExternal(p)) {
13550            pStats.codeSize += pStats.externalCodeSize;
13551            pStats.externalCodeSize = 0L;
13552        }
13553
13554        return true;
13555    }
13556
13557
13558    @Override
13559    public void addPackageToPreferred(String packageName) {
13560        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13561    }
13562
13563    @Override
13564    public void removePackageFromPreferred(String packageName) {
13565        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13566    }
13567
13568    @Override
13569    public List<PackageInfo> getPreferredPackages(int flags) {
13570        return new ArrayList<PackageInfo>();
13571    }
13572
13573    private int getUidTargetSdkVersionLockedLPr(int uid) {
13574        Object obj = mSettings.getUserIdLPr(uid);
13575        if (obj instanceof SharedUserSetting) {
13576            final SharedUserSetting sus = (SharedUserSetting) obj;
13577            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13578            final Iterator<PackageSetting> it = sus.packages.iterator();
13579            while (it.hasNext()) {
13580                final PackageSetting ps = it.next();
13581                if (ps.pkg != null) {
13582                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13583                    if (v < vers) vers = v;
13584                }
13585            }
13586            return vers;
13587        } else if (obj instanceof PackageSetting) {
13588            final PackageSetting ps = (PackageSetting) obj;
13589            if (ps.pkg != null) {
13590                return ps.pkg.applicationInfo.targetSdkVersion;
13591            }
13592        }
13593        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13594    }
13595
13596    @Override
13597    public void addPreferredActivity(IntentFilter filter, int match,
13598            ComponentName[] set, ComponentName activity, int userId) {
13599        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13600                "Adding preferred");
13601    }
13602
13603    private void addPreferredActivityInternal(IntentFilter filter, int match,
13604            ComponentName[] set, ComponentName activity, boolean always, int userId,
13605            String opname) {
13606        // writer
13607        int callingUid = Binder.getCallingUid();
13608        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13609        if (filter.countActions() == 0) {
13610            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13611            return;
13612        }
13613        synchronized (mPackages) {
13614            if (mContext.checkCallingOrSelfPermission(
13615                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13616                    != PackageManager.PERMISSION_GRANTED) {
13617                if (getUidTargetSdkVersionLockedLPr(callingUid)
13618                        < Build.VERSION_CODES.FROYO) {
13619                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13620                            + callingUid);
13621                    return;
13622                }
13623                mContext.enforceCallingOrSelfPermission(
13624                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13625            }
13626
13627            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13628            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13629                    + userId + ":");
13630            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13631            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13632            scheduleWritePackageRestrictionsLocked(userId);
13633        }
13634    }
13635
13636    @Override
13637    public void replacePreferredActivity(IntentFilter filter, int match,
13638            ComponentName[] set, ComponentName activity, int userId) {
13639        if (filter.countActions() != 1) {
13640            throw new IllegalArgumentException(
13641                    "replacePreferredActivity expects filter to have only 1 action.");
13642        }
13643        if (filter.countDataAuthorities() != 0
13644                || filter.countDataPaths() != 0
13645                || filter.countDataSchemes() > 1
13646                || filter.countDataTypes() != 0) {
13647            throw new IllegalArgumentException(
13648                    "replacePreferredActivity expects filter to have no data authorities, " +
13649                    "paths, or types; and at most one scheme.");
13650        }
13651
13652        final int callingUid = Binder.getCallingUid();
13653        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13654        synchronized (mPackages) {
13655            if (mContext.checkCallingOrSelfPermission(
13656                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13657                    != PackageManager.PERMISSION_GRANTED) {
13658                if (getUidTargetSdkVersionLockedLPr(callingUid)
13659                        < Build.VERSION_CODES.FROYO) {
13660                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13661                            + Binder.getCallingUid());
13662                    return;
13663                }
13664                mContext.enforceCallingOrSelfPermission(
13665                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13666            }
13667
13668            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13669            if (pir != null) {
13670                // Get all of the existing entries that exactly match this filter.
13671                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13672                if (existing != null && existing.size() == 1) {
13673                    PreferredActivity cur = existing.get(0);
13674                    if (DEBUG_PREFERRED) {
13675                        Slog.i(TAG, "Checking replace of preferred:");
13676                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13677                        if (!cur.mPref.mAlways) {
13678                            Slog.i(TAG, "  -- CUR; not mAlways!");
13679                        } else {
13680                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13681                            Slog.i(TAG, "  -- CUR: mSet="
13682                                    + Arrays.toString(cur.mPref.mSetComponents));
13683                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13684                            Slog.i(TAG, "  -- NEW: mMatch="
13685                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13686                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13687                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13688                        }
13689                    }
13690                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13691                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13692                            && cur.mPref.sameSet(set)) {
13693                        // Setting the preferred activity to what it happens to be already
13694                        if (DEBUG_PREFERRED) {
13695                            Slog.i(TAG, "Replacing with same preferred activity "
13696                                    + cur.mPref.mShortComponent + " for user "
13697                                    + userId + ":");
13698                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13699                        }
13700                        return;
13701                    }
13702                }
13703
13704                if (existing != null) {
13705                    if (DEBUG_PREFERRED) {
13706                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13707                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13708                    }
13709                    for (int i = 0; i < existing.size(); i++) {
13710                        PreferredActivity pa = existing.get(i);
13711                        if (DEBUG_PREFERRED) {
13712                            Slog.i(TAG, "Removing existing preferred activity "
13713                                    + pa.mPref.mComponent + ":");
13714                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13715                        }
13716                        pir.removeFilter(pa);
13717                    }
13718                }
13719            }
13720            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13721                    "Replacing preferred");
13722        }
13723    }
13724
13725    @Override
13726    public void clearPackagePreferredActivities(String packageName) {
13727        final int uid = Binder.getCallingUid();
13728        // writer
13729        synchronized (mPackages) {
13730            PackageParser.Package pkg = mPackages.get(packageName);
13731            if (pkg == null || pkg.applicationInfo.uid != uid) {
13732                if (mContext.checkCallingOrSelfPermission(
13733                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13734                        != PackageManager.PERMISSION_GRANTED) {
13735                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13736                            < Build.VERSION_CODES.FROYO) {
13737                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13738                                + Binder.getCallingUid());
13739                        return;
13740                    }
13741                    mContext.enforceCallingOrSelfPermission(
13742                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13743                }
13744            }
13745
13746            int user = UserHandle.getCallingUserId();
13747            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13748                scheduleWritePackageRestrictionsLocked(user);
13749            }
13750        }
13751    }
13752
13753    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13754    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13755        ArrayList<PreferredActivity> removed = null;
13756        boolean changed = false;
13757        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13758            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13759            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13760            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13761                continue;
13762            }
13763            Iterator<PreferredActivity> it = pir.filterIterator();
13764            while (it.hasNext()) {
13765                PreferredActivity pa = it.next();
13766                // Mark entry for removal only if it matches the package name
13767                // and the entry is of type "always".
13768                if (packageName == null ||
13769                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13770                                && pa.mPref.mAlways)) {
13771                    if (removed == null) {
13772                        removed = new ArrayList<PreferredActivity>();
13773                    }
13774                    removed.add(pa);
13775                }
13776            }
13777            if (removed != null) {
13778                for (int j=0; j<removed.size(); j++) {
13779                    PreferredActivity pa = removed.get(j);
13780                    pir.removeFilter(pa);
13781                }
13782                changed = true;
13783            }
13784        }
13785        return changed;
13786    }
13787
13788    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13789    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13790        if (userId == UserHandle.USER_ALL) {
13791            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13792                    sUserManager.getUserIds())) {
13793                for (int oneUserId : sUserManager.getUserIds()) {
13794                    scheduleWritePackageRestrictionsLocked(oneUserId);
13795                }
13796            }
13797        } else {
13798            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13799                scheduleWritePackageRestrictionsLocked(userId);
13800            }
13801        }
13802    }
13803
13804
13805    void clearDefaultBrowserIfNeeded(String packageName) {
13806        for (int oneUserId : sUserManager.getUserIds()) {
13807            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13808            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13809            if (packageName.equals(defaultBrowserPackageName)) {
13810                setDefaultBrowserPackageName(null, oneUserId);
13811            }
13812        }
13813    }
13814
13815    @Override
13816    public void resetPreferredActivities(int userId) {
13817        mContext.enforceCallingOrSelfPermission(
13818                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13819        // writer
13820        synchronized (mPackages) {
13821            clearPackagePreferredActivitiesLPw(null, userId);
13822            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13823            applyFactoryDefaultBrowserLPw(userId);
13824            primeDomainVerificationsLPw(userId);
13825
13826            scheduleWritePackageRestrictionsLocked(userId);
13827        }
13828    }
13829
13830    @Override
13831    public int getPreferredActivities(List<IntentFilter> outFilters,
13832            List<ComponentName> outActivities, String packageName) {
13833
13834        int num = 0;
13835        final int userId = UserHandle.getCallingUserId();
13836        // reader
13837        synchronized (mPackages) {
13838            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13839            if (pir != null) {
13840                final Iterator<PreferredActivity> it = pir.filterIterator();
13841                while (it.hasNext()) {
13842                    final PreferredActivity pa = it.next();
13843                    if (packageName == null
13844                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13845                                    && pa.mPref.mAlways)) {
13846                        if (outFilters != null) {
13847                            outFilters.add(new IntentFilter(pa));
13848                        }
13849                        if (outActivities != null) {
13850                            outActivities.add(pa.mPref.mComponent);
13851                        }
13852                    }
13853                }
13854            }
13855        }
13856
13857        return num;
13858    }
13859
13860    @Override
13861    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13862            int userId) {
13863        int callingUid = Binder.getCallingUid();
13864        if (callingUid != Process.SYSTEM_UID) {
13865            throw new SecurityException(
13866                    "addPersistentPreferredActivity can only be run by the system");
13867        }
13868        if (filter.countActions() == 0) {
13869            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13870            return;
13871        }
13872        synchronized (mPackages) {
13873            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13874                    " :");
13875            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13876            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13877                    new PersistentPreferredActivity(filter, activity));
13878            scheduleWritePackageRestrictionsLocked(userId);
13879        }
13880    }
13881
13882    @Override
13883    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13884        int callingUid = Binder.getCallingUid();
13885        if (callingUid != Process.SYSTEM_UID) {
13886            throw new SecurityException(
13887                    "clearPackagePersistentPreferredActivities can only be run by the system");
13888        }
13889        ArrayList<PersistentPreferredActivity> removed = null;
13890        boolean changed = false;
13891        synchronized (mPackages) {
13892            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13893                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13894                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13895                        .valueAt(i);
13896                if (userId != thisUserId) {
13897                    continue;
13898                }
13899                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13900                while (it.hasNext()) {
13901                    PersistentPreferredActivity ppa = it.next();
13902                    // Mark entry for removal only if it matches the package name.
13903                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13904                        if (removed == null) {
13905                            removed = new ArrayList<PersistentPreferredActivity>();
13906                        }
13907                        removed.add(ppa);
13908                    }
13909                }
13910                if (removed != null) {
13911                    for (int j=0; j<removed.size(); j++) {
13912                        PersistentPreferredActivity ppa = removed.get(j);
13913                        ppir.removeFilter(ppa);
13914                    }
13915                    changed = true;
13916                }
13917            }
13918
13919            if (changed) {
13920                scheduleWritePackageRestrictionsLocked(userId);
13921            }
13922        }
13923    }
13924
13925    /**
13926     * Common machinery for picking apart a restored XML blob and passing
13927     * it to a caller-supplied functor to be applied to the running system.
13928     */
13929    private void restoreFromXml(XmlPullParser parser, int userId,
13930            String expectedStartTag, BlobXmlRestorer functor)
13931            throws IOException, XmlPullParserException {
13932        int type;
13933        while ((type = parser.next()) != XmlPullParser.START_TAG
13934                && type != XmlPullParser.END_DOCUMENT) {
13935        }
13936        if (type != XmlPullParser.START_TAG) {
13937            // oops didn't find a start tag?!
13938            if (DEBUG_BACKUP) {
13939                Slog.e(TAG, "Didn't find start tag during restore");
13940            }
13941            return;
13942        }
13943
13944        // this is supposed to be TAG_PREFERRED_BACKUP
13945        if (!expectedStartTag.equals(parser.getName())) {
13946            if (DEBUG_BACKUP) {
13947                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13948            }
13949            return;
13950        }
13951
13952        // skip interfering stuff, then we're aligned with the backing implementation
13953        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13954        functor.apply(parser, userId);
13955    }
13956
13957    private interface BlobXmlRestorer {
13958        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13959    }
13960
13961    /**
13962     * Non-Binder method, support for the backup/restore mechanism: write the
13963     * full set of preferred activities in its canonical XML format.  Returns the
13964     * XML output as a byte array, or null if there is none.
13965     */
13966    @Override
13967    public byte[] getPreferredActivityBackup(int userId) {
13968        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13969            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13970        }
13971
13972        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13973        try {
13974            final XmlSerializer serializer = new FastXmlSerializer();
13975            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13976            serializer.startDocument(null, true);
13977            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13978
13979            synchronized (mPackages) {
13980                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13981            }
13982
13983            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13984            serializer.endDocument();
13985            serializer.flush();
13986        } catch (Exception e) {
13987            if (DEBUG_BACKUP) {
13988                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13989            }
13990            return null;
13991        }
13992
13993        return dataStream.toByteArray();
13994    }
13995
13996    @Override
13997    public void restorePreferredActivities(byte[] backup, int userId) {
13998        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13999            throw new SecurityException("Only the system may call restorePreferredActivities()");
14000        }
14001
14002        try {
14003            final XmlPullParser parser = Xml.newPullParser();
14004            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14005            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14006                    new BlobXmlRestorer() {
14007                        @Override
14008                        public void apply(XmlPullParser parser, int userId)
14009                                throws XmlPullParserException, IOException {
14010                            synchronized (mPackages) {
14011                                mSettings.readPreferredActivitiesLPw(parser, userId);
14012                            }
14013                        }
14014                    } );
14015        } catch (Exception e) {
14016            if (DEBUG_BACKUP) {
14017                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14018            }
14019        }
14020    }
14021
14022    /**
14023     * Non-Binder method, support for the backup/restore mechanism: write the
14024     * default browser (etc) settings in its canonical XML format.  Returns the default
14025     * browser XML representation as a byte array, or null if there is none.
14026     */
14027    @Override
14028    public byte[] getDefaultAppsBackup(int userId) {
14029        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14030            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14031        }
14032
14033        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14034        try {
14035            final XmlSerializer serializer = new FastXmlSerializer();
14036            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14037            serializer.startDocument(null, true);
14038            serializer.startTag(null, TAG_DEFAULT_APPS);
14039
14040            synchronized (mPackages) {
14041                mSettings.writeDefaultAppsLPr(serializer, userId);
14042            }
14043
14044            serializer.endTag(null, TAG_DEFAULT_APPS);
14045            serializer.endDocument();
14046            serializer.flush();
14047        } catch (Exception e) {
14048            if (DEBUG_BACKUP) {
14049                Slog.e(TAG, "Unable to write default apps for backup", e);
14050            }
14051            return null;
14052        }
14053
14054        return dataStream.toByteArray();
14055    }
14056
14057    @Override
14058    public void restoreDefaultApps(byte[] backup, int userId) {
14059        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14060            throw new SecurityException("Only the system may call restoreDefaultApps()");
14061        }
14062
14063        try {
14064            final XmlPullParser parser = Xml.newPullParser();
14065            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14066            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14067                    new BlobXmlRestorer() {
14068                        @Override
14069                        public void apply(XmlPullParser parser, int userId)
14070                                throws XmlPullParserException, IOException {
14071                            synchronized (mPackages) {
14072                                mSettings.readDefaultAppsLPw(parser, userId);
14073                            }
14074                        }
14075                    } );
14076        } catch (Exception e) {
14077            if (DEBUG_BACKUP) {
14078                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14079            }
14080        }
14081    }
14082
14083    @Override
14084    public byte[] getIntentFilterVerificationBackup(int userId) {
14085        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14086            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14087        }
14088
14089        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14090        try {
14091            final XmlSerializer serializer = new FastXmlSerializer();
14092            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14093            serializer.startDocument(null, true);
14094            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14095
14096            synchronized (mPackages) {
14097                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14098            }
14099
14100            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14101            serializer.endDocument();
14102            serializer.flush();
14103        } catch (Exception e) {
14104            if (DEBUG_BACKUP) {
14105                Slog.e(TAG, "Unable to write default apps for backup", e);
14106            }
14107            return null;
14108        }
14109
14110        return dataStream.toByteArray();
14111    }
14112
14113    @Override
14114    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14115        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14116            throw new SecurityException("Only the system may call restorePreferredActivities()");
14117        }
14118
14119        try {
14120            final XmlPullParser parser = Xml.newPullParser();
14121            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14122            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14123                    new BlobXmlRestorer() {
14124                        @Override
14125                        public void apply(XmlPullParser parser, int userId)
14126                                throws XmlPullParserException, IOException {
14127                            synchronized (mPackages) {
14128                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14129                                mSettings.writeLPr();
14130                            }
14131                        }
14132                    } );
14133        } catch (Exception e) {
14134            if (DEBUG_BACKUP) {
14135                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14136            }
14137        }
14138    }
14139
14140    @Override
14141    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14142            int sourceUserId, int targetUserId, int flags) {
14143        mContext.enforceCallingOrSelfPermission(
14144                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14145        int callingUid = Binder.getCallingUid();
14146        enforceOwnerRights(ownerPackage, callingUid);
14147        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14148        if (intentFilter.countActions() == 0) {
14149            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14150            return;
14151        }
14152        synchronized (mPackages) {
14153            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14154                    ownerPackage, targetUserId, flags);
14155            CrossProfileIntentResolver resolver =
14156                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14157            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14158            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14159            if (existing != null) {
14160                int size = existing.size();
14161                for (int i = 0; i < size; i++) {
14162                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14163                        return;
14164                    }
14165                }
14166            }
14167            resolver.addFilter(newFilter);
14168            scheduleWritePackageRestrictionsLocked(sourceUserId);
14169        }
14170    }
14171
14172    @Override
14173    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14174        mContext.enforceCallingOrSelfPermission(
14175                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14176        int callingUid = Binder.getCallingUid();
14177        enforceOwnerRights(ownerPackage, callingUid);
14178        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14179        synchronized (mPackages) {
14180            CrossProfileIntentResolver resolver =
14181                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14182            ArraySet<CrossProfileIntentFilter> set =
14183                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14184            for (CrossProfileIntentFilter filter : set) {
14185                if (filter.getOwnerPackage().equals(ownerPackage)) {
14186                    resolver.removeFilter(filter);
14187                }
14188            }
14189            scheduleWritePackageRestrictionsLocked(sourceUserId);
14190        }
14191    }
14192
14193    // Enforcing that callingUid is owning pkg on userId
14194    private void enforceOwnerRights(String pkg, int callingUid) {
14195        // The system owns everything.
14196        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14197            return;
14198        }
14199        int callingUserId = UserHandle.getUserId(callingUid);
14200        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14201        if (pi == null) {
14202            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14203                    + callingUserId);
14204        }
14205        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14206            throw new SecurityException("Calling uid " + callingUid
14207                    + " does not own package " + pkg);
14208        }
14209    }
14210
14211    @Override
14212    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14213        Intent intent = new Intent(Intent.ACTION_MAIN);
14214        intent.addCategory(Intent.CATEGORY_HOME);
14215
14216        final int callingUserId = UserHandle.getCallingUserId();
14217        List<ResolveInfo> list = queryIntentActivities(intent, null,
14218                PackageManager.GET_META_DATA, callingUserId);
14219        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14220                true, false, false, callingUserId);
14221
14222        allHomeCandidates.clear();
14223        if (list != null) {
14224            for (ResolveInfo ri : list) {
14225                allHomeCandidates.add(ri);
14226            }
14227        }
14228        return (preferred == null || preferred.activityInfo == null)
14229                ? null
14230                : new ComponentName(preferred.activityInfo.packageName,
14231                        preferred.activityInfo.name);
14232    }
14233
14234    @Override
14235    public void setApplicationEnabledSetting(String appPackageName,
14236            int newState, int flags, int userId, String callingPackage) {
14237        if (!sUserManager.exists(userId)) return;
14238        if (callingPackage == null) {
14239            callingPackage = Integer.toString(Binder.getCallingUid());
14240        }
14241        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14242    }
14243
14244    @Override
14245    public void setComponentEnabledSetting(ComponentName componentName,
14246            int newState, int flags, int userId) {
14247        if (!sUserManager.exists(userId)) return;
14248        setEnabledSetting(componentName.getPackageName(),
14249                componentName.getClassName(), newState, flags, userId, null);
14250    }
14251
14252    private void setEnabledSetting(final String packageName, String className, int newState,
14253            final int flags, int userId, String callingPackage) {
14254        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14255              || newState == COMPONENT_ENABLED_STATE_ENABLED
14256              || newState == COMPONENT_ENABLED_STATE_DISABLED
14257              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14258              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14259            throw new IllegalArgumentException("Invalid new component state: "
14260                    + newState);
14261        }
14262        PackageSetting pkgSetting;
14263        final int uid = Binder.getCallingUid();
14264        final int permission = mContext.checkCallingOrSelfPermission(
14265                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14266        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14267        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14268        boolean sendNow = false;
14269        boolean isApp = (className == null);
14270        String componentName = isApp ? packageName : className;
14271        int packageUid = -1;
14272        ArrayList<String> components;
14273
14274        // writer
14275        synchronized (mPackages) {
14276            pkgSetting = mSettings.mPackages.get(packageName);
14277            if (pkgSetting == null) {
14278                if (className == null) {
14279                    throw new IllegalArgumentException(
14280                            "Unknown package: " + packageName);
14281                }
14282                throw new IllegalArgumentException(
14283                        "Unknown component: " + packageName
14284                        + "/" + className);
14285            }
14286            // Allow root and verify that userId is not being specified by a different user
14287            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14288                throw new SecurityException(
14289                        "Permission Denial: attempt to change component state from pid="
14290                        + Binder.getCallingPid()
14291                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14292            }
14293            if (className == null) {
14294                // We're dealing with an application/package level state change
14295                if (pkgSetting.getEnabled(userId) == newState) {
14296                    // Nothing to do
14297                    return;
14298                }
14299                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14300                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14301                    // Don't care about who enables an app.
14302                    callingPackage = null;
14303                }
14304                pkgSetting.setEnabled(newState, userId, callingPackage);
14305                // pkgSetting.pkg.mSetEnabled = newState;
14306            } else {
14307                // We're dealing with a component level state change
14308                // First, verify that this is a valid class name.
14309                PackageParser.Package pkg = pkgSetting.pkg;
14310                if (pkg == null || !pkg.hasComponentClassName(className)) {
14311                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14312                        throw new IllegalArgumentException("Component class " + className
14313                                + " does not exist in " + packageName);
14314                    } else {
14315                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14316                                + className + " does not exist in " + packageName);
14317                    }
14318                }
14319                switch (newState) {
14320                case COMPONENT_ENABLED_STATE_ENABLED:
14321                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14322                        return;
14323                    }
14324                    break;
14325                case COMPONENT_ENABLED_STATE_DISABLED:
14326                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14327                        return;
14328                    }
14329                    break;
14330                case COMPONENT_ENABLED_STATE_DEFAULT:
14331                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14332                        return;
14333                    }
14334                    break;
14335                default:
14336                    Slog.e(TAG, "Invalid new component state: " + newState);
14337                    return;
14338                }
14339            }
14340            scheduleWritePackageRestrictionsLocked(userId);
14341            components = mPendingBroadcasts.get(userId, packageName);
14342            final boolean newPackage = components == null;
14343            if (newPackage) {
14344                components = new ArrayList<String>();
14345            }
14346            if (!components.contains(componentName)) {
14347                components.add(componentName);
14348            }
14349            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14350                sendNow = true;
14351                // Purge entry from pending broadcast list if another one exists already
14352                // since we are sending one right away.
14353                mPendingBroadcasts.remove(userId, packageName);
14354            } else {
14355                if (newPackage) {
14356                    mPendingBroadcasts.put(userId, packageName, components);
14357                }
14358                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14359                    // Schedule a message
14360                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14361                }
14362            }
14363        }
14364
14365        long callingId = Binder.clearCallingIdentity();
14366        try {
14367            if (sendNow) {
14368                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14369                sendPackageChangedBroadcast(packageName,
14370                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14371            }
14372        } finally {
14373            Binder.restoreCallingIdentity(callingId);
14374        }
14375    }
14376
14377    private void sendPackageChangedBroadcast(String packageName,
14378            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14379        if (DEBUG_INSTALL)
14380            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14381                    + componentNames);
14382        Bundle extras = new Bundle(4);
14383        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14384        String nameList[] = new String[componentNames.size()];
14385        componentNames.toArray(nameList);
14386        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14387        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14388        extras.putInt(Intent.EXTRA_UID, packageUid);
14389        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14390                new int[] {UserHandle.getUserId(packageUid)});
14391    }
14392
14393    @Override
14394    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14395        if (!sUserManager.exists(userId)) return;
14396        final int uid = Binder.getCallingUid();
14397        final int permission = mContext.checkCallingOrSelfPermission(
14398                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14399        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14400        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14401        // writer
14402        synchronized (mPackages) {
14403            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14404                    allowedByPermission, uid, userId)) {
14405                scheduleWritePackageRestrictionsLocked(userId);
14406            }
14407        }
14408    }
14409
14410    @Override
14411    public String getInstallerPackageName(String packageName) {
14412        // reader
14413        synchronized (mPackages) {
14414            return mSettings.getInstallerPackageNameLPr(packageName);
14415        }
14416    }
14417
14418    @Override
14419    public int getApplicationEnabledSetting(String packageName, int userId) {
14420        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14421        int uid = Binder.getCallingUid();
14422        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14423        // reader
14424        synchronized (mPackages) {
14425            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14426        }
14427    }
14428
14429    @Override
14430    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14431        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14432        int uid = Binder.getCallingUid();
14433        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14434        // reader
14435        synchronized (mPackages) {
14436            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14437        }
14438    }
14439
14440    @Override
14441    public void enterSafeMode() {
14442        enforceSystemOrRoot("Only the system can request entering safe mode");
14443
14444        if (!mSystemReady) {
14445            mSafeMode = true;
14446        }
14447    }
14448
14449    @Override
14450    public void systemReady() {
14451        mSystemReady = true;
14452
14453        // Read the compatibilty setting when the system is ready.
14454        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14455                mContext.getContentResolver(),
14456                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14457        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14458        if (DEBUG_SETTINGS) {
14459            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14460        }
14461
14462        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14463
14464        synchronized (mPackages) {
14465            // Verify that all of the preferred activity components actually
14466            // exist.  It is possible for applications to be updated and at
14467            // that point remove a previously declared activity component that
14468            // had been set as a preferred activity.  We try to clean this up
14469            // the next time we encounter that preferred activity, but it is
14470            // possible for the user flow to never be able to return to that
14471            // situation so here we do a sanity check to make sure we haven't
14472            // left any junk around.
14473            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14474            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14475                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14476                removed.clear();
14477                for (PreferredActivity pa : pir.filterSet()) {
14478                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14479                        removed.add(pa);
14480                    }
14481                }
14482                if (removed.size() > 0) {
14483                    for (int r=0; r<removed.size(); r++) {
14484                        PreferredActivity pa = removed.get(r);
14485                        Slog.w(TAG, "Removing dangling preferred activity: "
14486                                + pa.mPref.mComponent);
14487                        pir.removeFilter(pa);
14488                    }
14489                    mSettings.writePackageRestrictionsLPr(
14490                            mSettings.mPreferredActivities.keyAt(i));
14491                }
14492            }
14493
14494            for (int userId : UserManagerService.getInstance().getUserIds()) {
14495                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14496                    grantPermissionsUserIds = ArrayUtils.appendInt(
14497                            grantPermissionsUserIds, userId);
14498                }
14499            }
14500        }
14501        sUserManager.systemReady();
14502
14503        // If we upgraded grant all default permissions before kicking off.
14504        for (int userId : grantPermissionsUserIds) {
14505            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14506        }
14507
14508        // Kick off any messages waiting for system ready
14509        if (mPostSystemReadyMessages != null) {
14510            for (Message msg : mPostSystemReadyMessages) {
14511                msg.sendToTarget();
14512            }
14513            mPostSystemReadyMessages = null;
14514        }
14515
14516        // Watch for external volumes that come and go over time
14517        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14518        storage.registerListener(mStorageListener);
14519
14520        mInstallerService.systemReady();
14521        mPackageDexOptimizer.systemReady();
14522
14523        MountServiceInternal mountServiceInternal = LocalServices.getService(
14524                MountServiceInternal.class);
14525        mountServiceInternal.addExternalStoragePolicy(
14526                new MountServiceInternal.ExternalStorageMountPolicy() {
14527            @Override
14528            public int getMountMode(int uid, String packageName) {
14529                if (Process.isIsolated(uid)) {
14530                    return Zygote.MOUNT_EXTERNAL_NONE;
14531                }
14532                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14533                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14534                }
14535                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14536                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14537                }
14538                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14539                    return Zygote.MOUNT_EXTERNAL_READ;
14540                }
14541                return Zygote.MOUNT_EXTERNAL_WRITE;
14542            }
14543
14544            @Override
14545            public boolean hasExternalStorage(int uid, String packageName) {
14546                return true;
14547            }
14548        });
14549    }
14550
14551    @Override
14552    public boolean isSafeMode() {
14553        return mSafeMode;
14554    }
14555
14556    @Override
14557    public boolean hasSystemUidErrors() {
14558        return mHasSystemUidErrors;
14559    }
14560
14561    static String arrayToString(int[] array) {
14562        StringBuffer buf = new StringBuffer(128);
14563        buf.append('[');
14564        if (array != null) {
14565            for (int i=0; i<array.length; i++) {
14566                if (i > 0) buf.append(", ");
14567                buf.append(array[i]);
14568            }
14569        }
14570        buf.append(']');
14571        return buf.toString();
14572    }
14573
14574    static class DumpState {
14575        public static final int DUMP_LIBS = 1 << 0;
14576        public static final int DUMP_FEATURES = 1 << 1;
14577        public static final int DUMP_RESOLVERS = 1 << 2;
14578        public static final int DUMP_PERMISSIONS = 1 << 3;
14579        public static final int DUMP_PACKAGES = 1 << 4;
14580        public static final int DUMP_SHARED_USERS = 1 << 5;
14581        public static final int DUMP_MESSAGES = 1 << 6;
14582        public static final int DUMP_PROVIDERS = 1 << 7;
14583        public static final int DUMP_VERIFIERS = 1 << 8;
14584        public static final int DUMP_PREFERRED = 1 << 9;
14585        public static final int DUMP_PREFERRED_XML = 1 << 10;
14586        public static final int DUMP_KEYSETS = 1 << 11;
14587        public static final int DUMP_VERSION = 1 << 12;
14588        public static final int DUMP_INSTALLS = 1 << 13;
14589        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14590        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14591
14592        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14593
14594        private int mTypes;
14595
14596        private int mOptions;
14597
14598        private boolean mTitlePrinted;
14599
14600        private SharedUserSetting mSharedUser;
14601
14602        public boolean isDumping(int type) {
14603            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14604                return true;
14605            }
14606
14607            return (mTypes & type) != 0;
14608        }
14609
14610        public void setDump(int type) {
14611            mTypes |= type;
14612        }
14613
14614        public boolean isOptionEnabled(int option) {
14615            return (mOptions & option) != 0;
14616        }
14617
14618        public void setOptionEnabled(int option) {
14619            mOptions |= option;
14620        }
14621
14622        public boolean onTitlePrinted() {
14623            final boolean printed = mTitlePrinted;
14624            mTitlePrinted = true;
14625            return printed;
14626        }
14627
14628        public boolean getTitlePrinted() {
14629            return mTitlePrinted;
14630        }
14631
14632        public void setTitlePrinted(boolean enabled) {
14633            mTitlePrinted = enabled;
14634        }
14635
14636        public SharedUserSetting getSharedUser() {
14637            return mSharedUser;
14638        }
14639
14640        public void setSharedUser(SharedUserSetting user) {
14641            mSharedUser = user;
14642        }
14643    }
14644
14645    @Override
14646    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14647        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14648                != PackageManager.PERMISSION_GRANTED) {
14649            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14650                    + Binder.getCallingPid()
14651                    + ", uid=" + Binder.getCallingUid()
14652                    + " without permission "
14653                    + android.Manifest.permission.DUMP);
14654            return;
14655        }
14656
14657        DumpState dumpState = new DumpState();
14658        boolean fullPreferred = false;
14659        boolean checkin = false;
14660
14661        String packageName = null;
14662        ArraySet<String> permissionNames = null;
14663
14664        int opti = 0;
14665        while (opti < args.length) {
14666            String opt = args[opti];
14667            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14668                break;
14669            }
14670            opti++;
14671
14672            if ("-a".equals(opt)) {
14673                // Right now we only know how to print all.
14674            } else if ("-h".equals(opt)) {
14675                pw.println("Package manager dump options:");
14676                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14677                pw.println("    --checkin: dump for a checkin");
14678                pw.println("    -f: print details of intent filters");
14679                pw.println("    -h: print this help");
14680                pw.println("  cmd may be one of:");
14681                pw.println("    l[ibraries]: list known shared libraries");
14682                pw.println("    f[ibraries]: list device features");
14683                pw.println("    k[eysets]: print known keysets");
14684                pw.println("    r[esolvers]: dump intent resolvers");
14685                pw.println("    perm[issions]: dump permissions");
14686                pw.println("    permission [name ...]: dump declaration and use of given permission");
14687                pw.println("    pref[erred]: print preferred package settings");
14688                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14689                pw.println("    prov[iders]: dump content providers");
14690                pw.println("    p[ackages]: dump installed packages");
14691                pw.println("    s[hared-users]: dump shared user IDs");
14692                pw.println("    m[essages]: print collected runtime messages");
14693                pw.println("    v[erifiers]: print package verifier info");
14694                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14695                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14696                pw.println("    version: print database version info");
14697                pw.println("    write: write current settings now");
14698                pw.println("    installs: details about install sessions");
14699                pw.println("    <package.name>: info about given package");
14700                return;
14701            } else if ("--checkin".equals(opt)) {
14702                checkin = true;
14703            } else if ("-f".equals(opt)) {
14704                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14705            } else {
14706                pw.println("Unknown argument: " + opt + "; use -h for help");
14707            }
14708        }
14709
14710        // Is the caller requesting to dump a particular piece of data?
14711        if (opti < args.length) {
14712            String cmd = args[opti];
14713            opti++;
14714            // Is this a package name?
14715            if ("android".equals(cmd) || cmd.contains(".")) {
14716                packageName = cmd;
14717                // When dumping a single package, we always dump all of its
14718                // filter information since the amount of data will be reasonable.
14719                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14720            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14721                dumpState.setDump(DumpState.DUMP_LIBS);
14722            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14723                dumpState.setDump(DumpState.DUMP_FEATURES);
14724            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14725                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14726            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14727                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14728            } else if ("permission".equals(cmd)) {
14729                if (opti >= args.length) {
14730                    pw.println("Error: permission requires permission name");
14731                    return;
14732                }
14733                permissionNames = new ArraySet<>();
14734                while (opti < args.length) {
14735                    permissionNames.add(args[opti]);
14736                    opti++;
14737                }
14738                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14739                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14740            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14741                dumpState.setDump(DumpState.DUMP_PREFERRED);
14742            } else if ("preferred-xml".equals(cmd)) {
14743                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14744                if (opti < args.length && "--full".equals(args[opti])) {
14745                    fullPreferred = true;
14746                    opti++;
14747                }
14748            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14749                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14750            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14751                dumpState.setDump(DumpState.DUMP_PACKAGES);
14752            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14753                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14754            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14755                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14756            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14757                dumpState.setDump(DumpState.DUMP_MESSAGES);
14758            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14759                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14760            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14761                    || "intent-filter-verifiers".equals(cmd)) {
14762                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14763            } else if ("version".equals(cmd)) {
14764                dumpState.setDump(DumpState.DUMP_VERSION);
14765            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14766                dumpState.setDump(DumpState.DUMP_KEYSETS);
14767            } else if ("installs".equals(cmd)) {
14768                dumpState.setDump(DumpState.DUMP_INSTALLS);
14769            } else if ("write".equals(cmd)) {
14770                synchronized (mPackages) {
14771                    mSettings.writeLPr();
14772                    pw.println("Settings written.");
14773                    return;
14774                }
14775            }
14776        }
14777
14778        if (checkin) {
14779            pw.println("vers,1");
14780        }
14781
14782        // reader
14783        synchronized (mPackages) {
14784            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14785                if (!checkin) {
14786                    if (dumpState.onTitlePrinted())
14787                        pw.println();
14788                    pw.println("Database versions:");
14789                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14790                }
14791            }
14792
14793            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14794                if (!checkin) {
14795                    if (dumpState.onTitlePrinted())
14796                        pw.println();
14797                    pw.println("Verifiers:");
14798                    pw.print("  Required: ");
14799                    pw.print(mRequiredVerifierPackage);
14800                    pw.print(" (uid=");
14801                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14802                    pw.println(")");
14803                } else if (mRequiredVerifierPackage != null) {
14804                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14805                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14806                }
14807            }
14808
14809            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14810                    packageName == null) {
14811                if (mIntentFilterVerifierComponent != null) {
14812                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14813                    if (!checkin) {
14814                        if (dumpState.onTitlePrinted())
14815                            pw.println();
14816                        pw.println("Intent Filter Verifier:");
14817                        pw.print("  Using: ");
14818                        pw.print(verifierPackageName);
14819                        pw.print(" (uid=");
14820                        pw.print(getPackageUid(verifierPackageName, 0));
14821                        pw.println(")");
14822                    } else if (verifierPackageName != null) {
14823                        pw.print("ifv,"); pw.print(verifierPackageName);
14824                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14825                    }
14826                } else {
14827                    pw.println();
14828                    pw.println("No Intent Filter Verifier available!");
14829                }
14830            }
14831
14832            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14833                boolean printedHeader = false;
14834                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14835                while (it.hasNext()) {
14836                    String name = it.next();
14837                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14838                    if (!checkin) {
14839                        if (!printedHeader) {
14840                            if (dumpState.onTitlePrinted())
14841                                pw.println();
14842                            pw.println("Libraries:");
14843                            printedHeader = true;
14844                        }
14845                        pw.print("  ");
14846                    } else {
14847                        pw.print("lib,");
14848                    }
14849                    pw.print(name);
14850                    if (!checkin) {
14851                        pw.print(" -> ");
14852                    }
14853                    if (ent.path != null) {
14854                        if (!checkin) {
14855                            pw.print("(jar) ");
14856                            pw.print(ent.path);
14857                        } else {
14858                            pw.print(",jar,");
14859                            pw.print(ent.path);
14860                        }
14861                    } else {
14862                        if (!checkin) {
14863                            pw.print("(apk) ");
14864                            pw.print(ent.apk);
14865                        } else {
14866                            pw.print(",apk,");
14867                            pw.print(ent.apk);
14868                        }
14869                    }
14870                    pw.println();
14871                }
14872            }
14873
14874            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14875                if (dumpState.onTitlePrinted())
14876                    pw.println();
14877                if (!checkin) {
14878                    pw.println("Features:");
14879                }
14880                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14881                while (it.hasNext()) {
14882                    String name = it.next();
14883                    if (!checkin) {
14884                        pw.print("  ");
14885                    } else {
14886                        pw.print("feat,");
14887                    }
14888                    pw.println(name);
14889                }
14890            }
14891
14892            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14893                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14894                        : "Activity Resolver Table:", "  ", packageName,
14895                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14896                    dumpState.setTitlePrinted(true);
14897                }
14898                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14899                        : "Receiver Resolver Table:", "  ", packageName,
14900                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14901                    dumpState.setTitlePrinted(true);
14902                }
14903                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14904                        : "Service Resolver Table:", "  ", packageName,
14905                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14906                    dumpState.setTitlePrinted(true);
14907                }
14908                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14909                        : "Provider Resolver Table:", "  ", packageName,
14910                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14911                    dumpState.setTitlePrinted(true);
14912                }
14913            }
14914
14915            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14916                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14917                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14918                    int user = mSettings.mPreferredActivities.keyAt(i);
14919                    if (pir.dump(pw,
14920                            dumpState.getTitlePrinted()
14921                                ? "\nPreferred Activities User " + user + ":"
14922                                : "Preferred Activities User " + user + ":", "  ",
14923                            packageName, true, false)) {
14924                        dumpState.setTitlePrinted(true);
14925                    }
14926                }
14927            }
14928
14929            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14930                pw.flush();
14931                FileOutputStream fout = new FileOutputStream(fd);
14932                BufferedOutputStream str = new BufferedOutputStream(fout);
14933                XmlSerializer serializer = new FastXmlSerializer();
14934                try {
14935                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14936                    serializer.startDocument(null, true);
14937                    serializer.setFeature(
14938                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14939                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14940                    serializer.endDocument();
14941                    serializer.flush();
14942                } catch (IllegalArgumentException e) {
14943                    pw.println("Failed writing: " + e);
14944                } catch (IllegalStateException e) {
14945                    pw.println("Failed writing: " + e);
14946                } catch (IOException e) {
14947                    pw.println("Failed writing: " + e);
14948                }
14949            }
14950
14951            if (!checkin
14952                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14953                    && packageName == null) {
14954                pw.println();
14955                int count = mSettings.mPackages.size();
14956                if (count == 0) {
14957                    pw.println("No applications!");
14958                    pw.println();
14959                } else {
14960                    final String prefix = "  ";
14961                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14962                    if (allPackageSettings.size() == 0) {
14963                        pw.println("No domain preferred apps!");
14964                        pw.println();
14965                    } else {
14966                        pw.println("App verification status:");
14967                        pw.println();
14968                        count = 0;
14969                        for (PackageSetting ps : allPackageSettings) {
14970                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14971                            if (ivi == null || ivi.getPackageName() == null) continue;
14972                            pw.println(prefix + "Package: " + ivi.getPackageName());
14973                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14974                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14975                            pw.println();
14976                            count++;
14977                        }
14978                        if (count == 0) {
14979                            pw.println(prefix + "No app verification established.");
14980                            pw.println();
14981                        }
14982                        for (int userId : sUserManager.getUserIds()) {
14983                            pw.println("App linkages for user " + userId + ":");
14984                            pw.println();
14985                            count = 0;
14986                            for (PackageSetting ps : allPackageSettings) {
14987                                final long status = ps.getDomainVerificationStatusForUser(userId);
14988                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14989                                    continue;
14990                                }
14991                                pw.println(prefix + "Package: " + ps.name);
14992                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14993                                String statusStr = IntentFilterVerificationInfo.
14994                                        getStatusStringFromValue(status);
14995                                pw.println(prefix + "Status:  " + statusStr);
14996                                pw.println();
14997                                count++;
14998                            }
14999                            if (count == 0) {
15000                                pw.println(prefix + "No configured app linkages.");
15001                                pw.println();
15002                            }
15003                        }
15004                    }
15005                }
15006            }
15007
15008            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15009                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15010                if (packageName == null && permissionNames == null) {
15011                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15012                        if (iperm == 0) {
15013                            if (dumpState.onTitlePrinted())
15014                                pw.println();
15015                            pw.println("AppOp Permissions:");
15016                        }
15017                        pw.print("  AppOp Permission ");
15018                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15019                        pw.println(":");
15020                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15021                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15022                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15023                        }
15024                    }
15025                }
15026            }
15027
15028            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15029                boolean printedSomething = false;
15030                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15031                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15032                        continue;
15033                    }
15034                    if (!printedSomething) {
15035                        if (dumpState.onTitlePrinted())
15036                            pw.println();
15037                        pw.println("Registered ContentProviders:");
15038                        printedSomething = true;
15039                    }
15040                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15041                    pw.print("    "); pw.println(p.toString());
15042                }
15043                printedSomething = false;
15044                for (Map.Entry<String, PackageParser.Provider> entry :
15045                        mProvidersByAuthority.entrySet()) {
15046                    PackageParser.Provider p = entry.getValue();
15047                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15048                        continue;
15049                    }
15050                    if (!printedSomething) {
15051                        if (dumpState.onTitlePrinted())
15052                            pw.println();
15053                        pw.println("ContentProvider Authorities:");
15054                        printedSomething = true;
15055                    }
15056                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15057                    pw.print("    "); pw.println(p.toString());
15058                    if (p.info != null && p.info.applicationInfo != null) {
15059                        final String appInfo = p.info.applicationInfo.toString();
15060                        pw.print("      applicationInfo="); pw.println(appInfo);
15061                    }
15062                }
15063            }
15064
15065            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15066                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15067            }
15068
15069            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15070                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15071            }
15072
15073            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15074                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15075            }
15076
15077            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15078                // XXX should handle packageName != null by dumping only install data that
15079                // the given package is involved with.
15080                if (dumpState.onTitlePrinted()) pw.println();
15081                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15082            }
15083
15084            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15085                if (dumpState.onTitlePrinted()) pw.println();
15086                mSettings.dumpReadMessagesLPr(pw, dumpState);
15087
15088                pw.println();
15089                pw.println("Package warning messages:");
15090                BufferedReader in = null;
15091                String line = null;
15092                try {
15093                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15094                    while ((line = in.readLine()) != null) {
15095                        if (line.contains("ignored: updated version")) continue;
15096                        pw.println(line);
15097                    }
15098                } catch (IOException ignored) {
15099                } finally {
15100                    IoUtils.closeQuietly(in);
15101                }
15102            }
15103
15104            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15105                BufferedReader in = null;
15106                String line = null;
15107                try {
15108                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15109                    while ((line = in.readLine()) != null) {
15110                        if (line.contains("ignored: updated version")) continue;
15111                        pw.print("msg,");
15112                        pw.println(line);
15113                    }
15114                } catch (IOException ignored) {
15115                } finally {
15116                    IoUtils.closeQuietly(in);
15117                }
15118            }
15119        }
15120    }
15121
15122    private String dumpDomainString(String packageName) {
15123        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15124        List<IntentFilter> filters = getAllIntentFilters(packageName);
15125
15126        ArraySet<String> result = new ArraySet<>();
15127        if (iviList.size() > 0) {
15128            for (IntentFilterVerificationInfo ivi : iviList) {
15129                for (String host : ivi.getDomains()) {
15130                    result.add(host);
15131                }
15132            }
15133        }
15134        if (filters != null && filters.size() > 0) {
15135            for (IntentFilter filter : filters) {
15136                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15137                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15138                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15139                    result.addAll(filter.getHostsList());
15140                }
15141            }
15142        }
15143
15144        StringBuilder sb = new StringBuilder(result.size() * 16);
15145        for (String domain : result) {
15146            if (sb.length() > 0) sb.append(" ");
15147            sb.append(domain);
15148        }
15149        return sb.toString();
15150    }
15151
15152    // ------- apps on sdcard specific code -------
15153    static final boolean DEBUG_SD_INSTALL = false;
15154
15155    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15156
15157    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15158
15159    private boolean mMediaMounted = false;
15160
15161    static String getEncryptKey() {
15162        try {
15163            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15164                    SD_ENCRYPTION_KEYSTORE_NAME);
15165            if (sdEncKey == null) {
15166                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15167                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15168                if (sdEncKey == null) {
15169                    Slog.e(TAG, "Failed to create encryption keys");
15170                    return null;
15171                }
15172            }
15173            return sdEncKey;
15174        } catch (NoSuchAlgorithmException nsae) {
15175            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15176            return null;
15177        } catch (IOException ioe) {
15178            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15179            return null;
15180        }
15181    }
15182
15183    /*
15184     * Update media status on PackageManager.
15185     */
15186    @Override
15187    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15188        int callingUid = Binder.getCallingUid();
15189        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15190            throw new SecurityException("Media status can only be updated by the system");
15191        }
15192        // reader; this apparently protects mMediaMounted, but should probably
15193        // be a different lock in that case.
15194        synchronized (mPackages) {
15195            Log.i(TAG, "Updating external media status from "
15196                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15197                    + (mediaStatus ? "mounted" : "unmounted"));
15198            if (DEBUG_SD_INSTALL)
15199                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15200                        + ", mMediaMounted=" + mMediaMounted);
15201            if (mediaStatus == mMediaMounted) {
15202                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15203                        : 0, -1);
15204                mHandler.sendMessage(msg);
15205                return;
15206            }
15207            mMediaMounted = mediaStatus;
15208        }
15209        // Queue up an async operation since the package installation may take a
15210        // little while.
15211        mHandler.post(new Runnable() {
15212            public void run() {
15213                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15214            }
15215        });
15216    }
15217
15218    /**
15219     * Called by MountService when the initial ASECs to scan are available.
15220     * Should block until all the ASEC containers are finished being scanned.
15221     */
15222    public void scanAvailableAsecs() {
15223        updateExternalMediaStatusInner(true, false, false);
15224        if (mShouldRestoreconData) {
15225            SELinuxMMAC.setRestoreconDone();
15226            mShouldRestoreconData = false;
15227        }
15228    }
15229
15230    /*
15231     * Collect information of applications on external media, map them against
15232     * existing containers and update information based on current mount status.
15233     * Please note that we always have to report status if reportStatus has been
15234     * set to true especially when unloading packages.
15235     */
15236    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15237            boolean externalStorage) {
15238        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15239        int[] uidArr = EmptyArray.INT;
15240
15241        final String[] list = PackageHelper.getSecureContainerList();
15242        if (ArrayUtils.isEmpty(list)) {
15243            Log.i(TAG, "No secure containers found");
15244        } else {
15245            // Process list of secure containers and categorize them
15246            // as active or stale based on their package internal state.
15247
15248            // reader
15249            synchronized (mPackages) {
15250                for (String cid : list) {
15251                    // Leave stages untouched for now; installer service owns them
15252                    if (PackageInstallerService.isStageName(cid)) continue;
15253
15254                    if (DEBUG_SD_INSTALL)
15255                        Log.i(TAG, "Processing container " + cid);
15256                    String pkgName = getAsecPackageName(cid);
15257                    if (pkgName == null) {
15258                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15259                        continue;
15260                    }
15261                    if (DEBUG_SD_INSTALL)
15262                        Log.i(TAG, "Looking for pkg : " + pkgName);
15263
15264                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15265                    if (ps == null) {
15266                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15267                        continue;
15268                    }
15269
15270                    /*
15271                     * Skip packages that are not external if we're unmounting
15272                     * external storage.
15273                     */
15274                    if (externalStorage && !isMounted && !isExternal(ps)) {
15275                        continue;
15276                    }
15277
15278                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15279                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15280                    // The package status is changed only if the code path
15281                    // matches between settings and the container id.
15282                    if (ps.codePathString != null
15283                            && ps.codePathString.startsWith(args.getCodePath())) {
15284                        if (DEBUG_SD_INSTALL) {
15285                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15286                                    + " at code path: " + ps.codePathString);
15287                        }
15288
15289                        // We do have a valid package installed on sdcard
15290                        processCids.put(args, ps.codePathString);
15291                        final int uid = ps.appId;
15292                        if (uid != -1) {
15293                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15294                        }
15295                    } else {
15296                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15297                                + ps.codePathString);
15298                    }
15299                }
15300            }
15301
15302            Arrays.sort(uidArr);
15303        }
15304
15305        // Process packages with valid entries.
15306        if (isMounted) {
15307            if (DEBUG_SD_INSTALL)
15308                Log.i(TAG, "Loading packages");
15309            loadMediaPackages(processCids, uidArr);
15310            startCleaningPackages();
15311            mInstallerService.onSecureContainersAvailable();
15312        } else {
15313            if (DEBUG_SD_INSTALL)
15314                Log.i(TAG, "Unloading packages");
15315            unloadMediaPackages(processCids, uidArr, reportStatus);
15316        }
15317    }
15318
15319    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15320            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15321        final int size = infos.size();
15322        final String[] packageNames = new String[size];
15323        final int[] packageUids = new int[size];
15324        for (int i = 0; i < size; i++) {
15325            final ApplicationInfo info = infos.get(i);
15326            packageNames[i] = info.packageName;
15327            packageUids[i] = info.uid;
15328        }
15329        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15330                finishedReceiver);
15331    }
15332
15333    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15334            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15335        sendResourcesChangedBroadcast(mediaStatus, replacing,
15336                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15337    }
15338
15339    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15340            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15341        int size = pkgList.length;
15342        if (size > 0) {
15343            // Send broadcasts here
15344            Bundle extras = new Bundle();
15345            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15346            if (uidArr != null) {
15347                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15348            }
15349            if (replacing) {
15350                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15351            }
15352            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15353                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15354            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15355        }
15356    }
15357
15358   /*
15359     * Look at potentially valid container ids from processCids If package
15360     * information doesn't match the one on record or package scanning fails,
15361     * the cid is added to list of removeCids. We currently don't delete stale
15362     * containers.
15363     */
15364    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15365        ArrayList<String> pkgList = new ArrayList<String>();
15366        Set<AsecInstallArgs> keys = processCids.keySet();
15367
15368        for (AsecInstallArgs args : keys) {
15369            String codePath = processCids.get(args);
15370            if (DEBUG_SD_INSTALL)
15371                Log.i(TAG, "Loading container : " + args.cid);
15372            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15373            try {
15374                // Make sure there are no container errors first.
15375                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15376                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15377                            + " when installing from sdcard");
15378                    continue;
15379                }
15380                // Check code path here.
15381                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15382                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15383                            + " does not match one in settings " + codePath);
15384                    continue;
15385                }
15386                // Parse package
15387                int parseFlags = mDefParseFlags;
15388                if (args.isExternalAsec()) {
15389                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15390                }
15391                if (args.isFwdLocked()) {
15392                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15393                }
15394
15395                synchronized (mInstallLock) {
15396                    PackageParser.Package pkg = null;
15397                    try {
15398                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15399                    } catch (PackageManagerException e) {
15400                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15401                    }
15402                    // Scan the package
15403                    if (pkg != null) {
15404                        /*
15405                         * TODO why is the lock being held? doPostInstall is
15406                         * called in other places without the lock. This needs
15407                         * to be straightened out.
15408                         */
15409                        // writer
15410                        synchronized (mPackages) {
15411                            retCode = PackageManager.INSTALL_SUCCEEDED;
15412                            pkgList.add(pkg.packageName);
15413                            // Post process args
15414                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15415                                    pkg.applicationInfo.uid);
15416                        }
15417                    } else {
15418                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15419                    }
15420                }
15421
15422            } finally {
15423                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15424                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15425                }
15426            }
15427        }
15428        // writer
15429        synchronized (mPackages) {
15430            // If the platform SDK has changed since the last time we booted,
15431            // we need to re-grant app permission to catch any new ones that
15432            // appear. This is really a hack, and means that apps can in some
15433            // cases get permissions that the user didn't initially explicitly
15434            // allow... it would be nice to have some better way to handle
15435            // this situation.
15436            final VersionInfo ver = mSettings.getExternalVersion();
15437
15438            int updateFlags = UPDATE_PERMISSIONS_ALL;
15439            if (ver.sdkVersion != mSdkVersion) {
15440                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15441                        + mSdkVersion + "; regranting permissions for external");
15442                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15443            }
15444            updatePermissionsLPw(null, null, updateFlags);
15445
15446            // Yay, everything is now upgraded
15447            ver.forceCurrent();
15448
15449            // can downgrade to reader
15450            // Persist settings
15451            mSettings.writeLPr();
15452        }
15453        // Send a broadcast to let everyone know we are done processing
15454        if (pkgList.size() > 0) {
15455            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15456        }
15457    }
15458
15459   /*
15460     * Utility method to unload a list of specified containers
15461     */
15462    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15463        // Just unmount all valid containers.
15464        for (AsecInstallArgs arg : cidArgs) {
15465            synchronized (mInstallLock) {
15466                arg.doPostDeleteLI(false);
15467           }
15468       }
15469   }
15470
15471    /*
15472     * Unload packages mounted on external media. This involves deleting package
15473     * data from internal structures, sending broadcasts about diabled packages,
15474     * gc'ing to free up references, unmounting all secure containers
15475     * corresponding to packages on external media, and posting a
15476     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15477     * that we always have to post this message if status has been requested no
15478     * matter what.
15479     */
15480    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15481            final boolean reportStatus) {
15482        if (DEBUG_SD_INSTALL)
15483            Log.i(TAG, "unloading media packages");
15484        ArrayList<String> pkgList = new ArrayList<String>();
15485        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15486        final Set<AsecInstallArgs> keys = processCids.keySet();
15487        for (AsecInstallArgs args : keys) {
15488            String pkgName = args.getPackageName();
15489            if (DEBUG_SD_INSTALL)
15490                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15491            // Delete package internally
15492            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15493            synchronized (mInstallLock) {
15494                boolean res = deletePackageLI(pkgName, null, false, null, null,
15495                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15496                if (res) {
15497                    pkgList.add(pkgName);
15498                } else {
15499                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15500                    failedList.add(args);
15501                }
15502            }
15503        }
15504
15505        // reader
15506        synchronized (mPackages) {
15507            // We didn't update the settings after removing each package;
15508            // write them now for all packages.
15509            mSettings.writeLPr();
15510        }
15511
15512        // We have to absolutely send UPDATED_MEDIA_STATUS only
15513        // after confirming that all the receivers processed the ordered
15514        // broadcast when packages get disabled, force a gc to clean things up.
15515        // and unload all the containers.
15516        if (pkgList.size() > 0) {
15517            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15518                    new IIntentReceiver.Stub() {
15519                public void performReceive(Intent intent, int resultCode, String data,
15520                        Bundle extras, boolean ordered, boolean sticky,
15521                        int sendingUser) throws RemoteException {
15522                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15523                            reportStatus ? 1 : 0, 1, keys);
15524                    mHandler.sendMessage(msg);
15525                }
15526            });
15527        } else {
15528            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15529                    keys);
15530            mHandler.sendMessage(msg);
15531        }
15532    }
15533
15534    private void loadPrivatePackages(VolumeInfo vol) {
15535        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15536        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15537        synchronized (mInstallLock) {
15538        synchronized (mPackages) {
15539            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15540            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15541            for (PackageSetting ps : packages) {
15542                final PackageParser.Package pkg;
15543                try {
15544                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15545                    loaded.add(pkg.applicationInfo);
15546                } catch (PackageManagerException e) {
15547                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15548                }
15549
15550                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15551                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15552                }
15553            }
15554
15555            int updateFlags = UPDATE_PERMISSIONS_ALL;
15556            if (ver.sdkVersion != mSdkVersion) {
15557                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15558                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15559                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15560            }
15561            updatePermissionsLPw(null, null, updateFlags);
15562
15563            // Yay, everything is now upgraded
15564            ver.forceCurrent();
15565
15566            mSettings.writeLPr();
15567        }
15568        }
15569
15570        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15571        sendResourcesChangedBroadcast(true, false, loaded, null);
15572    }
15573
15574    private void unloadPrivatePackages(VolumeInfo vol) {
15575        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15576        synchronized (mInstallLock) {
15577        synchronized (mPackages) {
15578            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15579            for (PackageSetting ps : packages) {
15580                if (ps.pkg == null) continue;
15581
15582                final ApplicationInfo info = ps.pkg.applicationInfo;
15583                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15584                if (deletePackageLI(ps.name, null, false, null, null,
15585                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15586                    unloaded.add(info);
15587                } else {
15588                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15589                }
15590            }
15591
15592            mSettings.writeLPr();
15593        }
15594        }
15595
15596        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15597        sendResourcesChangedBroadcast(false, false, unloaded, null);
15598    }
15599
15600    /**
15601     * Examine all users present on given mounted volume, and destroy data
15602     * belonging to users that are no longer valid, or whose user ID has been
15603     * recycled.
15604     */
15605    private void reconcileUsers(String volumeUuid) {
15606        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15607        if (ArrayUtils.isEmpty(files)) {
15608            Slog.d(TAG, "No users found on " + volumeUuid);
15609            return;
15610        }
15611
15612        for (File file : files) {
15613            if (!file.isDirectory()) continue;
15614
15615            final int userId;
15616            final UserInfo info;
15617            try {
15618                userId = Integer.parseInt(file.getName());
15619                info = sUserManager.getUserInfo(userId);
15620            } catch (NumberFormatException e) {
15621                Slog.w(TAG, "Invalid user directory " + file);
15622                continue;
15623            }
15624
15625            boolean destroyUser = false;
15626            if (info == null) {
15627                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15628                        + " because no matching user was found");
15629                destroyUser = true;
15630            } else {
15631                try {
15632                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15633                } catch (IOException e) {
15634                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15635                            + " because we failed to enforce serial number: " + e);
15636                    destroyUser = true;
15637                }
15638            }
15639
15640            if (destroyUser) {
15641                synchronized (mInstallLock) {
15642                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15643                }
15644            }
15645        }
15646
15647        final UserManager um = mContext.getSystemService(UserManager.class);
15648        for (UserInfo user : um.getUsers()) {
15649            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15650            if (userDir.exists()) continue;
15651
15652            try {
15653                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15654                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15655            } catch (IOException e) {
15656                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15657            }
15658        }
15659    }
15660
15661    /**
15662     * Examine all apps present on given mounted volume, and destroy apps that
15663     * aren't expected, either due to uninstallation or reinstallation on
15664     * another volume.
15665     */
15666    private void reconcileApps(String volumeUuid) {
15667        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15668        if (ArrayUtils.isEmpty(files)) {
15669            Slog.d(TAG, "No apps found on " + volumeUuid);
15670            return;
15671        }
15672
15673        for (File file : files) {
15674            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15675                    && !PackageInstallerService.isStageName(file.getName());
15676            if (!isPackage) {
15677                // Ignore entries which are not packages
15678                continue;
15679            }
15680
15681            boolean destroyApp = false;
15682            String packageName = null;
15683            try {
15684                final PackageLite pkg = PackageParser.parsePackageLite(file,
15685                        PackageParser.PARSE_MUST_BE_APK);
15686                packageName = pkg.packageName;
15687
15688                synchronized (mPackages) {
15689                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15690                    if (ps == null) {
15691                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15692                                + volumeUuid + " because we found no install record");
15693                        destroyApp = true;
15694                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15695                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15696                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15697                        destroyApp = true;
15698                    }
15699                }
15700
15701            } catch (PackageParserException e) {
15702                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15703                destroyApp = true;
15704            }
15705
15706            if (destroyApp) {
15707                synchronized (mInstallLock) {
15708                    if (packageName != null) {
15709                        removeDataDirsLI(volumeUuid, packageName);
15710                    }
15711                    if (file.isDirectory()) {
15712                        mInstaller.rmPackageDir(file.getAbsolutePath());
15713                    } else {
15714                        file.delete();
15715                    }
15716                }
15717            }
15718        }
15719    }
15720
15721    private void unfreezePackage(String packageName) {
15722        synchronized (mPackages) {
15723            final PackageSetting ps = mSettings.mPackages.get(packageName);
15724            if (ps != null) {
15725                ps.frozen = false;
15726            }
15727        }
15728    }
15729
15730    @Override
15731    public int movePackage(final String packageName, final String volumeUuid) {
15732        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15733
15734        final int moveId = mNextMoveId.getAndIncrement();
15735        try {
15736            movePackageInternal(packageName, volumeUuid, moveId);
15737        } catch (PackageManagerException e) {
15738            Slog.w(TAG, "Failed to move " + packageName, e);
15739            mMoveCallbacks.notifyStatusChanged(moveId,
15740                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15741        }
15742        return moveId;
15743    }
15744
15745    private void movePackageInternal(final String packageName, final String volumeUuid,
15746            final int moveId) throws PackageManagerException {
15747        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15748        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15749        final PackageManager pm = mContext.getPackageManager();
15750
15751        final boolean currentAsec;
15752        final String currentVolumeUuid;
15753        final File codeFile;
15754        final String installerPackageName;
15755        final String packageAbiOverride;
15756        final int appId;
15757        final String seinfo;
15758        final String label;
15759
15760        // reader
15761        synchronized (mPackages) {
15762            final PackageParser.Package pkg = mPackages.get(packageName);
15763            final PackageSetting ps = mSettings.mPackages.get(packageName);
15764            if (pkg == null || ps == null) {
15765                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15766            }
15767
15768            if (pkg.applicationInfo.isSystemApp()) {
15769                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15770                        "Cannot move system application");
15771            }
15772
15773            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15774                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15775                        "Package already moved to " + volumeUuid);
15776            }
15777
15778            final File probe = new File(pkg.codePath);
15779            final File probeOat = new File(probe, "oat");
15780            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15781                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15782                        "Move only supported for modern cluster style installs");
15783            }
15784
15785            if (ps.frozen) {
15786                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15787                        "Failed to move already frozen package");
15788            }
15789            ps.frozen = true;
15790
15791            currentAsec = pkg.applicationInfo.isForwardLocked()
15792                    || pkg.applicationInfo.isExternalAsec();
15793            currentVolumeUuid = ps.volumeUuid;
15794            codeFile = new File(pkg.codePath);
15795            installerPackageName = ps.installerPackageName;
15796            packageAbiOverride = ps.cpuAbiOverrideString;
15797            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15798            seinfo = pkg.applicationInfo.seinfo;
15799            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15800        }
15801
15802        // Now that we're guarded by frozen state, kill app during move
15803        killApplication(packageName, appId, "move pkg");
15804
15805        final Bundle extras = new Bundle();
15806        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15807        extras.putString(Intent.EXTRA_TITLE, label);
15808        mMoveCallbacks.notifyCreated(moveId, extras);
15809
15810        int installFlags;
15811        final boolean moveCompleteApp;
15812        final File measurePath;
15813
15814        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15815            installFlags = INSTALL_INTERNAL;
15816            moveCompleteApp = !currentAsec;
15817            measurePath = Environment.getDataAppDirectory(volumeUuid);
15818        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15819            installFlags = INSTALL_EXTERNAL;
15820            moveCompleteApp = false;
15821            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15822        } else {
15823            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15824            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15825                    || !volume.isMountedWritable()) {
15826                unfreezePackage(packageName);
15827                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15828                        "Move location not mounted private volume");
15829            }
15830
15831            Preconditions.checkState(!currentAsec);
15832
15833            installFlags = INSTALL_INTERNAL;
15834            moveCompleteApp = true;
15835            measurePath = Environment.getDataAppDirectory(volumeUuid);
15836        }
15837
15838        final PackageStats stats = new PackageStats(null, -1);
15839        synchronized (mInstaller) {
15840            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15841                unfreezePackage(packageName);
15842                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15843                        "Failed to measure package size");
15844            }
15845        }
15846
15847        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15848                + stats.dataSize);
15849
15850        final long startFreeBytes = measurePath.getFreeSpace();
15851        final long sizeBytes;
15852        if (moveCompleteApp) {
15853            sizeBytes = stats.codeSize + stats.dataSize;
15854        } else {
15855            sizeBytes = stats.codeSize;
15856        }
15857
15858        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15859            unfreezePackage(packageName);
15860            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15861                    "Not enough free space to move");
15862        }
15863
15864        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15865
15866        final CountDownLatch installedLatch = new CountDownLatch(1);
15867        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15868            @Override
15869            public void onUserActionRequired(Intent intent) throws RemoteException {
15870                throw new IllegalStateException();
15871            }
15872
15873            @Override
15874            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15875                    Bundle extras) throws RemoteException {
15876                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15877                        + PackageManager.installStatusToString(returnCode, msg));
15878
15879                installedLatch.countDown();
15880
15881                // Regardless of success or failure of the move operation,
15882                // always unfreeze the package
15883                unfreezePackage(packageName);
15884
15885                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15886                switch (status) {
15887                    case PackageInstaller.STATUS_SUCCESS:
15888                        mMoveCallbacks.notifyStatusChanged(moveId,
15889                                PackageManager.MOVE_SUCCEEDED);
15890                        break;
15891                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15892                        mMoveCallbacks.notifyStatusChanged(moveId,
15893                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15894                        break;
15895                    default:
15896                        mMoveCallbacks.notifyStatusChanged(moveId,
15897                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15898                        break;
15899                }
15900            }
15901        };
15902
15903        final MoveInfo move;
15904        if (moveCompleteApp) {
15905            // Kick off a thread to report progress estimates
15906            new Thread() {
15907                @Override
15908                public void run() {
15909                    while (true) {
15910                        try {
15911                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15912                                break;
15913                            }
15914                        } catch (InterruptedException ignored) {
15915                        }
15916
15917                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15918                        final int progress = 10 + (int) MathUtils.constrain(
15919                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15920                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15921                    }
15922                }
15923            }.start();
15924
15925            final String dataAppName = codeFile.getName();
15926            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15927                    dataAppName, appId, seinfo);
15928        } else {
15929            move = null;
15930        }
15931
15932        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15933
15934        final Message msg = mHandler.obtainMessage(INIT_COPY);
15935        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15936        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15937                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15938        mHandler.sendMessage(msg);
15939    }
15940
15941    @Override
15942    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15943        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15944
15945        final int realMoveId = mNextMoveId.getAndIncrement();
15946        final Bundle extras = new Bundle();
15947        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15948        mMoveCallbacks.notifyCreated(realMoveId, extras);
15949
15950        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15951            @Override
15952            public void onCreated(int moveId, Bundle extras) {
15953                // Ignored
15954            }
15955
15956            @Override
15957            public void onStatusChanged(int moveId, int status, long estMillis) {
15958                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15959            }
15960        };
15961
15962        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15963        storage.setPrimaryStorageUuid(volumeUuid, callback);
15964        return realMoveId;
15965    }
15966
15967    @Override
15968    public int getMoveStatus(int moveId) {
15969        mContext.enforceCallingOrSelfPermission(
15970                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15971        return mMoveCallbacks.mLastStatus.get(moveId);
15972    }
15973
15974    @Override
15975    public void registerMoveCallback(IPackageMoveObserver callback) {
15976        mContext.enforceCallingOrSelfPermission(
15977                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15978        mMoveCallbacks.register(callback);
15979    }
15980
15981    @Override
15982    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15983        mContext.enforceCallingOrSelfPermission(
15984                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15985        mMoveCallbacks.unregister(callback);
15986    }
15987
15988    @Override
15989    public boolean setInstallLocation(int loc) {
15990        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15991                null);
15992        if (getInstallLocation() == loc) {
15993            return true;
15994        }
15995        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15996                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15997            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15998                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15999            return true;
16000        }
16001        return false;
16002   }
16003
16004    @Override
16005    public int getInstallLocation() {
16006        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16007                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16008                PackageHelper.APP_INSTALL_AUTO);
16009    }
16010
16011    /** Called by UserManagerService */
16012    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16013        mDirtyUsers.remove(userHandle);
16014        mSettings.removeUserLPw(userHandle);
16015        mPendingBroadcasts.remove(userHandle);
16016        if (mInstaller != null) {
16017            // Technically, we shouldn't be doing this with the package lock
16018            // held.  However, this is very rare, and there is already so much
16019            // other disk I/O going on, that we'll let it slide for now.
16020            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16021            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16022                final String volumeUuid = vol.getFsUuid();
16023                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16024                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16025            }
16026        }
16027        mUserNeedsBadging.delete(userHandle);
16028        removeUnusedPackagesLILPw(userManager, userHandle);
16029    }
16030
16031    /**
16032     * We're removing userHandle and would like to remove any downloaded packages
16033     * that are no longer in use by any other user.
16034     * @param userHandle the user being removed
16035     */
16036    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16037        final boolean DEBUG_CLEAN_APKS = false;
16038        int [] users = userManager.getUserIdsLPr();
16039        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16040        while (psit.hasNext()) {
16041            PackageSetting ps = psit.next();
16042            if (ps.pkg == null) {
16043                continue;
16044            }
16045            final String packageName = ps.pkg.packageName;
16046            // Skip over if system app
16047            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16048                continue;
16049            }
16050            if (DEBUG_CLEAN_APKS) {
16051                Slog.i(TAG, "Checking package " + packageName);
16052            }
16053            boolean keep = false;
16054            for (int i = 0; i < users.length; i++) {
16055                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16056                    keep = true;
16057                    if (DEBUG_CLEAN_APKS) {
16058                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16059                                + users[i]);
16060                    }
16061                    break;
16062                }
16063            }
16064            if (!keep) {
16065                if (DEBUG_CLEAN_APKS) {
16066                    Slog.i(TAG, "  Removing package " + packageName);
16067                }
16068                mHandler.post(new Runnable() {
16069                    public void run() {
16070                        deletePackageX(packageName, userHandle, 0);
16071                    } //end run
16072                });
16073            }
16074        }
16075    }
16076
16077    /** Called by UserManagerService */
16078    void createNewUserLILPw(int userHandle) {
16079        if (mInstaller != null) {
16080            mInstaller.createUserConfig(userHandle);
16081            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16082            applyFactoryDefaultBrowserLPw(userHandle);
16083            primeDomainVerificationsLPw(userHandle);
16084        }
16085    }
16086
16087    void newUserCreated(final int userHandle) {
16088        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16089    }
16090
16091    @Override
16092    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16093        mContext.enforceCallingOrSelfPermission(
16094                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16095                "Only package verification agents can read the verifier device identity");
16096
16097        synchronized (mPackages) {
16098            return mSettings.getVerifierDeviceIdentityLPw();
16099        }
16100    }
16101
16102    @Override
16103    public void setPermissionEnforced(String permission, boolean enforced) {
16104        // TODO: Now that we no longer change GID for storage, this should to away.
16105        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16106                "setPermissionEnforced");
16107        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16108            synchronized (mPackages) {
16109                if (mSettings.mReadExternalStorageEnforced == null
16110                        || mSettings.mReadExternalStorageEnforced != enforced) {
16111                    mSettings.mReadExternalStorageEnforced = enforced;
16112                    mSettings.writeLPr();
16113                }
16114            }
16115            // kill any non-foreground processes so we restart them and
16116            // grant/revoke the GID.
16117            final IActivityManager am = ActivityManagerNative.getDefault();
16118            if (am != null) {
16119                final long token = Binder.clearCallingIdentity();
16120                try {
16121                    am.killProcessesBelowForeground("setPermissionEnforcement");
16122                } catch (RemoteException e) {
16123                } finally {
16124                    Binder.restoreCallingIdentity(token);
16125                }
16126            }
16127        } else {
16128            throw new IllegalArgumentException("No selective enforcement for " + permission);
16129        }
16130    }
16131
16132    @Override
16133    @Deprecated
16134    public boolean isPermissionEnforced(String permission) {
16135        return true;
16136    }
16137
16138    @Override
16139    public boolean isStorageLow() {
16140        final long token = Binder.clearCallingIdentity();
16141        try {
16142            final DeviceStorageMonitorInternal
16143                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16144            if (dsm != null) {
16145                return dsm.isMemoryLow();
16146            } else {
16147                return false;
16148            }
16149        } finally {
16150            Binder.restoreCallingIdentity(token);
16151        }
16152    }
16153
16154    @Override
16155    public IPackageInstaller getPackageInstaller() {
16156        return mInstallerService;
16157    }
16158
16159    private boolean userNeedsBadging(int userId) {
16160        int index = mUserNeedsBadging.indexOfKey(userId);
16161        if (index < 0) {
16162            final UserInfo userInfo;
16163            final long token = Binder.clearCallingIdentity();
16164            try {
16165                userInfo = sUserManager.getUserInfo(userId);
16166            } finally {
16167                Binder.restoreCallingIdentity(token);
16168            }
16169            final boolean b;
16170            if (userInfo != null && userInfo.isManagedProfile()) {
16171                b = true;
16172            } else {
16173                b = false;
16174            }
16175            mUserNeedsBadging.put(userId, b);
16176            return b;
16177        }
16178        return mUserNeedsBadging.valueAt(index);
16179    }
16180
16181    @Override
16182    public KeySet getKeySetByAlias(String packageName, String alias) {
16183        if (packageName == null || alias == null) {
16184            return null;
16185        }
16186        synchronized(mPackages) {
16187            final PackageParser.Package pkg = mPackages.get(packageName);
16188            if (pkg == null) {
16189                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16190                throw new IllegalArgumentException("Unknown package: " + packageName);
16191            }
16192            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16193            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16194        }
16195    }
16196
16197    @Override
16198    public KeySet getSigningKeySet(String packageName) {
16199        if (packageName == null) {
16200            return null;
16201        }
16202        synchronized(mPackages) {
16203            final PackageParser.Package pkg = mPackages.get(packageName);
16204            if (pkg == null) {
16205                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16206                throw new IllegalArgumentException("Unknown package: " + packageName);
16207            }
16208            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16209                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16210                throw new SecurityException("May not access signing KeySet of other apps.");
16211            }
16212            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16213            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16214        }
16215    }
16216
16217    @Override
16218    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16219        if (packageName == null || ks == null) {
16220            return false;
16221        }
16222        synchronized(mPackages) {
16223            final PackageParser.Package pkg = mPackages.get(packageName);
16224            if (pkg == null) {
16225                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16226                throw new IllegalArgumentException("Unknown package: " + packageName);
16227            }
16228            IBinder ksh = ks.getToken();
16229            if (ksh instanceof KeySetHandle) {
16230                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16231                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16232            }
16233            return false;
16234        }
16235    }
16236
16237    @Override
16238    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16239        if (packageName == null || ks == null) {
16240            return false;
16241        }
16242        synchronized(mPackages) {
16243            final PackageParser.Package pkg = mPackages.get(packageName);
16244            if (pkg == null) {
16245                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16246                throw new IllegalArgumentException("Unknown package: " + packageName);
16247            }
16248            IBinder ksh = ks.getToken();
16249            if (ksh instanceof KeySetHandle) {
16250                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16251                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16252            }
16253            return false;
16254        }
16255    }
16256
16257    public void getUsageStatsIfNoPackageUsageInfo() {
16258        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16259            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16260            if (usm == null) {
16261                throw new IllegalStateException("UsageStatsManager must be initialized");
16262            }
16263            long now = System.currentTimeMillis();
16264            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16265            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16266                String packageName = entry.getKey();
16267                PackageParser.Package pkg = mPackages.get(packageName);
16268                if (pkg == null) {
16269                    continue;
16270                }
16271                UsageStats usage = entry.getValue();
16272                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16273                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16274            }
16275        }
16276    }
16277
16278    /**
16279     * Check and throw if the given before/after packages would be considered a
16280     * downgrade.
16281     */
16282    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16283            throws PackageManagerException {
16284        if (after.versionCode < before.mVersionCode) {
16285            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16286                    "Update version code " + after.versionCode + " is older than current "
16287                    + before.mVersionCode);
16288        } else if (after.versionCode == before.mVersionCode) {
16289            if (after.baseRevisionCode < before.baseRevisionCode) {
16290                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16291                        "Update base revision code " + after.baseRevisionCode
16292                        + " is older than current " + before.baseRevisionCode);
16293            }
16294
16295            if (!ArrayUtils.isEmpty(after.splitNames)) {
16296                for (int i = 0; i < after.splitNames.length; i++) {
16297                    final String splitName = after.splitNames[i];
16298                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16299                    if (j != -1) {
16300                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16301                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16302                                    "Update split " + splitName + " revision code "
16303                                    + after.splitRevisionCodes[i] + " is older than current "
16304                                    + before.splitRevisionCodes[j]);
16305                        }
16306                    }
16307                }
16308            }
16309        }
16310    }
16311
16312    private static class MoveCallbacks extends Handler {
16313        private static final int MSG_CREATED = 1;
16314        private static final int MSG_STATUS_CHANGED = 2;
16315
16316        private final RemoteCallbackList<IPackageMoveObserver>
16317                mCallbacks = new RemoteCallbackList<>();
16318
16319        private final SparseIntArray mLastStatus = new SparseIntArray();
16320
16321        public MoveCallbacks(Looper looper) {
16322            super(looper);
16323        }
16324
16325        public void register(IPackageMoveObserver callback) {
16326            mCallbacks.register(callback);
16327        }
16328
16329        public void unregister(IPackageMoveObserver callback) {
16330            mCallbacks.unregister(callback);
16331        }
16332
16333        @Override
16334        public void handleMessage(Message msg) {
16335            final SomeArgs args = (SomeArgs) msg.obj;
16336            final int n = mCallbacks.beginBroadcast();
16337            for (int i = 0; i < n; i++) {
16338                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16339                try {
16340                    invokeCallback(callback, msg.what, args);
16341                } catch (RemoteException ignored) {
16342                }
16343            }
16344            mCallbacks.finishBroadcast();
16345            args.recycle();
16346        }
16347
16348        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16349                throws RemoteException {
16350            switch (what) {
16351                case MSG_CREATED: {
16352                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16353                    break;
16354                }
16355                case MSG_STATUS_CHANGED: {
16356                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16357                    break;
16358                }
16359            }
16360        }
16361
16362        private void notifyCreated(int moveId, Bundle extras) {
16363            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16364
16365            final SomeArgs args = SomeArgs.obtain();
16366            args.argi1 = moveId;
16367            args.arg2 = extras;
16368            obtainMessage(MSG_CREATED, args).sendToTarget();
16369        }
16370
16371        private void notifyStatusChanged(int moveId, int status) {
16372            notifyStatusChanged(moveId, status, -1);
16373        }
16374
16375        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16376            Slog.v(TAG, "Move " + moveId + " status " + status);
16377
16378            final SomeArgs args = SomeArgs.obtain();
16379            args.argi1 = moveId;
16380            args.argi2 = status;
16381            args.arg3 = estMillis;
16382            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16383
16384            synchronized (mLastStatus) {
16385                mLastStatus.put(moveId, status);
16386            }
16387        }
16388    }
16389
16390    private final class OnPermissionChangeListeners extends Handler {
16391        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16392
16393        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16394                new RemoteCallbackList<>();
16395
16396        public OnPermissionChangeListeners(Looper looper) {
16397            super(looper);
16398        }
16399
16400        @Override
16401        public void handleMessage(Message msg) {
16402            switch (msg.what) {
16403                case MSG_ON_PERMISSIONS_CHANGED: {
16404                    final int uid = msg.arg1;
16405                    handleOnPermissionsChanged(uid);
16406                } break;
16407            }
16408        }
16409
16410        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16411            mPermissionListeners.register(listener);
16412
16413        }
16414
16415        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16416            mPermissionListeners.unregister(listener);
16417        }
16418
16419        public void onPermissionsChanged(int uid) {
16420            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16421                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16422            }
16423        }
16424
16425        private void handleOnPermissionsChanged(int uid) {
16426            final int count = mPermissionListeners.beginBroadcast();
16427            try {
16428                for (int i = 0; i < count; i++) {
16429                    IOnPermissionsChangeListener callback = mPermissionListeners
16430                            .getBroadcastItem(i);
16431                    try {
16432                        callback.onPermissionsChanged(uid);
16433                    } catch (RemoteException e) {
16434                        Log.e(TAG, "Permission listener is dead", e);
16435                    }
16436                }
16437            } finally {
16438                mPermissionListeners.finishBroadcast();
16439            }
16440        }
16441    }
16442
16443    private class PackageManagerInternalImpl extends PackageManagerInternal {
16444        @Override
16445        public void setLocationPackagesProvider(PackagesProvider provider) {
16446            synchronized (mPackages) {
16447                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16448            }
16449        }
16450
16451        @Override
16452        public void setImePackagesProvider(PackagesProvider provider) {
16453            synchronized (mPackages) {
16454                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16455            }
16456        }
16457
16458        @Override
16459        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16460            synchronized (mPackages) {
16461                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16462            }
16463        }
16464
16465        @Override
16466        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16467            synchronized (mPackages) {
16468                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16469            }
16470        }
16471
16472        @Override
16473        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16474            synchronized (mPackages) {
16475                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16476            }
16477        }
16478
16479        @Override
16480        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16481            synchronized (mPackages) {
16482                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16483            }
16484        }
16485
16486        @Override
16487        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16488            synchronized (mPackages) {
16489                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16490                        packageName, userId);
16491            }
16492        }
16493
16494        @Override
16495        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16496            synchronized (mPackages) {
16497                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16498                        packageName, userId);
16499            }
16500        }
16501    }
16502
16503    @Override
16504    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16505        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16506        synchronized (mPackages) {
16507            final long identity = Binder.clearCallingIdentity();
16508            try {
16509                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16510                        packageNames, userId);
16511            } finally {
16512                Binder.restoreCallingIdentity(identity);
16513            }
16514        }
16515    }
16516
16517    private static void enforceSystemOrPhoneCaller(String tag) {
16518        int callingUid = Binder.getCallingUid();
16519        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16520            throw new SecurityException(
16521                    "Cannot call " + tag + " from UID " + callingUid);
16522        }
16523    }
16524}
16525