PackageManagerService.java revision 5dc71cb2dd99bb2a5dd8bd6a51fec280bb488c38
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.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.system.OsConstants.O_CREAT;
71import static android.system.OsConstants.O_RDWR;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76import static com.android.internal.util.ArrayUtils.appendInt;
77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
85
86import android.Manifest;
87import android.app.ActivityManager;
88import android.app.ActivityManagerNative;
89import android.app.AppGlobals;
90import android.app.IActivityManager;
91import android.app.admin.IDevicePolicyManager;
92import android.app.backup.IBackupManager;
93import android.app.usage.UsageStats;
94import android.app.usage.UsageStatsManager;
95import android.content.BroadcastReceiver;
96import android.content.ComponentName;
97import android.content.Context;
98import android.content.IIntentReceiver;
99import android.content.Intent;
100import android.content.IntentFilter;
101import android.content.IntentSender;
102import android.content.IntentSender.SendIntentException;
103import android.content.ServiceConnection;
104import android.content.pm.ActivityInfo;
105import android.content.pm.ApplicationInfo;
106import android.content.pm.FeatureInfo;
107import android.content.pm.IOnPermissionsChangeListener;
108import android.content.pm.IPackageDataObserver;
109import android.content.pm.IPackageDeleteObserver;
110import android.content.pm.IPackageDeleteObserver2;
111import android.content.pm.IPackageInstallObserver2;
112import android.content.pm.IPackageInstaller;
113import android.content.pm.IPackageManager;
114import android.content.pm.IPackageMoveObserver;
115import android.content.pm.IPackageStatsObserver;
116import android.content.pm.InstrumentationInfo;
117import android.content.pm.IntentFilterVerificationInfo;
118import android.content.pm.KeySet;
119import android.content.pm.ManifestDigest;
120import android.content.pm.PackageCleanItem;
121import android.content.pm.PackageInfo;
122import android.content.pm.PackageInfoLite;
123import android.content.pm.PackageInstaller;
124import android.content.pm.PackageManager;
125import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
126import android.content.pm.PackageManagerInternal;
127import android.content.pm.PackageParser;
128import android.content.pm.PackageParser.ActivityIntentInfo;
129import android.content.pm.PackageParser.PackageLite;
130import android.content.pm.PackageParser.PackageParserException;
131import android.content.pm.PackageStats;
132import android.content.pm.PackageUserState;
133import android.content.pm.ParceledListSlice;
134import android.content.pm.PermissionGroupInfo;
135import android.content.pm.PermissionInfo;
136import android.content.pm.ProviderInfo;
137import android.content.pm.ResolveInfo;
138import android.content.pm.ServiceInfo;
139import android.content.pm.Signature;
140import android.content.pm.UserInfo;
141import android.content.pm.VerificationParams;
142import android.content.pm.VerifierDeviceIdentity;
143import android.content.pm.VerifierInfo;
144import android.content.res.Resources;
145import android.hardware.display.DisplayManager;
146import android.net.Uri;
147import android.os.Debug;
148import android.os.Binder;
149import android.os.Build;
150import android.os.Bundle;
151import android.os.Environment;
152import android.os.Environment.UserEnvironment;
153import android.os.FileUtils;
154import android.os.Handler;
155import android.os.IBinder;
156import android.os.Looper;
157import android.os.Message;
158import android.os.Parcel;
159import android.os.ParcelFileDescriptor;
160import android.os.Process;
161import android.os.RemoteCallbackList;
162import android.os.RemoteException;
163import android.os.SELinux;
164import android.os.ServiceManager;
165import android.os.SystemClock;
166import android.os.SystemProperties;
167import android.os.UserHandle;
168import android.os.UserManager;
169import android.os.storage.IMountService;
170import android.os.storage.MountServiceInternal;
171import android.os.storage.StorageEventListener;
172import android.os.storage.StorageManager;
173import android.os.storage.VolumeInfo;
174import android.os.storage.VolumeRecord;
175import android.security.KeyStore;
176import android.security.SystemKeyStore;
177import android.system.ErrnoException;
178import android.system.Os;
179import android.system.StructStat;
180import android.text.TextUtils;
181import android.text.format.DateUtils;
182import android.util.ArrayMap;
183import android.util.ArraySet;
184import android.util.AtomicFile;
185import android.util.DisplayMetrics;
186import android.util.EventLog;
187import android.util.ExceptionUtils;
188import android.util.Log;
189import android.util.LogPrinter;
190import android.util.MathUtils;
191import android.util.PrintStreamPrinter;
192import android.util.Slog;
193import android.util.SparseArray;
194import android.util.SparseBooleanArray;
195import android.util.SparseIntArray;
196import android.util.Xml;
197import android.view.Display;
198
199import dalvik.system.DexFile;
200import dalvik.system.VMRuntime;
201
202import libcore.io.IoUtils;
203import libcore.util.EmptyArray;
204
205import com.android.internal.R;
206import com.android.internal.annotations.GuardedBy;
207import com.android.internal.app.IMediaContainerService;
208import com.android.internal.app.ResolverActivity;
209import com.android.internal.content.NativeLibraryHelper;
210import com.android.internal.content.PackageHelper;
211import com.android.internal.os.IParcelFileDescriptorFactory;
212import com.android.internal.os.SomeArgs;
213import com.android.internal.os.Zygote;
214import com.android.internal.util.ArrayUtils;
215import com.android.internal.util.FastPrintWriter;
216import com.android.internal.util.FastXmlSerializer;
217import com.android.internal.util.IndentingPrintWriter;
218import com.android.internal.util.Preconditions;
219import com.android.server.EventLogTags;
220import com.android.server.FgThread;
221import com.android.server.IntentResolver;
222import com.android.server.LocalServices;
223import com.android.server.ServiceThread;
224import com.android.server.SystemConfig;
225import com.android.server.Watchdog;
226import com.android.server.pm.PermissionsState.PermissionState;
227import com.android.server.pm.Settings.DatabaseVersion;
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        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
803                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
804        if (!hasHTTPorHTTPS) {
805            return false;
806        }
807        return true;
808    }
809
810    private IntentFilterVerifier mIntentFilterVerifier;
811
812    // Set of pending broadcasts for aggregating enable/disable of components.
813    static class PendingPackageBroadcasts {
814        // for each user id, a map of <package name -> components within that package>
815        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
816
817        public PendingPackageBroadcasts() {
818            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
819        }
820
821        public ArrayList<String> get(int userId, String packageName) {
822            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
823            return packages.get(packageName);
824        }
825
826        public void put(int userId, String packageName, ArrayList<String> components) {
827            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
828            packages.put(packageName, components);
829        }
830
831        public void remove(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
833            if (packages != null) {
834                packages.remove(packageName);
835            }
836        }
837
838        public void remove(int userId) {
839            mUidMap.remove(userId);
840        }
841
842        public int userIdCount() {
843            return mUidMap.size();
844        }
845
846        public int userIdAt(int n) {
847            return mUidMap.keyAt(n);
848        }
849
850        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
851            return mUidMap.get(userId);
852        }
853
854        public int size() {
855            // total number of pending broadcast entries across all userIds
856            int num = 0;
857            for (int i = 0; i< mUidMap.size(); i++) {
858                num += mUidMap.valueAt(i).size();
859            }
860            return num;
861        }
862
863        public void clear() {
864            mUidMap.clear();
865        }
866
867        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
868            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
869            if (map == null) {
870                map = new ArrayMap<String, ArrayList<String>>();
871                mUidMap.put(userId, map);
872            }
873            return map;
874        }
875    }
876    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
877
878    // Service Connection to remote media container service to copy
879    // package uri's from external media onto secure containers
880    // or internal storage.
881    private IMediaContainerService mContainerService = null;
882
883    static final int SEND_PENDING_BROADCAST = 1;
884    static final int MCS_BOUND = 3;
885    static final int END_COPY = 4;
886    static final int INIT_COPY = 5;
887    static final int MCS_UNBIND = 6;
888    static final int START_CLEANING_PACKAGE = 7;
889    static final int FIND_INSTALL_LOC = 8;
890    static final int POST_INSTALL = 9;
891    static final int MCS_RECONNECT = 10;
892    static final int MCS_GIVE_UP = 11;
893    static final int UPDATED_MEDIA_STATUS = 12;
894    static final int WRITE_SETTINGS = 13;
895    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
896    static final int PACKAGE_VERIFIED = 15;
897    static final int CHECK_PENDING_VERIFICATION = 16;
898    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
899    static final int INTENT_FILTER_VERIFIED = 18;
900
901    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
902
903    // Delay time in millisecs
904    static final int BROADCAST_DELAY = 10 * 1000;
905
906    static UserManagerService sUserManager;
907
908    // Stores a list of users whose package restrictions file needs to be updated
909    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
910
911    final private DefaultContainerConnection mDefContainerConn =
912            new DefaultContainerConnection();
913    class DefaultContainerConnection implements ServiceConnection {
914        public void onServiceConnected(ComponentName name, IBinder service) {
915            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
916            IMediaContainerService imcs =
917                IMediaContainerService.Stub.asInterface(service);
918            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
919        }
920
921        public void onServiceDisconnected(ComponentName name) {
922            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
923        }
924    }
925
926    // Recordkeeping of restore-after-install operations that are currently in flight
927    // between the Package Manager and the Backup Manager
928    class PostInstallData {
929        public InstallArgs args;
930        public PackageInstalledInfo res;
931
932        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
933            args = _a;
934            res = _r;
935        }
936    }
937
938    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
939    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
940
941    // XML tags for backup/restore of various bits of state
942    private static final String TAG_PREFERRED_BACKUP = "pa";
943    private static final String TAG_DEFAULT_APPS = "da";
944    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
945
946    final String mRequiredVerifierPackage;
947    final String mRequiredInstallerPackage;
948
949    private final PackageUsage mPackageUsage = new PackageUsage();
950
951    private class PackageUsage {
952        private static final int WRITE_INTERVAL
953            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
954
955        private final Object mFileLock = new Object();
956        private final AtomicLong mLastWritten = new AtomicLong(0);
957        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
958
959        private boolean mIsHistoricalPackageUsageAvailable = true;
960
961        boolean isHistoricalPackageUsageAvailable() {
962            return mIsHistoricalPackageUsageAvailable;
963        }
964
965        void write(boolean force) {
966            if (force) {
967                writeInternal();
968                return;
969            }
970            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
971                && !DEBUG_DEXOPT) {
972                return;
973            }
974            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
975                new Thread("PackageUsage_DiskWriter") {
976                    @Override
977                    public void run() {
978                        try {
979                            writeInternal();
980                        } finally {
981                            mBackgroundWriteRunning.set(false);
982                        }
983                    }
984                }.start();
985            }
986        }
987
988        private void writeInternal() {
989            synchronized (mPackages) {
990                synchronized (mFileLock) {
991                    AtomicFile file = getFile();
992                    FileOutputStream f = null;
993                    try {
994                        f = file.startWrite();
995                        BufferedOutputStream out = new BufferedOutputStream(f);
996                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
997                        StringBuilder sb = new StringBuilder();
998                        for (PackageParser.Package pkg : mPackages.values()) {
999                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1000                                continue;
1001                            }
1002                            sb.setLength(0);
1003                            sb.append(pkg.packageName);
1004                            sb.append(' ');
1005                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1006                            sb.append('\n');
1007                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1008                        }
1009                        out.flush();
1010                        file.finishWrite(f);
1011                    } catch (IOException e) {
1012                        if (f != null) {
1013                            file.failWrite(f);
1014                        }
1015                        Log.e(TAG, "Failed to write package usage times", e);
1016                    }
1017                }
1018            }
1019            mLastWritten.set(SystemClock.elapsedRealtime());
1020        }
1021
1022        void readLP() {
1023            synchronized (mFileLock) {
1024                AtomicFile file = getFile();
1025                BufferedInputStream in = null;
1026                try {
1027                    in = new BufferedInputStream(file.openRead());
1028                    StringBuffer sb = new StringBuffer();
1029                    while (true) {
1030                        String packageName = readToken(in, sb, ' ');
1031                        if (packageName == null) {
1032                            break;
1033                        }
1034                        String timeInMillisString = readToken(in, sb, '\n');
1035                        if (timeInMillisString == null) {
1036                            throw new IOException("Failed to find last usage time for package "
1037                                                  + packageName);
1038                        }
1039                        PackageParser.Package pkg = mPackages.get(packageName);
1040                        if (pkg == null) {
1041                            continue;
1042                        }
1043                        long timeInMillis;
1044                        try {
1045                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1046                        } catch (NumberFormatException e) {
1047                            throw new IOException("Failed to parse " + timeInMillisString
1048                                                  + " as a long.", e);
1049                        }
1050                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1051                    }
1052                } catch (FileNotFoundException expected) {
1053                    mIsHistoricalPackageUsageAvailable = false;
1054                } catch (IOException e) {
1055                    Log.w(TAG, "Failed to read package usage times", e);
1056                } finally {
1057                    IoUtils.closeQuietly(in);
1058                }
1059            }
1060            mLastWritten.set(SystemClock.elapsedRealtime());
1061        }
1062
1063        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1064                throws IOException {
1065            sb.setLength(0);
1066            while (true) {
1067                int ch = in.read();
1068                if (ch == -1) {
1069                    if (sb.length() == 0) {
1070                        return null;
1071                    }
1072                    throw new IOException("Unexpected EOF");
1073                }
1074                if (ch == endOfToken) {
1075                    return sb.toString();
1076                }
1077                sb.append((char)ch);
1078            }
1079        }
1080
1081        private AtomicFile getFile() {
1082            File dataDir = Environment.getDataDirectory();
1083            File systemDir = new File(dataDir, "system");
1084            File fname = new File(systemDir, "package-usage.list");
1085            return new AtomicFile(fname);
1086        }
1087    }
1088
1089    class PackageHandler extends Handler {
1090        private boolean mBound = false;
1091        final ArrayList<HandlerParams> mPendingInstalls =
1092            new ArrayList<HandlerParams>();
1093
1094        private boolean connectToService() {
1095            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1096                    " DefaultContainerService");
1097            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1098            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1099            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1100                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1101                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1102                mBound = true;
1103                return true;
1104            }
1105            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1106            return false;
1107        }
1108
1109        private void disconnectService() {
1110            mContainerService = null;
1111            mBound = false;
1112            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1113            mContext.unbindService(mDefContainerConn);
1114            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1115        }
1116
1117        PackageHandler(Looper looper) {
1118            super(looper);
1119        }
1120
1121        public void handleMessage(Message msg) {
1122            try {
1123                doHandleMessage(msg);
1124            } finally {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126            }
1127        }
1128
1129        void doHandleMessage(Message msg) {
1130            switch (msg.what) {
1131                case INIT_COPY: {
1132                    HandlerParams params = (HandlerParams) msg.obj;
1133                    int idx = mPendingInstalls.size();
1134                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1135                    // If a bind was already initiated we dont really
1136                    // need to do anything. The pending install
1137                    // will be processed later on.
1138                    if (!mBound) {
1139                        // If this is the only one pending we might
1140                        // have to bind to the service again.
1141                        if (!connectToService()) {
1142                            Slog.e(TAG, "Failed to bind to media container service");
1143                            params.serviceError();
1144                            return;
1145                        } else {
1146                            // Once we bind to the service, the first
1147                            // pending request will be processed.
1148                            mPendingInstalls.add(idx, params);
1149                        }
1150                    } else {
1151                        mPendingInstalls.add(idx, params);
1152                        // Already bound to the service. Just make
1153                        // sure we trigger off processing the first request.
1154                        if (idx == 0) {
1155                            mHandler.sendEmptyMessage(MCS_BOUND);
1156                        }
1157                    }
1158                    break;
1159                }
1160                case MCS_BOUND: {
1161                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1162                    if (msg.obj != null) {
1163                        mContainerService = (IMediaContainerService) msg.obj;
1164                    }
1165                    if (mContainerService == null) {
1166                        if (!mBound) {
1167                            // Something seriously wrong since we are not bound and we are not
1168                            // waiting for connection. Bail out.
1169                            Slog.e(TAG, "Cannot bind to media container service");
1170                            for (HandlerParams params : mPendingInstalls) {
1171                                // Indicate service bind error
1172                                params.serviceError();
1173                            }
1174                            mPendingInstalls.clear();
1175                        } else {
1176                            Slog.w(TAG, "Waiting to connect to media container service");
1177                        }
1178                    } else if (mPendingInstalls.size() > 0) {
1179                        HandlerParams params = mPendingInstalls.get(0);
1180                        if (params != null) {
1181                            if (params.startCopy()) {
1182                                // We are done...  look for more work or to
1183                                // go idle.
1184                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1185                                        "Checking for more work or unbind...");
1186                                // Delete pending install
1187                                if (mPendingInstalls.size() > 0) {
1188                                    mPendingInstalls.remove(0);
1189                                }
1190                                if (mPendingInstalls.size() == 0) {
1191                                    if (mBound) {
1192                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1193                                                "Posting delayed MCS_UNBIND");
1194                                        removeMessages(MCS_UNBIND);
1195                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1196                                        // Unbind after a little delay, to avoid
1197                                        // continual thrashing.
1198                                        sendMessageDelayed(ubmsg, 10000);
1199                                    }
1200                                } else {
1201                                    // There are more pending requests in queue.
1202                                    // Just post MCS_BOUND message to trigger processing
1203                                    // of next pending install.
1204                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1205                                            "Posting MCS_BOUND for next work");
1206                                    mHandler.sendEmptyMessage(MCS_BOUND);
1207                                }
1208                            }
1209                        }
1210                    } else {
1211                        // Should never happen ideally.
1212                        Slog.w(TAG, "Empty queue");
1213                    }
1214                    break;
1215                }
1216                case MCS_RECONNECT: {
1217                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1218                    if (mPendingInstalls.size() > 0) {
1219                        if (mBound) {
1220                            disconnectService();
1221                        }
1222                        if (!connectToService()) {
1223                            Slog.e(TAG, "Failed to bind to media container service");
1224                            for (HandlerParams params : mPendingInstalls) {
1225                                // Indicate service bind error
1226                                params.serviceError();
1227                            }
1228                            mPendingInstalls.clear();
1229                        }
1230                    }
1231                    break;
1232                }
1233                case MCS_UNBIND: {
1234                    // If there is no actual work left, then time to unbind.
1235                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1236
1237                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1238                        if (mBound) {
1239                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1240
1241                            disconnectService();
1242                        }
1243                    } else if (mPendingInstalls.size() > 0) {
1244                        // There are more pending requests in queue.
1245                        // Just post MCS_BOUND message to trigger processing
1246                        // of next pending install.
1247                        mHandler.sendEmptyMessage(MCS_BOUND);
1248                    }
1249
1250                    break;
1251                }
1252                case MCS_GIVE_UP: {
1253                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1254                    mPendingInstalls.remove(0);
1255                    break;
1256                }
1257                case SEND_PENDING_BROADCAST: {
1258                    String packages[];
1259                    ArrayList<String> components[];
1260                    int size = 0;
1261                    int uids[];
1262                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1263                    synchronized (mPackages) {
1264                        if (mPendingBroadcasts == null) {
1265                            return;
1266                        }
1267                        size = mPendingBroadcasts.size();
1268                        if (size <= 0) {
1269                            // Nothing to be done. Just return
1270                            return;
1271                        }
1272                        packages = new String[size];
1273                        components = new ArrayList[size];
1274                        uids = new int[size];
1275                        int i = 0;  // filling out the above arrays
1276
1277                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1278                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1279                            Iterator<Map.Entry<String, ArrayList<String>>> it
1280                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1281                                            .entrySet().iterator();
1282                            while (it.hasNext() && i < size) {
1283                                Map.Entry<String, ArrayList<String>> ent = it.next();
1284                                packages[i] = ent.getKey();
1285                                components[i] = ent.getValue();
1286                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1287                                uids[i] = (ps != null)
1288                                        ? UserHandle.getUid(packageUserId, ps.appId)
1289                                        : -1;
1290                                i++;
1291                            }
1292                        }
1293                        size = i;
1294                        mPendingBroadcasts.clear();
1295                    }
1296                    // Send broadcasts
1297                    for (int i = 0; i < size; i++) {
1298                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1299                    }
1300                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1301                    break;
1302                }
1303                case START_CLEANING_PACKAGE: {
1304                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1305                    final String packageName = (String)msg.obj;
1306                    final int userId = msg.arg1;
1307                    final boolean andCode = msg.arg2 != 0;
1308                    synchronized (mPackages) {
1309                        if (userId == UserHandle.USER_ALL) {
1310                            int[] users = sUserManager.getUserIds();
1311                            for (int user : users) {
1312                                mSettings.addPackageToCleanLPw(
1313                                        new PackageCleanItem(user, packageName, andCode));
1314                            }
1315                        } else {
1316                            mSettings.addPackageToCleanLPw(
1317                                    new PackageCleanItem(userId, packageName, andCode));
1318                        }
1319                    }
1320                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1321                    startCleaningPackages();
1322                } break;
1323                case POST_INSTALL: {
1324                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1325                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1326                    mRunningInstalls.delete(msg.arg1);
1327                    boolean deleteOld = false;
1328
1329                    if (data != null) {
1330                        InstallArgs args = data.args;
1331                        PackageInstalledInfo res = data.res;
1332
1333                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1334                            final String packageName = res.pkg.applicationInfo.packageName;
1335                            res.removedInfo.sendBroadcast(false, true, false);
1336                            Bundle extras = new Bundle(1);
1337                            extras.putInt(Intent.EXTRA_UID, res.uid);
1338
1339                            // Now that we successfully installed the package, grant runtime
1340                            // permissions if requested before broadcasting the install.
1341                            if ((args.installFlags
1342                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1343                                grantRequestedRuntimePermissions(res.pkg,
1344                                        args.user.getIdentifier());
1345                            }
1346
1347                            // Determine the set of users who are adding this
1348                            // package for the first time vs. those who are seeing
1349                            // an update.
1350                            int[] firstUsers;
1351                            int[] updateUsers = new int[0];
1352                            if (res.origUsers == null || res.origUsers.length == 0) {
1353                                firstUsers = res.newUsers;
1354                            } else {
1355                                firstUsers = new int[0];
1356                                for (int i=0; i<res.newUsers.length; i++) {
1357                                    int user = res.newUsers[i];
1358                                    boolean isNew = true;
1359                                    for (int j=0; j<res.origUsers.length; j++) {
1360                                        if (res.origUsers[j] == user) {
1361                                            isNew = false;
1362                                            break;
1363                                        }
1364                                    }
1365                                    if (isNew) {
1366                                        int[] newFirst = new int[firstUsers.length+1];
1367                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1368                                                firstUsers.length);
1369                                        newFirst[firstUsers.length] = user;
1370                                        firstUsers = newFirst;
1371                                    } else {
1372                                        int[] newUpdate = new int[updateUsers.length+1];
1373                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1374                                                updateUsers.length);
1375                                        newUpdate[updateUsers.length] = user;
1376                                        updateUsers = newUpdate;
1377                                    }
1378                                }
1379                            }
1380                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1381                                    packageName, extras, null, null, firstUsers);
1382                            final boolean update = res.removedInfo.removedPackage != null;
1383                            if (update) {
1384                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1385                            }
1386                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1387                                    packageName, extras, null, null, updateUsers);
1388                            if (update) {
1389                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1390                                        packageName, extras, null, null, updateUsers);
1391                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1392                                        null, null, packageName, null, updateUsers);
1393
1394                                // treat asec-hosted packages like removable media on upgrade
1395                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1396                                    if (DEBUG_INSTALL) {
1397                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1398                                                + " is ASEC-hosted -> AVAILABLE");
1399                                    }
1400                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1401                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1402                                    pkgList.add(packageName);
1403                                    sendResourcesChangedBroadcast(true, true,
1404                                            pkgList,uidArray, null);
1405                                }
1406                            }
1407                            if (res.removedInfo.args != null) {
1408                                // Remove the replaced package's older resources safely now
1409                                deleteOld = true;
1410                            }
1411
1412                            // If this app is a browser and it's newly-installed for some
1413                            // users, clear any default-browser state in those users
1414                            if (firstUsers.length > 0) {
1415                                // the app's nature doesn't depend on the user, so we can just
1416                                // check its browser nature in any user and generalize.
1417                                if (packageIsBrowser(packageName, firstUsers[0])) {
1418                                    synchronized (mPackages) {
1419                                        for (int userId : firstUsers) {
1420                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1421                                        }
1422                                    }
1423                                }
1424                            }
1425                            // Log current value of "unknown sources" setting
1426                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1427                                getUnknownSourcesSettings());
1428                        }
1429                        // Force a gc to clear up things
1430                        Runtime.getRuntime().gc();
1431                        // We delete after a gc for applications  on sdcard.
1432                        if (deleteOld) {
1433                            synchronized (mInstallLock) {
1434                                res.removedInfo.args.doPostDeleteLI(true);
1435                            }
1436                        }
1437                        if (args.observer != null) {
1438                            try {
1439                                Bundle extras = extrasForInstallResult(res);
1440                                args.observer.onPackageInstalled(res.name, res.returnCode,
1441                                        res.returnMsg, extras);
1442                            } catch (RemoteException e) {
1443                                Slog.i(TAG, "Observer no longer exists.");
1444                            }
1445                        }
1446                    } else {
1447                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1448                    }
1449                } break;
1450                case UPDATED_MEDIA_STATUS: {
1451                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1452                    boolean reportStatus = msg.arg1 == 1;
1453                    boolean doGc = msg.arg2 == 1;
1454                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1455                    if (doGc) {
1456                        // Force a gc to clear up stale containers.
1457                        Runtime.getRuntime().gc();
1458                    }
1459                    if (msg.obj != null) {
1460                        @SuppressWarnings("unchecked")
1461                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1462                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1463                        // Unload containers
1464                        unloadAllContainers(args);
1465                    }
1466                    if (reportStatus) {
1467                        try {
1468                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1469                            PackageHelper.getMountService().finishMediaUpdate();
1470                        } catch (RemoteException e) {
1471                            Log.e(TAG, "MountService not running?");
1472                        }
1473                    }
1474                } break;
1475                case WRITE_SETTINGS: {
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1477                    synchronized (mPackages) {
1478                        removeMessages(WRITE_SETTINGS);
1479                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1480                        mSettings.writeLPr();
1481                        mDirtyUsers.clear();
1482                    }
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1484                } break;
1485                case WRITE_PACKAGE_RESTRICTIONS: {
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                    synchronized (mPackages) {
1488                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1489                        for (int userId : mDirtyUsers) {
1490                            mSettings.writePackageRestrictionsLPr(userId);
1491                        }
1492                        mDirtyUsers.clear();
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                } break;
1496                case CHECK_PENDING_VERIFICATION: {
1497                    final int verificationId = msg.arg1;
1498                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1499
1500                    if ((state != null) && !state.timeoutExtended()) {
1501                        final InstallArgs args = state.getInstallArgs();
1502                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1503
1504                        Slog.i(TAG, "Verification timed out for " + originUri);
1505                        mPendingVerification.remove(verificationId);
1506
1507                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1508
1509                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1510                            Slog.i(TAG, "Continuing with installation of " + originUri);
1511                            state.setVerifierResponse(Binder.getCallingUid(),
1512                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    PackageManager.VERIFICATION_ALLOW,
1515                                    state.getInstallArgs().getUser());
1516                            try {
1517                                ret = args.copyApk(mContainerService, true);
1518                            } catch (RemoteException e) {
1519                                Slog.e(TAG, "Could not contact the ContainerService");
1520                            }
1521                        } else {
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_REJECT,
1524                                    state.getInstallArgs().getUser());
1525                        }
1526
1527                        processPendingInstall(args, ret);
1528                        mHandler.sendEmptyMessage(MCS_UNBIND);
1529                    }
1530                    break;
1531                }
1532                case PACKAGE_VERIFIED: {
1533                    final int verificationId = msg.arg1;
1534
1535                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1536                    if (state == null) {
1537                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1538                        break;
1539                    }
1540
1541                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1542
1543                    state.setVerifierResponse(response.callerUid, response.code);
1544
1545                    if (state.isVerificationComplete()) {
1546                        mPendingVerification.remove(verificationId);
1547
1548                        final InstallArgs args = state.getInstallArgs();
1549                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1550
1551                        int ret;
1552                        if (state.isInstallAllowed()) {
1553                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1554                            broadcastPackageVerified(verificationId, originUri,
1555                                    response.code, state.getInstallArgs().getUser());
1556                            try {
1557                                ret = args.copyApk(mContainerService, true);
1558                            } catch (RemoteException e) {
1559                                Slog.e(TAG, "Could not contact the ContainerService");
1560                            }
1561                        } else {
1562                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1563                        }
1564
1565                        processPendingInstall(args, ret);
1566
1567                        mHandler.sendEmptyMessage(MCS_UNBIND);
1568                    }
1569
1570                    break;
1571                }
1572                case START_INTENT_FILTER_VERIFICATIONS: {
1573                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1574                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1575                            params.replacing, params.pkg);
1576                    break;
1577                }
1578                case INTENT_FILTER_VERIFIED: {
1579                    final int verificationId = msg.arg1;
1580
1581                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1582                            verificationId);
1583                    if (state == null) {
1584                        Slog.w(TAG, "Invalid IntentFilter verification token "
1585                                + verificationId + " received");
1586                        break;
1587                    }
1588
1589                    final int userId = state.getUserId();
1590
1591                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1592                            "Processing IntentFilter verification with token:"
1593                            + verificationId + " and userId:" + userId);
1594
1595                    final IntentFilterVerificationResponse response =
1596                            (IntentFilterVerificationResponse) msg.obj;
1597
1598                    state.setVerifierResponse(response.callerUid, response.code);
1599
1600                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1601                            "IntentFilter verification with token:" + verificationId
1602                            + " and userId:" + userId
1603                            + " is settings verifier response with response code:"
1604                            + response.code);
1605
1606                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1607                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1608                                + response.getFailedDomainsString());
1609                    }
1610
1611                    if (state.isVerificationComplete()) {
1612                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1613                    } else {
1614                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                                "IntentFilter verification with token:" + verificationId
1616                                + " was not said to be complete");
1617                    }
1618
1619                    break;
1620                }
1621            }
1622        }
1623    }
1624
1625    private StorageEventListener mStorageListener = new StorageEventListener() {
1626        @Override
1627        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1628            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1629                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1630                    final String volumeUuid = vol.getFsUuid();
1631
1632                    // Clean up any users or apps that were removed or recreated
1633                    // while this volume was missing
1634                    reconcileUsers(volumeUuid);
1635                    reconcileApps(volumeUuid);
1636
1637                    // Clean up any install sessions that expired or were
1638                    // cancelled while this volume was missing
1639                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1640
1641                    loadPrivatePackages(vol);
1642
1643                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1644                    unloadPrivatePackages(vol);
1645                }
1646            }
1647
1648            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1649                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1650                    updateExternalMediaStatus(true, false);
1651                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1652                    updateExternalMediaStatus(false, false);
1653                }
1654            }
1655        }
1656
1657        @Override
1658        public void onVolumeForgotten(String fsUuid) {
1659            // Remove any apps installed on the forgotten volume
1660            synchronized (mPackages) {
1661                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1662                for (PackageSetting ps : packages) {
1663                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1664                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1665                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1666                }
1667
1668                mSettings.writeLPr();
1669            }
1670        }
1671    };
1672
1673    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1674        if (userId >= UserHandle.USER_OWNER) {
1675            grantRequestedRuntimePermissionsForUser(pkg, userId);
1676        } else if (userId == UserHandle.USER_ALL) {
1677            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1678                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1679            }
1680        }
1681
1682        // We could have touched GID membership, so flush out packages.list
1683        synchronized (mPackages) {
1684            mSettings.writePackageListLPr();
1685        }
1686    }
1687
1688    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1689        SettingBase sb = (SettingBase) pkg.mExtras;
1690        if (sb == null) {
1691            return;
1692        }
1693
1694        PermissionsState permissionsState = sb.getPermissionsState();
1695
1696        for (String permission : pkg.requestedPermissions) {
1697            BasePermission bp = mSettings.mPermissions.get(permission);
1698            if (bp != null && bp.isRuntime()) {
1699                permissionsState.grantRuntimePermission(bp, userId);
1700            }
1701        }
1702    }
1703
1704    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1705        Bundle extras = null;
1706        switch (res.returnCode) {
1707            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1708                extras = new Bundle();
1709                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1710                        res.origPermission);
1711                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1712                        res.origPackage);
1713                break;
1714            }
1715            case PackageManager.INSTALL_SUCCEEDED: {
1716                extras = new Bundle();
1717                extras.putBoolean(Intent.EXTRA_REPLACING,
1718                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1719                break;
1720            }
1721        }
1722        return extras;
1723    }
1724
1725    void scheduleWriteSettingsLocked() {
1726        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1727            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1728        }
1729    }
1730
1731    void scheduleWritePackageRestrictionsLocked(int userId) {
1732        if (!sUserManager.exists(userId)) return;
1733        mDirtyUsers.add(userId);
1734        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1735            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1736        }
1737    }
1738
1739    public static PackageManagerService main(Context context, Installer installer,
1740            boolean factoryTest, boolean onlyCore) {
1741        PackageManagerService m = new PackageManagerService(context, installer,
1742                factoryTest, onlyCore);
1743        ServiceManager.addService("package", m);
1744        return m;
1745    }
1746
1747    static String[] splitString(String str, char sep) {
1748        int count = 1;
1749        int i = 0;
1750        while ((i=str.indexOf(sep, i)) >= 0) {
1751            count++;
1752            i++;
1753        }
1754
1755        String[] res = new String[count];
1756        i=0;
1757        count = 0;
1758        int lastI=0;
1759        while ((i=str.indexOf(sep, i)) >= 0) {
1760            res[count] = str.substring(lastI, i);
1761            count++;
1762            i++;
1763            lastI = i;
1764        }
1765        res[count] = str.substring(lastI, str.length());
1766        return res;
1767    }
1768
1769    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1770        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1771                Context.DISPLAY_SERVICE);
1772        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1773    }
1774
1775    public PackageManagerService(Context context, Installer installer,
1776            boolean factoryTest, boolean onlyCore) {
1777        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1778                SystemClock.uptimeMillis());
1779
1780        if (mSdkVersion <= 0) {
1781            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1782        }
1783
1784        mContext = context;
1785        mFactoryTest = factoryTest;
1786        mOnlyCore = onlyCore;
1787        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1788        mMetrics = new DisplayMetrics();
1789        mSettings = new Settings(mPackages);
1790        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1791                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1792        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1793                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1794        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1795                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1796        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1797                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1798        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1799                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1800        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1801                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1802
1803        // TODO: add a property to control this?
1804        long dexOptLRUThresholdInMinutes;
1805        if (mLazyDexOpt) {
1806            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1807        } else {
1808            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1809        }
1810        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1811
1812        String separateProcesses = SystemProperties.get("debug.separate_processes");
1813        if (separateProcesses != null && separateProcesses.length() > 0) {
1814            if ("*".equals(separateProcesses)) {
1815                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1816                mSeparateProcesses = null;
1817                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1818            } else {
1819                mDefParseFlags = 0;
1820                mSeparateProcesses = separateProcesses.split(",");
1821                Slog.w(TAG, "Running with debug.separate_processes: "
1822                        + separateProcesses);
1823            }
1824        } else {
1825            mDefParseFlags = 0;
1826            mSeparateProcesses = null;
1827        }
1828
1829        mInstaller = installer;
1830        mPackageDexOptimizer = new PackageDexOptimizer(this);
1831        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1832
1833        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1834                FgThread.get().getLooper());
1835
1836        getDefaultDisplayMetrics(context, mMetrics);
1837
1838        SystemConfig systemConfig = SystemConfig.getInstance();
1839        mGlobalGids = systemConfig.getGlobalGids();
1840        mSystemPermissions = systemConfig.getSystemPermissions();
1841        mAvailableFeatures = systemConfig.getAvailableFeatures();
1842
1843        synchronized (mInstallLock) {
1844        // writer
1845        synchronized (mPackages) {
1846            mHandlerThread = new ServiceThread(TAG,
1847                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1848            mHandlerThread.start();
1849            mHandler = new PackageHandler(mHandlerThread.getLooper());
1850            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1851
1852            File dataDir = Environment.getDataDirectory();
1853            mAppDataDir = new File(dataDir, "data");
1854            mAppInstallDir = new File(dataDir, "app");
1855            mAppLib32InstallDir = new File(dataDir, "app-lib");
1856            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1857            mUserAppDataDir = new File(dataDir, "user");
1858            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1859
1860            sUserManager = new UserManagerService(context, this,
1861                    mInstallLock, mPackages);
1862
1863            // Propagate permission configuration in to package manager.
1864            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1865                    = systemConfig.getPermissions();
1866            for (int i=0; i<permConfig.size(); i++) {
1867                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1868                BasePermission bp = mSettings.mPermissions.get(perm.name);
1869                if (bp == null) {
1870                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1871                    mSettings.mPermissions.put(perm.name, bp);
1872                }
1873                if (perm.gids != null) {
1874                    bp.setGids(perm.gids, perm.perUser);
1875                }
1876            }
1877
1878            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1879            for (int i=0; i<libConfig.size(); i++) {
1880                mSharedLibraries.put(libConfig.keyAt(i),
1881                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1882            }
1883
1884            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1885
1886            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1887                    mSdkVersion, mOnlyCore);
1888
1889            String customResolverActivity = Resources.getSystem().getString(
1890                    R.string.config_customResolverActivity);
1891            if (TextUtils.isEmpty(customResolverActivity)) {
1892                customResolverActivity = null;
1893            } else {
1894                mCustomResolverComponentName = ComponentName.unflattenFromString(
1895                        customResolverActivity);
1896            }
1897
1898            long startTime = SystemClock.uptimeMillis();
1899
1900            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1901                    startTime);
1902
1903            // Set flag to monitor and not change apk file paths when
1904            // scanning install directories.
1905            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1906
1907            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1908
1909            /**
1910             * Add everything in the in the boot class path to the
1911             * list of process files because dexopt will have been run
1912             * if necessary during zygote startup.
1913             */
1914            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1915            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1916
1917            if (bootClassPath != null) {
1918                String[] bootClassPathElements = splitString(bootClassPath, ':');
1919                for (String element : bootClassPathElements) {
1920                    alreadyDexOpted.add(element);
1921                }
1922            } else {
1923                Slog.w(TAG, "No BOOTCLASSPATH found!");
1924            }
1925
1926            if (systemServerClassPath != null) {
1927                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1928                for (String element : systemServerClassPathElements) {
1929                    alreadyDexOpted.add(element);
1930                }
1931            } else {
1932                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1933            }
1934
1935            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1936            final String[] dexCodeInstructionSets =
1937                    getDexCodeInstructionSets(
1938                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1939
1940            /**
1941             * Ensure all external libraries have had dexopt run on them.
1942             */
1943            if (mSharedLibraries.size() > 0) {
1944                // NOTE: For now, we're compiling these system "shared libraries"
1945                // (and framework jars) into all available architectures. It's possible
1946                // to compile them only when we come across an app that uses them (there's
1947                // already logic for that in scanPackageLI) but that adds some complexity.
1948                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1949                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1950                        final String lib = libEntry.path;
1951                        if (lib == null) {
1952                            continue;
1953                        }
1954
1955                        try {
1956                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1957                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1958                                alreadyDexOpted.add(lib);
1959                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1960                            }
1961                        } catch (FileNotFoundException e) {
1962                            Slog.w(TAG, "Library not found: " + lib);
1963                        } catch (IOException e) {
1964                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1965                                    + e.getMessage());
1966                        }
1967                    }
1968                }
1969            }
1970
1971            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1972
1973            // Gross hack for now: we know this file doesn't contain any
1974            // code, so don't dexopt it to avoid the resulting log spew.
1975            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1976
1977            // Gross hack for now: we know this file is only part of
1978            // the boot class path for art, so don't dexopt it to
1979            // avoid the resulting log spew.
1980            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1981
1982            /**
1983             * There are a number of commands implemented in Java, which
1984             * we currently need to do the dexopt on so that they can be
1985             * run from a non-root shell.
1986             */
1987            String[] frameworkFiles = frameworkDir.list();
1988            if (frameworkFiles != null) {
1989                // TODO: We could compile these only for the most preferred ABI. We should
1990                // first double check that the dex files for these commands are not referenced
1991                // by other system apps.
1992                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1993                    for (int i=0; i<frameworkFiles.length; i++) {
1994                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1995                        String path = libPath.getPath();
1996                        // Skip the file if we already did it.
1997                        if (alreadyDexOpted.contains(path)) {
1998                            continue;
1999                        }
2000                        // Skip the file if it is not a type we want to dexopt.
2001                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2002                            continue;
2003                        }
2004                        try {
2005                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2006                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2007                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2008                            }
2009                        } catch (FileNotFoundException e) {
2010                            Slog.w(TAG, "Jar not found: " + path);
2011                        } catch (IOException e) {
2012                            Slog.w(TAG, "Exception reading jar: " + path, e);
2013                        }
2014                    }
2015                }
2016            }
2017
2018            // Collect vendor overlay packages.
2019            // (Do this before scanning any apps.)
2020            // For security and version matching reason, only consider
2021            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2022            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2023            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2024                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2025
2026            // Find base frameworks (resource packages without code).
2027            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2028                    | PackageParser.PARSE_IS_SYSTEM_DIR
2029                    | PackageParser.PARSE_IS_PRIVILEGED,
2030                    scanFlags | SCAN_NO_DEX, 0);
2031
2032            // Collected privileged system packages.
2033            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2034            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2035                    | PackageParser.PARSE_IS_SYSTEM_DIR
2036                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2037
2038            // Collect ordinary system packages.
2039            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2040            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2041                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2042
2043            // Collect all vendor packages.
2044            File vendorAppDir = new File("/vendor/app");
2045            try {
2046                vendorAppDir = vendorAppDir.getCanonicalFile();
2047            } catch (IOException e) {
2048                // failed to look up canonical path, continue with original one
2049            }
2050            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2051                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2052
2053            // Collect all OEM packages.
2054            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2055            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2056                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2057
2058            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2059            mInstaller.moveFiles();
2060
2061            // Prune any system packages that no longer exist.
2062            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2063            if (!mOnlyCore) {
2064                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2065                while (psit.hasNext()) {
2066                    PackageSetting ps = psit.next();
2067
2068                    /*
2069                     * If this is not a system app, it can't be a
2070                     * disable system app.
2071                     */
2072                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2073                        continue;
2074                    }
2075
2076                    /*
2077                     * If the package is scanned, it's not erased.
2078                     */
2079                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2080                    if (scannedPkg != null) {
2081                        /*
2082                         * If the system app is both scanned and in the
2083                         * disabled packages list, then it must have been
2084                         * added via OTA. Remove it from the currently
2085                         * scanned package so the previously user-installed
2086                         * application can be scanned.
2087                         */
2088                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2089                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2090                                    + ps.name + "; removing system app.  Last known codePath="
2091                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2092                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2093                                    + scannedPkg.mVersionCode);
2094                            removePackageLI(ps, true);
2095                            mExpectingBetter.put(ps.name, ps.codePath);
2096                        }
2097
2098                        continue;
2099                    }
2100
2101                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2102                        psit.remove();
2103                        logCriticalInfo(Log.WARN, "System package " + ps.name
2104                                + " no longer exists; wiping its data");
2105                        removeDataDirsLI(null, ps.name);
2106                    } else {
2107                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2108                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2109                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2110                        }
2111                    }
2112                }
2113            }
2114
2115            //look for any incomplete package installations
2116            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2117            //clean up list
2118            for(int i = 0; i < deletePkgsList.size(); i++) {
2119                //clean up here
2120                cleanupInstallFailedPackage(deletePkgsList.get(i));
2121            }
2122            //delete tmp files
2123            deleteTempPackageFiles();
2124
2125            // Remove any shared userIDs that have no associated packages
2126            mSettings.pruneSharedUsersLPw();
2127
2128            if (!mOnlyCore) {
2129                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2130                        SystemClock.uptimeMillis());
2131                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2132
2133                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2134                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2135
2136                /**
2137                 * Remove disable package settings for any updated system
2138                 * apps that were removed via an OTA. If they're not a
2139                 * previously-updated app, remove them completely.
2140                 * Otherwise, just revoke their system-level permissions.
2141                 */
2142                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2143                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2144                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2145
2146                    String msg;
2147                    if (deletedPkg == null) {
2148                        msg = "Updated system package " + deletedAppName
2149                                + " no longer exists; wiping its data";
2150                        removeDataDirsLI(null, deletedAppName);
2151                    } else {
2152                        msg = "Updated system app + " + deletedAppName
2153                                + " no longer present; removing system privileges for "
2154                                + deletedAppName;
2155
2156                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2157
2158                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2159                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2160                    }
2161                    logCriticalInfo(Log.WARN, msg);
2162                }
2163
2164                /**
2165                 * Make sure all system apps that we expected to appear on
2166                 * the userdata partition actually showed up. If they never
2167                 * appeared, crawl back and revive the system version.
2168                 */
2169                for (int i = 0; i < mExpectingBetter.size(); i++) {
2170                    final String packageName = mExpectingBetter.keyAt(i);
2171                    if (!mPackages.containsKey(packageName)) {
2172                        final File scanFile = mExpectingBetter.valueAt(i);
2173
2174                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2175                                + " but never showed up; reverting to system");
2176
2177                        final int reparseFlags;
2178                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2179                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2180                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2181                                    | PackageParser.PARSE_IS_PRIVILEGED;
2182                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2183                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2184                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2185                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2186                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2187                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2188                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2189                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2190                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2191                        } else {
2192                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2193                            continue;
2194                        }
2195
2196                        mSettings.enableSystemPackageLPw(packageName);
2197
2198                        try {
2199                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2200                        } catch (PackageManagerException e) {
2201                            Slog.e(TAG, "Failed to parse original system package: "
2202                                    + e.getMessage());
2203                        }
2204                    }
2205                }
2206            }
2207            mExpectingBetter.clear();
2208
2209            // Now that we know all of the shared libraries, update all clients to have
2210            // the correct library paths.
2211            updateAllSharedLibrariesLPw();
2212
2213            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2214                // NOTE: We ignore potential failures here during a system scan (like
2215                // the rest of the commands above) because there's precious little we
2216                // can do about it. A settings error is reported, though.
2217                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2218                        false /* force dexopt */, false /* defer dexopt */);
2219            }
2220
2221            // Now that we know all the packages we are keeping,
2222            // read and update their last usage times.
2223            mPackageUsage.readLP();
2224
2225            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2226                    SystemClock.uptimeMillis());
2227            Slog.i(TAG, "Time to scan packages: "
2228                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2229                    + " seconds");
2230
2231            // If the platform SDK has changed since the last time we booted,
2232            // we need to re-grant app permission to catch any new ones that
2233            // appear.  This is really a hack, and means that apps can in some
2234            // cases get permissions that the user didn't initially explicitly
2235            // allow...  it would be nice to have some better way to handle
2236            // this situation.
2237            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2238                    != mSdkVersion;
2239            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2240                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2241                    + "; regranting permissions for internal storage");
2242            mSettings.mInternalSdkPlatform = mSdkVersion;
2243
2244            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2245                    | (regrantPermissions
2246                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2247                            : 0));
2248
2249            // If this is the first boot, and it is a normal boot, then
2250            // we need to initialize the default preferred apps.
2251            if (!mRestoredSettings && !onlyCore) {
2252                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2253                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2254                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2255            }
2256
2257            // If this is first boot after an OTA, and a normal boot, then
2258            // we need to clear code cache directories.
2259            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2260            if (mIsUpgrade && !onlyCore) {
2261                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2262                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2263                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2264                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2265                }
2266                mSettings.mFingerprint = Build.FINGERPRINT;
2267            }
2268
2269            checkDefaultBrowser();
2270
2271            // All the changes are done during package scanning.
2272            mSettings.updateInternalDatabaseVersion();
2273
2274            // can downgrade to reader
2275            mSettings.writeLPr();
2276
2277            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2278                    SystemClock.uptimeMillis());
2279
2280            mRequiredVerifierPackage = getRequiredVerifierLPr();
2281            mRequiredInstallerPackage = getRequiredInstallerLPr();
2282
2283            mInstallerService = new PackageInstallerService(context, this);
2284
2285            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2286            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2287                    mIntentFilterVerifierComponent);
2288
2289        } // synchronized (mPackages)
2290        } // synchronized (mInstallLock)
2291
2292        // Now after opening every single application zip, make sure they
2293        // are all flushed.  Not really needed, but keeps things nice and
2294        // tidy.
2295        Runtime.getRuntime().gc();
2296
2297        // Expose private service for system components to use.
2298        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2299    }
2300
2301    @Override
2302    public boolean isFirstBoot() {
2303        return !mRestoredSettings;
2304    }
2305
2306    @Override
2307    public boolean isOnlyCoreApps() {
2308        return mOnlyCore;
2309    }
2310
2311    @Override
2312    public boolean isUpgrade() {
2313        return mIsUpgrade;
2314    }
2315
2316    private String getRequiredVerifierLPr() {
2317        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2318        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2319                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2320
2321        String requiredVerifier = null;
2322
2323        final int N = receivers.size();
2324        for (int i = 0; i < N; i++) {
2325            final ResolveInfo info = receivers.get(i);
2326
2327            if (info.activityInfo == null) {
2328                continue;
2329            }
2330
2331            final String packageName = info.activityInfo.packageName;
2332
2333            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2334                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2335                continue;
2336            }
2337
2338            if (requiredVerifier != null) {
2339                throw new RuntimeException("There can be only one required verifier");
2340            }
2341
2342            requiredVerifier = packageName;
2343        }
2344
2345        return requiredVerifier;
2346    }
2347
2348    private String getRequiredInstallerLPr() {
2349        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2350        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2351        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2352
2353        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2354                PACKAGE_MIME_TYPE, 0, 0);
2355
2356        String requiredInstaller = null;
2357
2358        final int N = installers.size();
2359        for (int i = 0; i < N; i++) {
2360            final ResolveInfo info = installers.get(i);
2361            final String packageName = info.activityInfo.packageName;
2362
2363            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2364                continue;
2365            }
2366
2367            if (requiredInstaller != null) {
2368                throw new RuntimeException("There must be one required installer");
2369            }
2370
2371            requiredInstaller = packageName;
2372        }
2373
2374        if (requiredInstaller == null) {
2375            throw new RuntimeException("There must be one required installer");
2376        }
2377
2378        return requiredInstaller;
2379    }
2380
2381    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2382        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2383        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2384                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2385
2386        ComponentName verifierComponentName = null;
2387
2388        int priority = -1000;
2389        final int N = receivers.size();
2390        for (int i = 0; i < N; i++) {
2391            final ResolveInfo info = receivers.get(i);
2392
2393            if (info.activityInfo == null) {
2394                continue;
2395            }
2396
2397            final String packageName = info.activityInfo.packageName;
2398
2399            final PackageSetting ps = mSettings.mPackages.get(packageName);
2400            if (ps == null) {
2401                continue;
2402            }
2403
2404            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2405                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2406                continue;
2407            }
2408
2409            // Select the IntentFilterVerifier with the highest priority
2410            if (priority < info.priority) {
2411                priority = info.priority;
2412                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2413                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2414                        + verifierComponentName + " with priority: " + info.priority);
2415            }
2416        }
2417
2418        return verifierComponentName;
2419    }
2420
2421    private void primeDomainVerificationsLPw(int userId) {
2422        if (DEBUG_DOMAIN_VERIFICATION) {
2423            Slog.d(TAG, "Priming domain verifications in user " + userId);
2424        }
2425
2426        SystemConfig systemConfig = SystemConfig.getInstance();
2427        ArraySet<String> packages = systemConfig.getLinkedApps();
2428        ArraySet<String> domains = new ArraySet<String>();
2429
2430        for (String packageName : packages) {
2431            PackageParser.Package pkg = mPackages.get(packageName);
2432            if (pkg != null) {
2433                if (!pkg.isSystemApp()) {
2434                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2435                    continue;
2436                }
2437
2438                domains.clear();
2439                for (PackageParser.Activity a : pkg.activities) {
2440                    for (ActivityIntentInfo filter : a.intents) {
2441                        if (hasValidDomains(filter)) {
2442                            domains.addAll(filter.getHostsList());
2443                        }
2444                    }
2445                }
2446
2447                if (domains.size() > 0) {
2448                    if (DEBUG_DOMAIN_VERIFICATION) {
2449                        Slog.v(TAG, "      + " + packageName);
2450                    }
2451                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2452                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2453                    // and then 'always' in the per-user state actually used for intent resolution.
2454                    final IntentFilterVerificationInfo ivi;
2455                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2456                            new ArrayList<String>(domains));
2457                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2458                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2459                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2460                } else {
2461                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2462                            + "' does not handle web links");
2463                }
2464            } else {
2465                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2466            }
2467        }
2468
2469        scheduleWritePackageRestrictionsLocked(userId);
2470        scheduleWriteSettingsLocked();
2471    }
2472
2473    private void applyFactoryDefaultBrowserLPw(int userId) {
2474        // The default browser app's package name is stored in a string resource,
2475        // with a product-specific overlay used for vendor customization.
2476        String browserPkg = mContext.getResources().getString(
2477                com.android.internal.R.string.default_browser);
2478        if (!TextUtils.isEmpty(browserPkg)) {
2479            // non-empty string => required to be a known package
2480            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2481            if (ps == null) {
2482                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2483                browserPkg = null;
2484            } else {
2485                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2486            }
2487        }
2488
2489        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2490        // default.  If there's more than one, just leave everything alone.
2491        if (browserPkg == null) {
2492            calculateDefaultBrowserLPw(userId);
2493        }
2494    }
2495
2496    private void calculateDefaultBrowserLPw(int userId) {
2497        List<String> allBrowsers = resolveAllBrowserApps(userId);
2498        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2499        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2500    }
2501
2502    private List<String> resolveAllBrowserApps(int userId) {
2503        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2504        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2505                PackageManager.MATCH_ALL, userId);
2506
2507        final int count = list.size();
2508        List<String> result = new ArrayList<String>(count);
2509        for (int i=0; i<count; i++) {
2510            ResolveInfo info = list.get(i);
2511            if (info.activityInfo == null
2512                    || !info.handleAllWebDataURI
2513                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2514                    || result.contains(info.activityInfo.packageName)) {
2515                continue;
2516            }
2517            result.add(info.activityInfo.packageName);
2518        }
2519
2520        return result;
2521    }
2522
2523    private boolean packageIsBrowser(String packageName, int userId) {
2524        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2525                PackageManager.MATCH_ALL, userId);
2526        final int N = list.size();
2527        for (int i = 0; i < N; i++) {
2528            ResolveInfo info = list.get(i);
2529            if (packageName.equals(info.activityInfo.packageName)) {
2530                return true;
2531            }
2532        }
2533        return false;
2534    }
2535
2536    private void checkDefaultBrowser() {
2537        final int myUserId = UserHandle.myUserId();
2538        final String packageName = getDefaultBrowserPackageName(myUserId);
2539        if (packageName != null) {
2540            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2541            if (info == null) {
2542                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2543                synchronized (mPackages) {
2544                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2545                }
2546            }
2547        }
2548    }
2549
2550    @Override
2551    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2552            throws RemoteException {
2553        try {
2554            return super.onTransact(code, data, reply, flags);
2555        } catch (RuntimeException e) {
2556            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2557                Slog.wtf(TAG, "Package Manager Crash", e);
2558            }
2559            throw e;
2560        }
2561    }
2562
2563    void cleanupInstallFailedPackage(PackageSetting ps) {
2564        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2565
2566        removeDataDirsLI(ps.volumeUuid, ps.name);
2567        if (ps.codePath != null) {
2568            if (ps.codePath.isDirectory()) {
2569                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2570            } else {
2571                ps.codePath.delete();
2572            }
2573        }
2574        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2575            if (ps.resourcePath.isDirectory()) {
2576                FileUtils.deleteContents(ps.resourcePath);
2577            }
2578            ps.resourcePath.delete();
2579        }
2580        mSettings.removePackageLPw(ps.name);
2581    }
2582
2583    static int[] appendInts(int[] cur, int[] add) {
2584        if (add == null) return cur;
2585        if (cur == null) return add;
2586        final int N = add.length;
2587        for (int i=0; i<N; i++) {
2588            cur = appendInt(cur, add[i]);
2589        }
2590        return cur;
2591    }
2592
2593    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2594        if (!sUserManager.exists(userId)) return null;
2595        final PackageSetting ps = (PackageSetting) p.mExtras;
2596        if (ps == null) {
2597            return null;
2598        }
2599
2600        final PermissionsState permissionsState = ps.getPermissionsState();
2601
2602        final int[] gids = permissionsState.computeGids(userId);
2603        final Set<String> permissions = permissionsState.getPermissions(userId);
2604        final PackageUserState state = ps.readUserState(userId);
2605
2606        return PackageParser.generatePackageInfo(p, gids, flags,
2607                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2608    }
2609
2610    @Override
2611    public boolean isPackageFrozen(String packageName) {
2612        synchronized (mPackages) {
2613            final PackageSetting ps = mSettings.mPackages.get(packageName);
2614            if (ps != null) {
2615                return ps.frozen;
2616            }
2617        }
2618        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2619        return true;
2620    }
2621
2622    @Override
2623    public boolean isPackageAvailable(String packageName, int userId) {
2624        if (!sUserManager.exists(userId)) return false;
2625        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2626        synchronized (mPackages) {
2627            PackageParser.Package p = mPackages.get(packageName);
2628            if (p != null) {
2629                final PackageSetting ps = (PackageSetting) p.mExtras;
2630                if (ps != null) {
2631                    final PackageUserState state = ps.readUserState(userId);
2632                    if (state != null) {
2633                        return PackageParser.isAvailable(state);
2634                    }
2635                }
2636            }
2637        }
2638        return false;
2639    }
2640
2641    @Override
2642    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2643        if (!sUserManager.exists(userId)) return null;
2644        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2645        // reader
2646        synchronized (mPackages) {
2647            PackageParser.Package p = mPackages.get(packageName);
2648            if (DEBUG_PACKAGE_INFO)
2649                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2650            if (p != null) {
2651                return generatePackageInfo(p, flags, userId);
2652            }
2653            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2654                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2655            }
2656        }
2657        return null;
2658    }
2659
2660    @Override
2661    public String[] currentToCanonicalPackageNames(String[] names) {
2662        String[] out = new String[names.length];
2663        // reader
2664        synchronized (mPackages) {
2665            for (int i=names.length-1; i>=0; i--) {
2666                PackageSetting ps = mSettings.mPackages.get(names[i]);
2667                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2668            }
2669        }
2670        return out;
2671    }
2672
2673    @Override
2674    public String[] canonicalToCurrentPackageNames(String[] names) {
2675        String[] out = new String[names.length];
2676        // reader
2677        synchronized (mPackages) {
2678            for (int i=names.length-1; i>=0; i--) {
2679                String cur = mSettings.mRenamedPackages.get(names[i]);
2680                out[i] = cur != null ? cur : names[i];
2681            }
2682        }
2683        return out;
2684    }
2685
2686    @Override
2687    public int getPackageUid(String packageName, int userId) {
2688        if (!sUserManager.exists(userId)) return -1;
2689        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2690
2691        // reader
2692        synchronized (mPackages) {
2693            PackageParser.Package p = mPackages.get(packageName);
2694            if(p != null) {
2695                return UserHandle.getUid(userId, p.applicationInfo.uid);
2696            }
2697            PackageSetting ps = mSettings.mPackages.get(packageName);
2698            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2699                return -1;
2700            }
2701            p = ps.pkg;
2702            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2703        }
2704    }
2705
2706    @Override
2707    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2708        if (!sUserManager.exists(userId)) {
2709            return null;
2710        }
2711
2712        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2713                "getPackageGids");
2714
2715        // reader
2716        synchronized (mPackages) {
2717            PackageParser.Package p = mPackages.get(packageName);
2718            if (DEBUG_PACKAGE_INFO) {
2719                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2720            }
2721            if (p != null) {
2722                PackageSetting ps = (PackageSetting) p.mExtras;
2723                return ps.getPermissionsState().computeGids(userId);
2724            }
2725        }
2726
2727        return null;
2728    }
2729
2730    static PermissionInfo generatePermissionInfo(
2731            BasePermission bp, int flags) {
2732        if (bp.perm != null) {
2733            return PackageParser.generatePermissionInfo(bp.perm, flags);
2734        }
2735        PermissionInfo pi = new PermissionInfo();
2736        pi.name = bp.name;
2737        pi.packageName = bp.sourcePackage;
2738        pi.nonLocalizedLabel = bp.name;
2739        pi.protectionLevel = bp.protectionLevel;
2740        return pi;
2741    }
2742
2743    @Override
2744    public PermissionInfo getPermissionInfo(String name, int flags) {
2745        // reader
2746        synchronized (mPackages) {
2747            final BasePermission p = mSettings.mPermissions.get(name);
2748            if (p != null) {
2749                return generatePermissionInfo(p, flags);
2750            }
2751            return null;
2752        }
2753    }
2754
2755    @Override
2756    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2757        // reader
2758        synchronized (mPackages) {
2759            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2760            for (BasePermission p : mSettings.mPermissions.values()) {
2761                if (group == null) {
2762                    if (p.perm == null || p.perm.info.group == null) {
2763                        out.add(generatePermissionInfo(p, flags));
2764                    }
2765                } else {
2766                    if (p.perm != null && group.equals(p.perm.info.group)) {
2767                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2768                    }
2769                }
2770            }
2771
2772            if (out.size() > 0) {
2773                return out;
2774            }
2775            return mPermissionGroups.containsKey(group) ? out : null;
2776        }
2777    }
2778
2779    @Override
2780    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2781        // reader
2782        synchronized (mPackages) {
2783            return PackageParser.generatePermissionGroupInfo(
2784                    mPermissionGroups.get(name), flags);
2785        }
2786    }
2787
2788    @Override
2789    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2790        // reader
2791        synchronized (mPackages) {
2792            final int N = mPermissionGroups.size();
2793            ArrayList<PermissionGroupInfo> out
2794                    = new ArrayList<PermissionGroupInfo>(N);
2795            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2796                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2797            }
2798            return out;
2799        }
2800    }
2801
2802    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2803            int userId) {
2804        if (!sUserManager.exists(userId)) return null;
2805        PackageSetting ps = mSettings.mPackages.get(packageName);
2806        if (ps != null) {
2807            if (ps.pkg == null) {
2808                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2809                        flags, userId);
2810                if (pInfo != null) {
2811                    return pInfo.applicationInfo;
2812                }
2813                return null;
2814            }
2815            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2816                    ps.readUserState(userId), userId);
2817        }
2818        return null;
2819    }
2820
2821    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2822            int userId) {
2823        if (!sUserManager.exists(userId)) return null;
2824        PackageSetting ps = mSettings.mPackages.get(packageName);
2825        if (ps != null) {
2826            PackageParser.Package pkg = ps.pkg;
2827            if (pkg == null) {
2828                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2829                    return null;
2830                }
2831                // Only data remains, so we aren't worried about code paths
2832                pkg = new PackageParser.Package(packageName);
2833                pkg.applicationInfo.packageName = packageName;
2834                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2835                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2836                pkg.applicationInfo.dataDir = Environment
2837                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2838                        .getAbsolutePath();
2839                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2840                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2841            }
2842            return generatePackageInfo(pkg, flags, userId);
2843        }
2844        return null;
2845    }
2846
2847    @Override
2848    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2849        if (!sUserManager.exists(userId)) return null;
2850        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2851        // writer
2852        synchronized (mPackages) {
2853            PackageParser.Package p = mPackages.get(packageName);
2854            if (DEBUG_PACKAGE_INFO) Log.v(
2855                    TAG, "getApplicationInfo " + packageName
2856                    + ": " + p);
2857            if (p != null) {
2858                PackageSetting ps = mSettings.mPackages.get(packageName);
2859                if (ps == null) return null;
2860                // Note: isEnabledLP() does not apply here - always return info
2861                return PackageParser.generateApplicationInfo(
2862                        p, flags, ps.readUserState(userId), userId);
2863            }
2864            if ("android".equals(packageName)||"system".equals(packageName)) {
2865                return mAndroidApplication;
2866            }
2867            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2868                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2869            }
2870        }
2871        return null;
2872    }
2873
2874    @Override
2875    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2876            final IPackageDataObserver observer) {
2877        mContext.enforceCallingOrSelfPermission(
2878                android.Manifest.permission.CLEAR_APP_CACHE, null);
2879        // Queue up an async operation since clearing cache may take a little while.
2880        mHandler.post(new Runnable() {
2881            public void run() {
2882                mHandler.removeCallbacks(this);
2883                int retCode = -1;
2884                synchronized (mInstallLock) {
2885                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2886                    if (retCode < 0) {
2887                        Slog.w(TAG, "Couldn't clear application caches");
2888                    }
2889                }
2890                if (observer != null) {
2891                    try {
2892                        observer.onRemoveCompleted(null, (retCode >= 0));
2893                    } catch (RemoteException e) {
2894                        Slog.w(TAG, "RemoveException when invoking call back");
2895                    }
2896                }
2897            }
2898        });
2899    }
2900
2901    @Override
2902    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2903            final IntentSender pi) {
2904        mContext.enforceCallingOrSelfPermission(
2905                android.Manifest.permission.CLEAR_APP_CACHE, null);
2906        // Queue up an async operation since clearing cache may take a little while.
2907        mHandler.post(new Runnable() {
2908            public void run() {
2909                mHandler.removeCallbacks(this);
2910                int retCode = -1;
2911                synchronized (mInstallLock) {
2912                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2913                    if (retCode < 0) {
2914                        Slog.w(TAG, "Couldn't clear application caches");
2915                    }
2916                }
2917                if(pi != null) {
2918                    try {
2919                        // Callback via pending intent
2920                        int code = (retCode >= 0) ? 1 : 0;
2921                        pi.sendIntent(null, code, null,
2922                                null, null);
2923                    } catch (SendIntentException e1) {
2924                        Slog.i(TAG, "Failed to send pending intent");
2925                    }
2926                }
2927            }
2928        });
2929    }
2930
2931    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2932        synchronized (mInstallLock) {
2933            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2934                throw new IOException("Failed to free enough space");
2935            }
2936        }
2937    }
2938
2939    @Override
2940    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2941        if (!sUserManager.exists(userId)) return null;
2942        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2943        synchronized (mPackages) {
2944            PackageParser.Activity a = mActivities.mActivities.get(component);
2945
2946            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2947            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2948                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2949                if (ps == null) return null;
2950                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2951                        userId);
2952            }
2953            if (mResolveComponentName.equals(component)) {
2954                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2955                        new PackageUserState(), userId);
2956            }
2957        }
2958        return null;
2959    }
2960
2961    @Override
2962    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2963            String resolvedType) {
2964        synchronized (mPackages) {
2965            PackageParser.Activity a = mActivities.mActivities.get(component);
2966            if (a == null) {
2967                return false;
2968            }
2969            for (int i=0; i<a.intents.size(); i++) {
2970                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2971                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2972                    return true;
2973                }
2974            }
2975            return false;
2976        }
2977    }
2978
2979    @Override
2980    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2981        if (!sUserManager.exists(userId)) return null;
2982        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2983        synchronized (mPackages) {
2984            PackageParser.Activity a = mReceivers.mActivities.get(component);
2985            if (DEBUG_PACKAGE_INFO) Log.v(
2986                TAG, "getReceiverInfo " + component + ": " + a);
2987            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2988                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2989                if (ps == null) return null;
2990                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2991                        userId);
2992            }
2993        }
2994        return null;
2995    }
2996
2997    @Override
2998    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2999        if (!sUserManager.exists(userId)) return null;
3000        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3001        synchronized (mPackages) {
3002            PackageParser.Service s = mServices.mServices.get(component);
3003            if (DEBUG_PACKAGE_INFO) Log.v(
3004                TAG, "getServiceInfo " + component + ": " + s);
3005            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3006                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3007                if (ps == null) return null;
3008                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3009                        userId);
3010            }
3011        }
3012        return null;
3013    }
3014
3015    @Override
3016    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3017        if (!sUserManager.exists(userId)) return null;
3018        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3019        synchronized (mPackages) {
3020            PackageParser.Provider p = mProviders.mProviders.get(component);
3021            if (DEBUG_PACKAGE_INFO) Log.v(
3022                TAG, "getProviderInfo " + component + ": " + p);
3023            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3024                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3025                if (ps == null) return null;
3026                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3027                        userId);
3028            }
3029        }
3030        return null;
3031    }
3032
3033    @Override
3034    public String[] getSystemSharedLibraryNames() {
3035        Set<String> libSet;
3036        synchronized (mPackages) {
3037            libSet = mSharedLibraries.keySet();
3038            int size = libSet.size();
3039            if (size > 0) {
3040                String[] libs = new String[size];
3041                libSet.toArray(libs);
3042                return libs;
3043            }
3044        }
3045        return null;
3046    }
3047
3048    /**
3049     * @hide
3050     */
3051    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3052        synchronized (mPackages) {
3053            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3054            if (lib != null && lib.apk != null) {
3055                return mPackages.get(lib.apk);
3056            }
3057        }
3058        return null;
3059    }
3060
3061    @Override
3062    public FeatureInfo[] getSystemAvailableFeatures() {
3063        Collection<FeatureInfo> featSet;
3064        synchronized (mPackages) {
3065            featSet = mAvailableFeatures.values();
3066            int size = featSet.size();
3067            if (size > 0) {
3068                FeatureInfo[] features = new FeatureInfo[size+1];
3069                featSet.toArray(features);
3070                FeatureInfo fi = new FeatureInfo();
3071                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3072                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3073                features[size] = fi;
3074                return features;
3075            }
3076        }
3077        return null;
3078    }
3079
3080    @Override
3081    public boolean hasSystemFeature(String name) {
3082        synchronized (mPackages) {
3083            return mAvailableFeatures.containsKey(name);
3084        }
3085    }
3086
3087    private void checkValidCaller(int uid, int userId) {
3088        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3089            return;
3090
3091        throw new SecurityException("Caller uid=" + uid
3092                + " is not privileged to communicate with user=" + userId);
3093    }
3094
3095    @Override
3096    public int checkPermission(String permName, String pkgName, int userId) {
3097        if (!sUserManager.exists(userId)) {
3098            return PackageManager.PERMISSION_DENIED;
3099        }
3100
3101        synchronized (mPackages) {
3102            final PackageParser.Package p = mPackages.get(pkgName);
3103            if (p != null && p.mExtras != null) {
3104                final PackageSetting ps = (PackageSetting) p.mExtras;
3105                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3106                    return PackageManager.PERMISSION_GRANTED;
3107                }
3108            }
3109        }
3110
3111        return PackageManager.PERMISSION_DENIED;
3112    }
3113
3114    @Override
3115    public int checkUidPermission(String permName, int uid) {
3116        final int userId = UserHandle.getUserId(uid);
3117
3118        if (!sUserManager.exists(userId)) {
3119            return PackageManager.PERMISSION_DENIED;
3120        }
3121
3122        synchronized (mPackages) {
3123            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3124            if (obj != null) {
3125                final SettingBase ps = (SettingBase) obj;
3126                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3127                    return PackageManager.PERMISSION_GRANTED;
3128                }
3129            } else {
3130                ArraySet<String> perms = mSystemPermissions.get(uid);
3131                if (perms != null && perms.contains(permName)) {
3132                    return PackageManager.PERMISSION_GRANTED;
3133                }
3134            }
3135        }
3136
3137        return PackageManager.PERMISSION_DENIED;
3138    }
3139
3140    @Override
3141    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3142        if (UserHandle.getCallingUserId() != userId) {
3143            mContext.enforceCallingPermission(
3144                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3145                    "isPermissionRevokedByPolicy for user " + userId);
3146        }
3147
3148        if (checkPermission(permission, packageName, userId)
3149                == PackageManager.PERMISSION_GRANTED) {
3150            return false;
3151        }
3152
3153        final long identity = Binder.clearCallingIdentity();
3154        try {
3155            final int flags = getPermissionFlags(permission, packageName, userId);
3156            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3157        } finally {
3158            Binder.restoreCallingIdentity(identity);
3159        }
3160    }
3161
3162    /**
3163     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3164     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3165     * @param checkShell TODO(yamasani):
3166     * @param message the message to log on security exception
3167     */
3168    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3169            boolean checkShell, String message) {
3170        if (userId < 0) {
3171            throw new IllegalArgumentException("Invalid userId " + userId);
3172        }
3173        if (checkShell) {
3174            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3175        }
3176        if (userId == UserHandle.getUserId(callingUid)) return;
3177        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3178            if (requireFullPermission) {
3179                mContext.enforceCallingOrSelfPermission(
3180                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3181            } else {
3182                try {
3183                    mContext.enforceCallingOrSelfPermission(
3184                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3185                } catch (SecurityException se) {
3186                    mContext.enforceCallingOrSelfPermission(
3187                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3188                }
3189            }
3190        }
3191    }
3192
3193    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3194        if (callingUid == Process.SHELL_UID) {
3195            if (userHandle >= 0
3196                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3197                throw new SecurityException("Shell does not have permission to access user "
3198                        + userHandle);
3199            } else if (userHandle < 0) {
3200                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3201                        + Debug.getCallers(3));
3202            }
3203        }
3204    }
3205
3206    private BasePermission findPermissionTreeLP(String permName) {
3207        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3208            if (permName.startsWith(bp.name) &&
3209                    permName.length() > bp.name.length() &&
3210                    permName.charAt(bp.name.length()) == '.') {
3211                return bp;
3212            }
3213        }
3214        return null;
3215    }
3216
3217    private BasePermission checkPermissionTreeLP(String permName) {
3218        if (permName != null) {
3219            BasePermission bp = findPermissionTreeLP(permName);
3220            if (bp != null) {
3221                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3222                    return bp;
3223                }
3224                throw new SecurityException("Calling uid "
3225                        + Binder.getCallingUid()
3226                        + " is not allowed to add to permission tree "
3227                        + bp.name + " owned by uid " + bp.uid);
3228            }
3229        }
3230        throw new SecurityException("No permission tree found for " + permName);
3231    }
3232
3233    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3234        if (s1 == null) {
3235            return s2 == null;
3236        }
3237        if (s2 == null) {
3238            return false;
3239        }
3240        if (s1.getClass() != s2.getClass()) {
3241            return false;
3242        }
3243        return s1.equals(s2);
3244    }
3245
3246    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3247        if (pi1.icon != pi2.icon) return false;
3248        if (pi1.logo != pi2.logo) return false;
3249        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3250        if (!compareStrings(pi1.name, pi2.name)) return false;
3251        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3252        // We'll take care of setting this one.
3253        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3254        // These are not currently stored in settings.
3255        //if (!compareStrings(pi1.group, pi2.group)) return false;
3256        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3257        //if (pi1.labelRes != pi2.labelRes) return false;
3258        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3259        return true;
3260    }
3261
3262    int permissionInfoFootprint(PermissionInfo info) {
3263        int size = info.name.length();
3264        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3265        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3266        return size;
3267    }
3268
3269    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3270        int size = 0;
3271        for (BasePermission perm : mSettings.mPermissions.values()) {
3272            if (perm.uid == tree.uid) {
3273                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3274            }
3275        }
3276        return size;
3277    }
3278
3279    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3280        // We calculate the max size of permissions defined by this uid and throw
3281        // if that plus the size of 'info' would exceed our stated maximum.
3282        if (tree.uid != Process.SYSTEM_UID) {
3283            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3284            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3285                throw new SecurityException("Permission tree size cap exceeded");
3286            }
3287        }
3288    }
3289
3290    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3291        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3292            throw new SecurityException("Label must be specified in permission");
3293        }
3294        BasePermission tree = checkPermissionTreeLP(info.name);
3295        BasePermission bp = mSettings.mPermissions.get(info.name);
3296        boolean added = bp == null;
3297        boolean changed = true;
3298        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3299        if (added) {
3300            enforcePermissionCapLocked(info, tree);
3301            bp = new BasePermission(info.name, tree.sourcePackage,
3302                    BasePermission.TYPE_DYNAMIC);
3303        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3304            throw new SecurityException(
3305                    "Not allowed to modify non-dynamic permission "
3306                    + info.name);
3307        } else {
3308            if (bp.protectionLevel == fixedLevel
3309                    && bp.perm.owner.equals(tree.perm.owner)
3310                    && bp.uid == tree.uid
3311                    && comparePermissionInfos(bp.perm.info, info)) {
3312                changed = false;
3313            }
3314        }
3315        bp.protectionLevel = fixedLevel;
3316        info = new PermissionInfo(info);
3317        info.protectionLevel = fixedLevel;
3318        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3319        bp.perm.info.packageName = tree.perm.info.packageName;
3320        bp.uid = tree.uid;
3321        if (added) {
3322            mSettings.mPermissions.put(info.name, bp);
3323        }
3324        if (changed) {
3325            if (!async) {
3326                mSettings.writeLPr();
3327            } else {
3328                scheduleWriteSettingsLocked();
3329            }
3330        }
3331        return added;
3332    }
3333
3334    @Override
3335    public boolean addPermission(PermissionInfo info) {
3336        synchronized (mPackages) {
3337            return addPermissionLocked(info, false);
3338        }
3339    }
3340
3341    @Override
3342    public boolean addPermissionAsync(PermissionInfo info) {
3343        synchronized (mPackages) {
3344            return addPermissionLocked(info, true);
3345        }
3346    }
3347
3348    @Override
3349    public void removePermission(String name) {
3350        synchronized (mPackages) {
3351            checkPermissionTreeLP(name);
3352            BasePermission bp = mSettings.mPermissions.get(name);
3353            if (bp != null) {
3354                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3355                    throw new SecurityException(
3356                            "Not allowed to modify non-dynamic permission "
3357                            + name);
3358                }
3359                mSettings.mPermissions.remove(name);
3360                mSettings.writeLPr();
3361            }
3362        }
3363    }
3364
3365    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3366            BasePermission bp) {
3367        int index = pkg.requestedPermissions.indexOf(bp.name);
3368        if (index == -1) {
3369            throw new SecurityException("Package " + pkg.packageName
3370                    + " has not requested permission " + bp.name);
3371        }
3372        if (!bp.isRuntime()) {
3373            throw new SecurityException("Permission " + bp.name
3374                    + " is not a changeable permission type");
3375        }
3376    }
3377
3378    @Override
3379    public void grantRuntimePermission(String packageName, String name, final int userId) {
3380        if (!sUserManager.exists(userId)) {
3381            Log.e(TAG, "No such user:" + userId);
3382            return;
3383        }
3384
3385        mContext.enforceCallingOrSelfPermission(
3386                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3387                "grantRuntimePermission");
3388
3389        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3390                "grantRuntimePermission");
3391
3392        final int uid;
3393        final SettingBase sb;
3394
3395        synchronized (mPackages) {
3396            final PackageParser.Package pkg = mPackages.get(packageName);
3397            if (pkg == null) {
3398                throw new IllegalArgumentException("Unknown package: " + packageName);
3399            }
3400
3401            final BasePermission bp = mSettings.mPermissions.get(name);
3402            if (bp == null) {
3403                throw new IllegalArgumentException("Unknown permission: " + name);
3404            }
3405
3406            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3407
3408            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3409            sb = (SettingBase) pkg.mExtras;
3410            if (sb == null) {
3411                throw new IllegalArgumentException("Unknown package: " + packageName);
3412            }
3413
3414            final PermissionsState permissionsState = sb.getPermissionsState();
3415
3416            final int flags = permissionsState.getPermissionFlags(name, userId);
3417            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3418                throw new SecurityException("Cannot grant system fixed permission: "
3419                        + name + " for package: " + packageName);
3420            }
3421
3422            final int result = permissionsState.grantRuntimePermission(bp, userId);
3423            switch (result) {
3424                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3425                    return;
3426                }
3427
3428                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3429                    mHandler.post(new Runnable() {
3430                        @Override
3431                        public void run() {
3432                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3433                        }
3434                    });
3435                } break;
3436            }
3437
3438            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3439
3440            // Not critical if that is lost - app has to request again.
3441            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3442        }
3443
3444        // Only need to do this if user is initialized. Otherwise it's a new user
3445        // and there are no processes running as the user yet and there's no need
3446        // to make an expensive call to remount processes for the changed permissions.
3447        if (READ_EXTERNAL_STORAGE.equals(name)
3448                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3449            final long token = Binder.clearCallingIdentity();
3450            try {
3451                if (sUserManager.isInitialized(userId)) {
3452                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3453                            MountServiceInternal.class);
3454                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3455                }
3456            } finally {
3457                Binder.restoreCallingIdentity(token);
3458            }
3459        }
3460    }
3461
3462    @Override
3463    public void revokeRuntimePermission(String packageName, String name, int userId) {
3464        if (!sUserManager.exists(userId)) {
3465            Log.e(TAG, "No such user:" + userId);
3466            return;
3467        }
3468
3469        mContext.enforceCallingOrSelfPermission(
3470                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3471                "revokeRuntimePermission");
3472
3473        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3474                "revokeRuntimePermission");
3475
3476        final SettingBase sb;
3477
3478        synchronized (mPackages) {
3479            final PackageParser.Package pkg = mPackages.get(packageName);
3480            if (pkg == null) {
3481                throw new IllegalArgumentException("Unknown package: " + packageName);
3482            }
3483
3484            final BasePermission bp = mSettings.mPermissions.get(name);
3485            if (bp == null) {
3486                throw new IllegalArgumentException("Unknown permission: " + name);
3487            }
3488
3489            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3490
3491            sb = (SettingBase) pkg.mExtras;
3492            if (sb == null) {
3493                throw new IllegalArgumentException("Unknown package: " + packageName);
3494            }
3495
3496            final PermissionsState permissionsState = sb.getPermissionsState();
3497
3498            final int flags = permissionsState.getPermissionFlags(name, userId);
3499            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3500                throw new SecurityException("Cannot revoke system fixed permission: "
3501                        + name + " for package: " + packageName);
3502            }
3503
3504            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3505                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3506                return;
3507            }
3508
3509            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3510
3511            // Critical, after this call app should never have the permission.
3512            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3513        }
3514
3515        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3516    }
3517
3518    @Override
3519    public void resetRuntimePermissions() {
3520        mContext.enforceCallingOrSelfPermission(
3521                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3522                "revokeRuntimePermission");
3523
3524        int callingUid = Binder.getCallingUid();
3525        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3526            mContext.enforceCallingOrSelfPermission(
3527                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3528                    "resetRuntimePermissions");
3529        }
3530
3531        final int[] userIds;
3532
3533        synchronized (mPackages) {
3534            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3535            final int userCount = UserManagerService.getInstance().getUserIds().length;
3536            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3537        }
3538
3539        for (int userId : userIds) {
3540            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3541        }
3542    }
3543
3544    @Override
3545    public int getPermissionFlags(String name, String packageName, int userId) {
3546        if (!sUserManager.exists(userId)) {
3547            return 0;
3548        }
3549
3550        mContext.enforceCallingOrSelfPermission(
3551                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3552                "getPermissionFlags");
3553
3554        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3555                "getPermissionFlags");
3556
3557        synchronized (mPackages) {
3558            final PackageParser.Package pkg = mPackages.get(packageName);
3559            if (pkg == null) {
3560                throw new IllegalArgumentException("Unknown package: " + packageName);
3561            }
3562
3563            final BasePermission bp = mSettings.mPermissions.get(name);
3564            if (bp == null) {
3565                throw new IllegalArgumentException("Unknown permission: " + name);
3566            }
3567
3568            SettingBase sb = (SettingBase) pkg.mExtras;
3569            if (sb == null) {
3570                throw new IllegalArgumentException("Unknown package: " + packageName);
3571            }
3572
3573            PermissionsState permissionsState = sb.getPermissionsState();
3574            return permissionsState.getPermissionFlags(name, userId);
3575        }
3576    }
3577
3578    @Override
3579    public void updatePermissionFlags(String name, String packageName, int flagMask,
3580            int flagValues, int userId) {
3581        if (!sUserManager.exists(userId)) {
3582            return;
3583        }
3584
3585        mContext.enforceCallingOrSelfPermission(
3586                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3587                "updatePermissionFlags");
3588
3589        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3590                "updatePermissionFlags");
3591
3592        // Only the system can change system fixed flags.
3593        if (getCallingUid() != Process.SYSTEM_UID) {
3594            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3595            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3596        }
3597
3598        synchronized (mPackages) {
3599            final PackageParser.Package pkg = mPackages.get(packageName);
3600            if (pkg == null) {
3601                throw new IllegalArgumentException("Unknown package: " + packageName);
3602            }
3603
3604            final BasePermission bp = mSettings.mPermissions.get(name);
3605            if (bp == null) {
3606                throw new IllegalArgumentException("Unknown permission: " + name);
3607            }
3608
3609            SettingBase sb = (SettingBase) pkg.mExtras;
3610            if (sb == null) {
3611                throw new IllegalArgumentException("Unknown package: " + packageName);
3612            }
3613
3614            PermissionsState permissionsState = sb.getPermissionsState();
3615
3616            // Only the package manager can change flags for system component permissions.
3617            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3618            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3619                return;
3620            }
3621
3622            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3623
3624            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3625                // Install and runtime permissions are stored in different places,
3626                // so figure out what permission changed and persist the change.
3627                if (permissionsState.getInstallPermissionState(name) != null) {
3628                    scheduleWriteSettingsLocked();
3629                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3630                        || hadState) {
3631                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3632                }
3633            }
3634        }
3635    }
3636
3637    /**
3638     * Update the permission flags for all packages and runtime permissions of a user in order
3639     * to allow device or profile owner to remove POLICY_FIXED.
3640     */
3641    @Override
3642    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3643        if (!sUserManager.exists(userId)) {
3644            return;
3645        }
3646
3647        mContext.enforceCallingOrSelfPermission(
3648                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3649                "updatePermissionFlagsForAllApps");
3650
3651        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3652                "updatePermissionFlagsForAllApps");
3653
3654        // Only the system can change system fixed flags.
3655        if (getCallingUid() != Process.SYSTEM_UID) {
3656            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3657            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3658        }
3659
3660        synchronized (mPackages) {
3661            boolean changed = false;
3662            final int packageCount = mPackages.size();
3663            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3664                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3665                SettingBase sb = (SettingBase) pkg.mExtras;
3666                if (sb == null) {
3667                    continue;
3668                }
3669                PermissionsState permissionsState = sb.getPermissionsState();
3670                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3671                        userId, flagMask, flagValues);
3672            }
3673            if (changed) {
3674                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3675            }
3676        }
3677    }
3678
3679    @Override
3680    public boolean shouldShowRequestPermissionRationale(String permissionName,
3681            String packageName, int userId) {
3682        if (UserHandle.getCallingUserId() != userId) {
3683            mContext.enforceCallingPermission(
3684                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3685                    "canShowRequestPermissionRationale for user " + userId);
3686        }
3687
3688        final int uid = getPackageUid(packageName, userId);
3689        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3690            return false;
3691        }
3692
3693        if (checkPermission(permissionName, packageName, userId)
3694                == PackageManager.PERMISSION_GRANTED) {
3695            return false;
3696        }
3697
3698        final int flags;
3699
3700        final long identity = Binder.clearCallingIdentity();
3701        try {
3702            flags = getPermissionFlags(permissionName,
3703                    packageName, userId);
3704        } finally {
3705            Binder.restoreCallingIdentity(identity);
3706        }
3707
3708        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3709                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3710                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3711
3712        if ((flags & fixedFlags) != 0) {
3713            return false;
3714        }
3715
3716        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3717    }
3718
3719    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3720        BasePermission bp = mSettings.mPermissions.get(permission);
3721        if (bp == null) {
3722            throw new SecurityException("Missing " + permission + " permission");
3723        }
3724
3725        SettingBase sb = (SettingBase) pkg.mExtras;
3726        PermissionsState permissionsState = sb.getPermissionsState();
3727
3728        if (permissionsState.grantInstallPermission(bp) !=
3729                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3730            scheduleWriteSettingsLocked();
3731        }
3732    }
3733
3734    @Override
3735    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3736        mContext.enforceCallingOrSelfPermission(
3737                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3738                "addOnPermissionsChangeListener");
3739
3740        synchronized (mPackages) {
3741            mOnPermissionChangeListeners.addListenerLocked(listener);
3742        }
3743    }
3744
3745    @Override
3746    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3747        synchronized (mPackages) {
3748            mOnPermissionChangeListeners.removeListenerLocked(listener);
3749        }
3750    }
3751
3752    @Override
3753    public boolean isProtectedBroadcast(String actionName) {
3754        synchronized (mPackages) {
3755            return mProtectedBroadcasts.contains(actionName);
3756        }
3757    }
3758
3759    @Override
3760    public int checkSignatures(String pkg1, String pkg2) {
3761        synchronized (mPackages) {
3762            final PackageParser.Package p1 = mPackages.get(pkg1);
3763            final PackageParser.Package p2 = mPackages.get(pkg2);
3764            if (p1 == null || p1.mExtras == null
3765                    || p2 == null || p2.mExtras == null) {
3766                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3767            }
3768            return compareSignatures(p1.mSignatures, p2.mSignatures);
3769        }
3770    }
3771
3772    @Override
3773    public int checkUidSignatures(int uid1, int uid2) {
3774        // Map to base uids.
3775        uid1 = UserHandle.getAppId(uid1);
3776        uid2 = UserHandle.getAppId(uid2);
3777        // reader
3778        synchronized (mPackages) {
3779            Signature[] s1;
3780            Signature[] s2;
3781            Object obj = mSettings.getUserIdLPr(uid1);
3782            if (obj != null) {
3783                if (obj instanceof SharedUserSetting) {
3784                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3785                } else if (obj instanceof PackageSetting) {
3786                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3787                } else {
3788                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3789                }
3790            } else {
3791                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3792            }
3793            obj = mSettings.getUserIdLPr(uid2);
3794            if (obj != null) {
3795                if (obj instanceof SharedUserSetting) {
3796                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3797                } else if (obj instanceof PackageSetting) {
3798                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3799                } else {
3800                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3801                }
3802            } else {
3803                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3804            }
3805            return compareSignatures(s1, s2);
3806        }
3807    }
3808
3809    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3810        final long identity = Binder.clearCallingIdentity();
3811        try {
3812            if (sb instanceof SharedUserSetting) {
3813                SharedUserSetting sus = (SharedUserSetting) sb;
3814                final int packageCount = sus.packages.size();
3815                for (int i = 0; i < packageCount; i++) {
3816                    PackageSetting susPs = sus.packages.valueAt(i);
3817                    if (userId == UserHandle.USER_ALL) {
3818                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3819                    } else {
3820                        final int uid = UserHandle.getUid(userId, susPs.appId);
3821                        killUid(uid, reason);
3822                    }
3823                }
3824            } else if (sb instanceof PackageSetting) {
3825                PackageSetting ps = (PackageSetting) sb;
3826                if (userId == UserHandle.USER_ALL) {
3827                    killApplication(ps.pkg.packageName, ps.appId, reason);
3828                } else {
3829                    final int uid = UserHandle.getUid(userId, ps.appId);
3830                    killUid(uid, reason);
3831                }
3832            }
3833        } finally {
3834            Binder.restoreCallingIdentity(identity);
3835        }
3836    }
3837
3838    private static void killUid(int uid, String reason) {
3839        IActivityManager am = ActivityManagerNative.getDefault();
3840        if (am != null) {
3841            try {
3842                am.killUid(uid, reason);
3843            } catch (RemoteException e) {
3844                /* ignore - same process */
3845            }
3846        }
3847    }
3848
3849    /**
3850     * Compares two sets of signatures. Returns:
3851     * <br />
3852     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3853     * <br />
3854     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3855     * <br />
3856     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3857     * <br />
3858     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3859     * <br />
3860     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3861     */
3862    static int compareSignatures(Signature[] s1, Signature[] s2) {
3863        if (s1 == null) {
3864            return s2 == null
3865                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3866                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3867        }
3868
3869        if (s2 == null) {
3870            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3871        }
3872
3873        if (s1.length != s2.length) {
3874            return PackageManager.SIGNATURE_NO_MATCH;
3875        }
3876
3877        // Since both signature sets are of size 1, we can compare without HashSets.
3878        if (s1.length == 1) {
3879            return s1[0].equals(s2[0]) ?
3880                    PackageManager.SIGNATURE_MATCH :
3881                    PackageManager.SIGNATURE_NO_MATCH;
3882        }
3883
3884        ArraySet<Signature> set1 = new ArraySet<Signature>();
3885        for (Signature sig : s1) {
3886            set1.add(sig);
3887        }
3888        ArraySet<Signature> set2 = new ArraySet<Signature>();
3889        for (Signature sig : s2) {
3890            set2.add(sig);
3891        }
3892        // Make sure s2 contains all signatures in s1.
3893        if (set1.equals(set2)) {
3894            return PackageManager.SIGNATURE_MATCH;
3895        }
3896        return PackageManager.SIGNATURE_NO_MATCH;
3897    }
3898
3899    /**
3900     * If the database version for this type of package (internal storage or
3901     * external storage) is less than the version where package signatures
3902     * were updated, return true.
3903     */
3904    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3905        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3906                DatabaseVersion.SIGNATURE_END_ENTITY))
3907                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3908                        DatabaseVersion.SIGNATURE_END_ENTITY));
3909    }
3910
3911    /**
3912     * Used for backward compatibility to make sure any packages with
3913     * certificate chains get upgraded to the new style. {@code existingSigs}
3914     * will be in the old format (since they were stored on disk from before the
3915     * system upgrade) and {@code scannedSigs} will be in the newer format.
3916     */
3917    private int compareSignaturesCompat(PackageSignatures existingSigs,
3918            PackageParser.Package scannedPkg) {
3919        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3920            return PackageManager.SIGNATURE_NO_MATCH;
3921        }
3922
3923        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3924        for (Signature sig : existingSigs.mSignatures) {
3925            existingSet.add(sig);
3926        }
3927        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3928        for (Signature sig : scannedPkg.mSignatures) {
3929            try {
3930                Signature[] chainSignatures = sig.getChainSignatures();
3931                for (Signature chainSig : chainSignatures) {
3932                    scannedCompatSet.add(chainSig);
3933                }
3934            } catch (CertificateEncodingException e) {
3935                scannedCompatSet.add(sig);
3936            }
3937        }
3938        /*
3939         * Make sure the expanded scanned set contains all signatures in the
3940         * existing one.
3941         */
3942        if (scannedCompatSet.equals(existingSet)) {
3943            // Migrate the old signatures to the new scheme.
3944            existingSigs.assignSignatures(scannedPkg.mSignatures);
3945            // The new KeySets will be re-added later in the scanning process.
3946            synchronized (mPackages) {
3947                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3948            }
3949            return PackageManager.SIGNATURE_MATCH;
3950        }
3951        return PackageManager.SIGNATURE_NO_MATCH;
3952    }
3953
3954    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3955        if (isExternal(scannedPkg)) {
3956            return mSettings.isExternalDatabaseVersionOlderThan(
3957                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3958        } else {
3959            return mSettings.isInternalDatabaseVersionOlderThan(
3960                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3961        }
3962    }
3963
3964    private int compareSignaturesRecover(PackageSignatures existingSigs,
3965            PackageParser.Package scannedPkg) {
3966        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3967            return PackageManager.SIGNATURE_NO_MATCH;
3968        }
3969
3970        String msg = null;
3971        try {
3972            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3973                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3974                        + scannedPkg.packageName);
3975                return PackageManager.SIGNATURE_MATCH;
3976            }
3977        } catch (CertificateException e) {
3978            msg = e.getMessage();
3979        }
3980
3981        logCriticalInfo(Log.INFO,
3982                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3983        return PackageManager.SIGNATURE_NO_MATCH;
3984    }
3985
3986    @Override
3987    public String[] getPackagesForUid(int uid) {
3988        uid = UserHandle.getAppId(uid);
3989        // reader
3990        synchronized (mPackages) {
3991            Object obj = mSettings.getUserIdLPr(uid);
3992            if (obj instanceof SharedUserSetting) {
3993                final SharedUserSetting sus = (SharedUserSetting) obj;
3994                final int N = sus.packages.size();
3995                final String[] res = new String[N];
3996                final Iterator<PackageSetting> it = sus.packages.iterator();
3997                int i = 0;
3998                while (it.hasNext()) {
3999                    res[i++] = it.next().name;
4000                }
4001                return res;
4002            } else if (obj instanceof PackageSetting) {
4003                final PackageSetting ps = (PackageSetting) obj;
4004                return new String[] { ps.name };
4005            }
4006        }
4007        return null;
4008    }
4009
4010    @Override
4011    public String getNameForUid(int uid) {
4012        // reader
4013        synchronized (mPackages) {
4014            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4015            if (obj instanceof SharedUserSetting) {
4016                final SharedUserSetting sus = (SharedUserSetting) obj;
4017                return sus.name + ":" + sus.userId;
4018            } else if (obj instanceof PackageSetting) {
4019                final PackageSetting ps = (PackageSetting) obj;
4020                return ps.name;
4021            }
4022        }
4023        return null;
4024    }
4025
4026    @Override
4027    public int getUidForSharedUser(String sharedUserName) {
4028        if(sharedUserName == null) {
4029            return -1;
4030        }
4031        // reader
4032        synchronized (mPackages) {
4033            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4034            if (suid == null) {
4035                return -1;
4036            }
4037            return suid.userId;
4038        }
4039    }
4040
4041    @Override
4042    public int getFlagsForUid(int uid) {
4043        synchronized (mPackages) {
4044            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4045            if (obj instanceof SharedUserSetting) {
4046                final SharedUserSetting sus = (SharedUserSetting) obj;
4047                return sus.pkgFlags;
4048            } else if (obj instanceof PackageSetting) {
4049                final PackageSetting ps = (PackageSetting) obj;
4050                return ps.pkgFlags;
4051            }
4052        }
4053        return 0;
4054    }
4055
4056    @Override
4057    public int getPrivateFlagsForUid(int uid) {
4058        synchronized (mPackages) {
4059            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4060            if (obj instanceof SharedUserSetting) {
4061                final SharedUserSetting sus = (SharedUserSetting) obj;
4062                return sus.pkgPrivateFlags;
4063            } else if (obj instanceof PackageSetting) {
4064                final PackageSetting ps = (PackageSetting) obj;
4065                return ps.pkgPrivateFlags;
4066            }
4067        }
4068        return 0;
4069    }
4070
4071    @Override
4072    public boolean isUidPrivileged(int uid) {
4073        uid = UserHandle.getAppId(uid);
4074        // reader
4075        synchronized (mPackages) {
4076            Object obj = mSettings.getUserIdLPr(uid);
4077            if (obj instanceof SharedUserSetting) {
4078                final SharedUserSetting sus = (SharedUserSetting) obj;
4079                final Iterator<PackageSetting> it = sus.packages.iterator();
4080                while (it.hasNext()) {
4081                    if (it.next().isPrivileged()) {
4082                        return true;
4083                    }
4084                }
4085            } else if (obj instanceof PackageSetting) {
4086                final PackageSetting ps = (PackageSetting) obj;
4087                return ps.isPrivileged();
4088            }
4089        }
4090        return false;
4091    }
4092
4093    @Override
4094    public String[] getAppOpPermissionPackages(String permissionName) {
4095        synchronized (mPackages) {
4096            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4097            if (pkgs == null) {
4098                return null;
4099            }
4100            return pkgs.toArray(new String[pkgs.size()]);
4101        }
4102    }
4103
4104    @Override
4105    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4106            int flags, int userId) {
4107        if (!sUserManager.exists(userId)) return null;
4108        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4109        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4110        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4111    }
4112
4113    @Override
4114    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4115            IntentFilter filter, int match, ComponentName activity) {
4116        final int userId = UserHandle.getCallingUserId();
4117        if (DEBUG_PREFERRED) {
4118            Log.v(TAG, "setLastChosenActivity intent=" + intent
4119                + " resolvedType=" + resolvedType
4120                + " flags=" + flags
4121                + " filter=" + filter
4122                + " match=" + match
4123                + " activity=" + activity);
4124            filter.dump(new PrintStreamPrinter(System.out), "    ");
4125        }
4126        intent.setComponent(null);
4127        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4128        // Find any earlier preferred or last chosen entries and nuke them
4129        findPreferredActivity(intent, resolvedType,
4130                flags, query, 0, false, true, false, userId);
4131        // Add the new activity as the last chosen for this filter
4132        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4133                "Setting last chosen");
4134    }
4135
4136    @Override
4137    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4138        final int userId = UserHandle.getCallingUserId();
4139        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4140        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4141        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4142                false, false, false, userId);
4143    }
4144
4145    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4146            int flags, List<ResolveInfo> query, int userId) {
4147        if (query != null) {
4148            final int N = query.size();
4149            if (N == 1) {
4150                return query.get(0);
4151            } else if (N > 1) {
4152                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4153                // If there is more than one activity with the same priority,
4154                // then let the user decide between them.
4155                ResolveInfo r0 = query.get(0);
4156                ResolveInfo r1 = query.get(1);
4157                if (DEBUG_INTENT_MATCHING || debug) {
4158                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4159                            + r1.activityInfo.name + "=" + r1.priority);
4160                }
4161                // If the first activity has a higher priority, or a different
4162                // default, then it is always desireable to pick it.
4163                if (r0.priority != r1.priority
4164                        || r0.preferredOrder != r1.preferredOrder
4165                        || r0.isDefault != r1.isDefault) {
4166                    return query.get(0);
4167                }
4168                // If we have saved a preference for a preferred activity for
4169                // this Intent, use that.
4170                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4171                        flags, query, r0.priority, true, false, debug, userId);
4172                if (ri != null) {
4173                    return ri;
4174                }
4175                if (userId != 0) {
4176                    ri = new ResolveInfo(mResolveInfo);
4177                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4178                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4179                            ri.activityInfo.applicationInfo);
4180                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4181                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4182                    return ri;
4183                }
4184                return mResolveInfo;
4185            }
4186        }
4187        return null;
4188    }
4189
4190    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4191            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4192        final int N = query.size();
4193        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4194                .get(userId);
4195        // Get the list of persistent preferred activities that handle the intent
4196        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4197        List<PersistentPreferredActivity> pprefs = ppir != null
4198                ? ppir.queryIntent(intent, resolvedType,
4199                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4200                : null;
4201        if (pprefs != null && pprefs.size() > 0) {
4202            final int M = pprefs.size();
4203            for (int i=0; i<M; i++) {
4204                final PersistentPreferredActivity ppa = pprefs.get(i);
4205                if (DEBUG_PREFERRED || debug) {
4206                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4207                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4208                            + "\n  component=" + ppa.mComponent);
4209                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4210                }
4211                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4212                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4213                if (DEBUG_PREFERRED || debug) {
4214                    Slog.v(TAG, "Found persistent preferred activity:");
4215                    if (ai != null) {
4216                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4217                    } else {
4218                        Slog.v(TAG, "  null");
4219                    }
4220                }
4221                if (ai == null) {
4222                    // This previously registered persistent preferred activity
4223                    // component is no longer known. Ignore it and do NOT remove it.
4224                    continue;
4225                }
4226                for (int j=0; j<N; j++) {
4227                    final ResolveInfo ri = query.get(j);
4228                    if (!ri.activityInfo.applicationInfo.packageName
4229                            .equals(ai.applicationInfo.packageName)) {
4230                        continue;
4231                    }
4232                    if (!ri.activityInfo.name.equals(ai.name)) {
4233                        continue;
4234                    }
4235                    //  Found a persistent preference that can handle the intent.
4236                    if (DEBUG_PREFERRED || debug) {
4237                        Slog.v(TAG, "Returning persistent preferred activity: " +
4238                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4239                    }
4240                    return ri;
4241                }
4242            }
4243        }
4244        return null;
4245    }
4246
4247    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4248            List<ResolveInfo> query, int priority, boolean always,
4249            boolean removeMatches, boolean debug, int userId) {
4250        if (!sUserManager.exists(userId)) return null;
4251        // writer
4252        synchronized (mPackages) {
4253            if (intent.getSelector() != null) {
4254                intent = intent.getSelector();
4255            }
4256            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4257
4258            // Try to find a matching persistent preferred activity.
4259            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4260                    debug, userId);
4261
4262            // If a persistent preferred activity matched, use it.
4263            if (pri != null) {
4264                return pri;
4265            }
4266
4267            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4268            // Get the list of preferred activities that handle the intent
4269            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4270            List<PreferredActivity> prefs = pir != null
4271                    ? pir.queryIntent(intent, resolvedType,
4272                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4273                    : null;
4274            if (prefs != null && prefs.size() > 0) {
4275                boolean changed = false;
4276                try {
4277                    // First figure out how good the original match set is.
4278                    // We will only allow preferred activities that came
4279                    // from the same match quality.
4280                    int match = 0;
4281
4282                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4283
4284                    final int N = query.size();
4285                    for (int j=0; j<N; j++) {
4286                        final ResolveInfo ri = query.get(j);
4287                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4288                                + ": 0x" + Integer.toHexString(match));
4289                        if (ri.match > match) {
4290                            match = ri.match;
4291                        }
4292                    }
4293
4294                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4295                            + Integer.toHexString(match));
4296
4297                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4298                    final int M = prefs.size();
4299                    for (int i=0; i<M; i++) {
4300                        final PreferredActivity pa = prefs.get(i);
4301                        if (DEBUG_PREFERRED || debug) {
4302                            Slog.v(TAG, "Checking PreferredActivity ds="
4303                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4304                                    + "\n  component=" + pa.mPref.mComponent);
4305                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4306                        }
4307                        if (pa.mPref.mMatch != match) {
4308                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4309                                    + Integer.toHexString(pa.mPref.mMatch));
4310                            continue;
4311                        }
4312                        // If it's not an "always" type preferred activity and that's what we're
4313                        // looking for, skip it.
4314                        if (always && !pa.mPref.mAlways) {
4315                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4316                            continue;
4317                        }
4318                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4319                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4320                        if (DEBUG_PREFERRED || debug) {
4321                            Slog.v(TAG, "Found preferred activity:");
4322                            if (ai != null) {
4323                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4324                            } else {
4325                                Slog.v(TAG, "  null");
4326                            }
4327                        }
4328                        if (ai == null) {
4329                            // This previously registered preferred activity
4330                            // component is no longer known.  Most likely an update
4331                            // to the app was installed and in the new version this
4332                            // component no longer exists.  Clean it up by removing
4333                            // it from the preferred activities list, and skip it.
4334                            Slog.w(TAG, "Removing dangling preferred activity: "
4335                                    + pa.mPref.mComponent);
4336                            pir.removeFilter(pa);
4337                            changed = true;
4338                            continue;
4339                        }
4340                        for (int j=0; j<N; j++) {
4341                            final ResolveInfo ri = query.get(j);
4342                            if (!ri.activityInfo.applicationInfo.packageName
4343                                    .equals(ai.applicationInfo.packageName)) {
4344                                continue;
4345                            }
4346                            if (!ri.activityInfo.name.equals(ai.name)) {
4347                                continue;
4348                            }
4349
4350                            if (removeMatches) {
4351                                pir.removeFilter(pa);
4352                                changed = true;
4353                                if (DEBUG_PREFERRED) {
4354                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4355                                }
4356                                break;
4357                            }
4358
4359                            // Okay we found a previously set preferred or last chosen app.
4360                            // If the result set is different from when this
4361                            // was created, we need to clear it and re-ask the
4362                            // user their preference, if we're looking for an "always" type entry.
4363                            if (always && !pa.mPref.sameSet(query)) {
4364                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4365                                        + intent + " type " + resolvedType);
4366                                if (DEBUG_PREFERRED) {
4367                                    Slog.v(TAG, "Removing preferred activity since set changed "
4368                                            + pa.mPref.mComponent);
4369                                }
4370                                pir.removeFilter(pa);
4371                                // Re-add the filter as a "last chosen" entry (!always)
4372                                PreferredActivity lastChosen = new PreferredActivity(
4373                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4374                                pir.addFilter(lastChosen);
4375                                changed = true;
4376                                return null;
4377                            }
4378
4379                            // Yay! Either the set matched or we're looking for the last chosen
4380                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4381                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4382                            return ri;
4383                        }
4384                    }
4385                } finally {
4386                    if (changed) {
4387                        if (DEBUG_PREFERRED) {
4388                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4389                        }
4390                        scheduleWritePackageRestrictionsLocked(userId);
4391                    }
4392                }
4393            }
4394        }
4395        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4396        return null;
4397    }
4398
4399    /*
4400     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4401     */
4402    @Override
4403    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4404            int targetUserId) {
4405        mContext.enforceCallingOrSelfPermission(
4406                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4407        List<CrossProfileIntentFilter> matches =
4408                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4409        if (matches != null) {
4410            int size = matches.size();
4411            for (int i = 0; i < size; i++) {
4412                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4413            }
4414        }
4415        if (hasWebURI(intent)) {
4416            // cross-profile app linking works only towards the parent.
4417            final UserInfo parent = getProfileParent(sourceUserId);
4418            synchronized(mPackages) {
4419                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4420                        intent, resolvedType, 0, sourceUserId, parent.id);
4421                return xpDomainInfo != null
4422                        && xpDomainInfo.bestDomainVerificationStatus !=
4423                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
4424            }
4425        }
4426        return false;
4427    }
4428
4429    private UserInfo getProfileParent(int userId) {
4430        final long identity = Binder.clearCallingIdentity();
4431        try {
4432            return sUserManager.getProfileParent(userId);
4433        } finally {
4434            Binder.restoreCallingIdentity(identity);
4435        }
4436    }
4437
4438    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4439            String resolvedType, int userId) {
4440        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4441        if (resolver != null) {
4442            return resolver.queryIntent(intent, resolvedType, false, userId);
4443        }
4444        return null;
4445    }
4446
4447    @Override
4448    public List<ResolveInfo> queryIntentActivities(Intent intent,
4449            String resolvedType, int flags, int userId) {
4450        if (!sUserManager.exists(userId)) return Collections.emptyList();
4451        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4452        ComponentName comp = intent.getComponent();
4453        if (comp == null) {
4454            if (intent.getSelector() != null) {
4455                intent = intent.getSelector();
4456                comp = intent.getComponent();
4457            }
4458        }
4459
4460        if (comp != null) {
4461            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4462            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4463            if (ai != null) {
4464                final ResolveInfo ri = new ResolveInfo();
4465                ri.activityInfo = ai;
4466                list.add(ri);
4467            }
4468            return list;
4469        }
4470
4471        // reader
4472        synchronized (mPackages) {
4473            final String pkgName = intent.getPackage();
4474            if (pkgName == null) {
4475                List<CrossProfileIntentFilter> matchingFilters =
4476                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4477                // Check for results that need to skip the current profile.
4478                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4479                        resolvedType, flags, userId);
4480                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4481                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4482                    result.add(xpResolveInfo);
4483                    return filterIfNotPrimaryUser(result, userId);
4484                }
4485
4486                // Check for results in the current profile.
4487                List<ResolveInfo> result = mActivities.queryIntent(
4488                        intent, resolvedType, flags, userId);
4489
4490                // Check for cross profile results.
4491                xpResolveInfo = queryCrossProfileIntents(
4492                        matchingFilters, intent, resolvedType, flags, userId);
4493                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4494                    result.add(xpResolveInfo);
4495                    Collections.sort(result, mResolvePrioritySorter);
4496                }
4497                result = filterIfNotPrimaryUser(result, userId);
4498                if (hasWebURI(intent)) {
4499                    CrossProfileDomainInfo xpDomainInfo = null;
4500                    final UserInfo parent = getProfileParent(userId);
4501                    if (parent != null) {
4502                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4503                                flags, userId, parent.id);
4504                    }
4505                    if (xpDomainInfo != null) {
4506                        if (xpResolveInfo != null) {
4507                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4508                            // in the result.
4509                            result.remove(xpResolveInfo);
4510                        }
4511                        if (result.size() == 0) {
4512                            result.add(xpDomainInfo.resolveInfo);
4513                            return result;
4514                        }
4515                    } else if (result.size() <= 1) {
4516                        return result;
4517                    }
4518                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4519                            xpDomainInfo, userId);
4520                    Collections.sort(result, mResolvePrioritySorter);
4521                }
4522                return result;
4523            }
4524            final PackageParser.Package pkg = mPackages.get(pkgName);
4525            if (pkg != null) {
4526                return filterIfNotPrimaryUser(
4527                        mActivities.queryIntentForPackage(
4528                                intent, resolvedType, flags, pkg.activities, userId),
4529                        userId);
4530            }
4531            return new ArrayList<ResolveInfo>();
4532        }
4533    }
4534
4535    private static class CrossProfileDomainInfo {
4536        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4537        ResolveInfo resolveInfo;
4538        /* Best domain verification status of the activities found in the other profile */
4539        int bestDomainVerificationStatus;
4540    }
4541
4542    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4543            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4544        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4545                sourceUserId)) {
4546            return null;
4547        }
4548        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4549                resolvedType, flags, parentUserId);
4550
4551        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4552            return null;
4553        }
4554        CrossProfileDomainInfo result = null;
4555        int size = resultTargetUser.size();
4556        for (int i = 0; i < size; i++) {
4557            ResolveInfo riTargetUser = resultTargetUser.get(i);
4558            // Intent filter verification is only for filters that specify a host. So don't return
4559            // those that handle all web uris.
4560            if (riTargetUser.handleAllWebDataURI) {
4561                continue;
4562            }
4563            String packageName = riTargetUser.activityInfo.packageName;
4564            PackageSetting ps = mSettings.mPackages.get(packageName);
4565            if (ps == null) {
4566                continue;
4567            }
4568            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4569            int status = (int)(verificationState >> 32);
4570            if (result == null) {
4571                result = new CrossProfileDomainInfo();
4572                result.resolveInfo =
4573                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4574                result.bestDomainVerificationStatus = status;
4575            } else {
4576                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4577                        result.bestDomainVerificationStatus);
4578            }
4579        }
4580        return result;
4581    }
4582
4583    /**
4584     * Verification statuses are ordered from the worse to the best, except for
4585     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4586     */
4587    private int bestDomainVerificationStatus(int status1, int status2) {
4588        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4589            return status2;
4590        }
4591        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4592            return status1;
4593        }
4594        return (int) MathUtils.max(status1, status2);
4595    }
4596
4597    private boolean isUserEnabled(int userId) {
4598        long callingId = Binder.clearCallingIdentity();
4599        try {
4600            UserInfo userInfo = sUserManager.getUserInfo(userId);
4601            return userInfo != null && userInfo.isEnabled();
4602        } finally {
4603            Binder.restoreCallingIdentity(callingId);
4604        }
4605    }
4606
4607    /**
4608     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4609     *
4610     * @return filtered list
4611     */
4612    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4613        if (userId == UserHandle.USER_OWNER) {
4614            return resolveInfos;
4615        }
4616        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4617            ResolveInfo info = resolveInfos.get(i);
4618            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4619                resolveInfos.remove(i);
4620            }
4621        }
4622        return resolveInfos;
4623    }
4624
4625    private static boolean hasWebURI(Intent intent) {
4626        if (intent.getData() == null) {
4627            return false;
4628        }
4629        final String scheme = intent.getScheme();
4630        if (TextUtils.isEmpty(scheme)) {
4631            return false;
4632        }
4633        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4634    }
4635
4636    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4637            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4638            int userId) {
4639        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4640
4641        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4642            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4643                    candidates.size());
4644        }
4645
4646        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4647        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4648        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4649        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4650        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4651
4652        synchronized (mPackages) {
4653            final int count = candidates.size();
4654            // First, try to use linked apps. Partition the candidates into four lists:
4655            // one for the final results, one for the "do not use ever", one for "undefined status"
4656            // and finally one for "browser app type".
4657            for (int n=0; n<count; n++) {
4658                ResolveInfo info = candidates.get(n);
4659                String packageName = info.activityInfo.packageName;
4660                PackageSetting ps = mSettings.mPackages.get(packageName);
4661                if (ps != null) {
4662                    // Add to the special match all list (Browser use case)
4663                    if (info.handleAllWebDataURI) {
4664                        matchAllList.add(info);
4665                        continue;
4666                    }
4667                    // Try to get the status from User settings first
4668                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4669                    int status = (int)(packedStatus >> 32);
4670                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4671                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4672                        if (DEBUG_DOMAIN_VERIFICATION) {
4673                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4674                                    + " : linkgen=" + linkGeneration);
4675                        }
4676                        // Use link-enabled generation as preferredOrder, i.e.
4677                        // prefer newly-enabled over earlier-enabled.
4678                        info.preferredOrder = linkGeneration;
4679                        alwaysList.add(info);
4680                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4681                        if (DEBUG_DOMAIN_VERIFICATION) {
4682                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4683                        }
4684                        neverList.add(info);
4685                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4686                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4687                        if (DEBUG_DOMAIN_VERIFICATION) {
4688                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4689                        }
4690                        undefinedList.add(info);
4691                    }
4692                }
4693            }
4694            // First try to add the "always" resolution(s) for the current user, if any
4695            if (alwaysList.size() > 0) {
4696                result.addAll(alwaysList);
4697            // if there is an "always" for the parent user, add it.
4698            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4699                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4700                result.add(xpDomainInfo.resolveInfo);
4701            } else {
4702                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4703                result.addAll(undefinedList);
4704                if (xpDomainInfo != null && (
4705                        xpDomainInfo.bestDomainVerificationStatus
4706                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4707                        || xpDomainInfo.bestDomainVerificationStatus
4708                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4709                    result.add(xpDomainInfo.resolveInfo);
4710                }
4711                // Also add Browsers (all of them or only the default one)
4712                if ((matchFlags & MATCH_ALL) != 0) {
4713                    result.addAll(matchAllList);
4714                } else {
4715                    // Browser/generic handling case.  If there's a default browser, go straight
4716                    // to that (but only if there is no other higher-priority match).
4717                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4718                            UserHandle.myUserId());
4719                    int maxMatchPrio = 0;
4720                    ResolveInfo defaultBrowserMatch = null;
4721                    final int numCandidates = matchAllList.size();
4722                    for (int n = 0; n < numCandidates; n++) {
4723                        ResolveInfo info = matchAllList.get(n);
4724                        // track the highest overall match priority...
4725                        if (info.priority > maxMatchPrio) {
4726                            maxMatchPrio = info.priority;
4727                        }
4728                        // ...and the highest-priority default browser match
4729                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4730                            if (defaultBrowserMatch == null
4731                                    || (defaultBrowserMatch.priority < info.priority)) {
4732                                if (debug) {
4733                                    Slog.v(TAG, "Considering default browser match " + info);
4734                                }
4735                                defaultBrowserMatch = info;
4736                            }
4737                        }
4738                    }
4739                    if (defaultBrowserMatch != null
4740                            && defaultBrowserMatch.priority >= maxMatchPrio
4741                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4742                    {
4743                        if (debug) {
4744                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4745                        }
4746                        result.add(defaultBrowserMatch);
4747                    } else {
4748                        result.addAll(matchAllList);
4749                    }
4750                }
4751
4752                // If there is nothing selected, add all candidates and remove the ones that the user
4753                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4754                if (result.size() == 0) {
4755                    result.addAll(candidates);
4756                    result.removeAll(neverList);
4757                }
4758            }
4759        }
4760        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4761            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4762                    result.size());
4763            for (ResolveInfo info : result) {
4764                Slog.v(TAG, "  + " + info.activityInfo);
4765            }
4766        }
4767        return result;
4768    }
4769
4770    // Returns a packed value as a long:
4771    //
4772    // high 'int'-sized word: link status: undefined/ask/never/always.
4773    // low 'int'-sized word: relative priority among 'always' results.
4774    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4775        long result = ps.getDomainVerificationStatusForUser(userId);
4776        // if none available, get the master status
4777        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4778            if (ps.getIntentFilterVerificationInfo() != null) {
4779                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4780            }
4781        }
4782        return result;
4783    }
4784
4785    private ResolveInfo querySkipCurrentProfileIntents(
4786            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4787            int flags, int sourceUserId) {
4788        if (matchingFilters != null) {
4789            int size = matchingFilters.size();
4790            for (int i = 0; i < size; i ++) {
4791                CrossProfileIntentFilter filter = matchingFilters.get(i);
4792                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4793                    // Checking if there are activities in the target user that can handle the
4794                    // intent.
4795                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4796                            flags, sourceUserId);
4797                    if (resolveInfo != null) {
4798                        return resolveInfo;
4799                    }
4800                }
4801            }
4802        }
4803        return null;
4804    }
4805
4806    // Return matching ResolveInfo if any for skip current profile intent filters.
4807    private ResolveInfo queryCrossProfileIntents(
4808            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4809            int flags, int sourceUserId) {
4810        if (matchingFilters != null) {
4811            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4812            // match the same intent. For performance reasons, it is better not to
4813            // run queryIntent twice for the same userId
4814            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4815            int size = matchingFilters.size();
4816            for (int i = 0; i < size; i++) {
4817                CrossProfileIntentFilter filter = matchingFilters.get(i);
4818                int targetUserId = filter.getTargetUserId();
4819                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4820                        && !alreadyTriedUserIds.get(targetUserId)) {
4821                    // Checking if there are activities in the target user that can handle the
4822                    // intent.
4823                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4824                            flags, sourceUserId);
4825                    if (resolveInfo != null) return resolveInfo;
4826                    alreadyTriedUserIds.put(targetUserId, true);
4827                }
4828            }
4829        }
4830        return null;
4831    }
4832
4833    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4834            String resolvedType, int flags, int sourceUserId) {
4835        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4836                resolvedType, flags, filter.getTargetUserId());
4837        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4838            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4839        }
4840        return null;
4841    }
4842
4843    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4844            int sourceUserId, int targetUserId) {
4845        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4846        String className;
4847        if (targetUserId == UserHandle.USER_OWNER) {
4848            className = FORWARD_INTENT_TO_USER_OWNER;
4849        } else {
4850            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4851        }
4852        ComponentName forwardingActivityComponentName = new ComponentName(
4853                mAndroidApplication.packageName, className);
4854        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4855                sourceUserId);
4856        if (targetUserId == UserHandle.USER_OWNER) {
4857            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4858            forwardingResolveInfo.noResourceId = true;
4859        }
4860        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4861        forwardingResolveInfo.priority = 0;
4862        forwardingResolveInfo.preferredOrder = 0;
4863        forwardingResolveInfo.match = 0;
4864        forwardingResolveInfo.isDefault = true;
4865        forwardingResolveInfo.filter = filter;
4866        forwardingResolveInfo.targetUserId = targetUserId;
4867        return forwardingResolveInfo;
4868    }
4869
4870    @Override
4871    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4872            Intent[] specifics, String[] specificTypes, Intent intent,
4873            String resolvedType, int flags, int userId) {
4874        if (!sUserManager.exists(userId)) return Collections.emptyList();
4875        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4876                false, "query intent activity options");
4877        final String resultsAction = intent.getAction();
4878
4879        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4880                | PackageManager.GET_RESOLVED_FILTER, userId);
4881
4882        if (DEBUG_INTENT_MATCHING) {
4883            Log.v(TAG, "Query " + intent + ": " + results);
4884        }
4885
4886        int specificsPos = 0;
4887        int N;
4888
4889        // todo: note that the algorithm used here is O(N^2).  This
4890        // isn't a problem in our current environment, but if we start running
4891        // into situations where we have more than 5 or 10 matches then this
4892        // should probably be changed to something smarter...
4893
4894        // First we go through and resolve each of the specific items
4895        // that were supplied, taking care of removing any corresponding
4896        // duplicate items in the generic resolve list.
4897        if (specifics != null) {
4898            for (int i=0; i<specifics.length; i++) {
4899                final Intent sintent = specifics[i];
4900                if (sintent == null) {
4901                    continue;
4902                }
4903
4904                if (DEBUG_INTENT_MATCHING) {
4905                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4906                }
4907
4908                String action = sintent.getAction();
4909                if (resultsAction != null && resultsAction.equals(action)) {
4910                    // If this action was explicitly requested, then don't
4911                    // remove things that have it.
4912                    action = null;
4913                }
4914
4915                ResolveInfo ri = null;
4916                ActivityInfo ai = null;
4917
4918                ComponentName comp = sintent.getComponent();
4919                if (comp == null) {
4920                    ri = resolveIntent(
4921                        sintent,
4922                        specificTypes != null ? specificTypes[i] : null,
4923                            flags, userId);
4924                    if (ri == null) {
4925                        continue;
4926                    }
4927                    if (ri == mResolveInfo) {
4928                        // ACK!  Must do something better with this.
4929                    }
4930                    ai = ri.activityInfo;
4931                    comp = new ComponentName(ai.applicationInfo.packageName,
4932                            ai.name);
4933                } else {
4934                    ai = getActivityInfo(comp, flags, userId);
4935                    if (ai == null) {
4936                        continue;
4937                    }
4938                }
4939
4940                // Look for any generic query activities that are duplicates
4941                // of this specific one, and remove them from the results.
4942                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4943                N = results.size();
4944                int j;
4945                for (j=specificsPos; j<N; j++) {
4946                    ResolveInfo sri = results.get(j);
4947                    if ((sri.activityInfo.name.equals(comp.getClassName())
4948                            && sri.activityInfo.applicationInfo.packageName.equals(
4949                                    comp.getPackageName()))
4950                        || (action != null && sri.filter.matchAction(action))) {
4951                        results.remove(j);
4952                        if (DEBUG_INTENT_MATCHING) Log.v(
4953                            TAG, "Removing duplicate item from " + j
4954                            + " due to specific " + specificsPos);
4955                        if (ri == null) {
4956                            ri = sri;
4957                        }
4958                        j--;
4959                        N--;
4960                    }
4961                }
4962
4963                // Add this specific item to its proper place.
4964                if (ri == null) {
4965                    ri = new ResolveInfo();
4966                    ri.activityInfo = ai;
4967                }
4968                results.add(specificsPos, ri);
4969                ri.specificIndex = i;
4970                specificsPos++;
4971            }
4972        }
4973
4974        // Now we go through the remaining generic results and remove any
4975        // duplicate actions that are found here.
4976        N = results.size();
4977        for (int i=specificsPos; i<N-1; i++) {
4978            final ResolveInfo rii = results.get(i);
4979            if (rii.filter == null) {
4980                continue;
4981            }
4982
4983            // Iterate over all of the actions of this result's intent
4984            // filter...  typically this should be just one.
4985            final Iterator<String> it = rii.filter.actionsIterator();
4986            if (it == null) {
4987                continue;
4988            }
4989            while (it.hasNext()) {
4990                final String action = it.next();
4991                if (resultsAction != null && resultsAction.equals(action)) {
4992                    // If this action was explicitly requested, then don't
4993                    // remove things that have it.
4994                    continue;
4995                }
4996                for (int j=i+1; j<N; j++) {
4997                    final ResolveInfo rij = results.get(j);
4998                    if (rij.filter != null && rij.filter.hasAction(action)) {
4999                        results.remove(j);
5000                        if (DEBUG_INTENT_MATCHING) Log.v(
5001                            TAG, "Removing duplicate item from " + j
5002                            + " due to action " + action + " at " + i);
5003                        j--;
5004                        N--;
5005                    }
5006                }
5007            }
5008
5009            // If the caller didn't request filter information, drop it now
5010            // so we don't have to marshall/unmarshall it.
5011            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5012                rii.filter = null;
5013            }
5014        }
5015
5016        // Filter out the caller activity if so requested.
5017        if (caller != null) {
5018            N = results.size();
5019            for (int i=0; i<N; i++) {
5020                ActivityInfo ainfo = results.get(i).activityInfo;
5021                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5022                        && caller.getClassName().equals(ainfo.name)) {
5023                    results.remove(i);
5024                    break;
5025                }
5026            }
5027        }
5028
5029        // If the caller didn't request filter information,
5030        // drop them now so we don't have to
5031        // marshall/unmarshall it.
5032        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5033            N = results.size();
5034            for (int i=0; i<N; i++) {
5035                results.get(i).filter = null;
5036            }
5037        }
5038
5039        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5040        return results;
5041    }
5042
5043    @Override
5044    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5045            int userId) {
5046        if (!sUserManager.exists(userId)) return Collections.emptyList();
5047        ComponentName comp = intent.getComponent();
5048        if (comp == null) {
5049            if (intent.getSelector() != null) {
5050                intent = intent.getSelector();
5051                comp = intent.getComponent();
5052            }
5053        }
5054        if (comp != null) {
5055            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5056            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5057            if (ai != null) {
5058                ResolveInfo ri = new ResolveInfo();
5059                ri.activityInfo = ai;
5060                list.add(ri);
5061            }
5062            return list;
5063        }
5064
5065        // reader
5066        synchronized (mPackages) {
5067            String pkgName = intent.getPackage();
5068            if (pkgName == null) {
5069                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5070            }
5071            final PackageParser.Package pkg = mPackages.get(pkgName);
5072            if (pkg != null) {
5073                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5074                        userId);
5075            }
5076            return null;
5077        }
5078    }
5079
5080    @Override
5081    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5082        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5083        if (!sUserManager.exists(userId)) return null;
5084        if (query != null) {
5085            if (query.size() >= 1) {
5086                // If there is more than one service with the same priority,
5087                // just arbitrarily pick the first one.
5088                return query.get(0);
5089            }
5090        }
5091        return null;
5092    }
5093
5094    @Override
5095    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5096            int userId) {
5097        if (!sUserManager.exists(userId)) return Collections.emptyList();
5098        ComponentName comp = intent.getComponent();
5099        if (comp == null) {
5100            if (intent.getSelector() != null) {
5101                intent = intent.getSelector();
5102                comp = intent.getComponent();
5103            }
5104        }
5105        if (comp != null) {
5106            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5107            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5108            if (si != null) {
5109                final ResolveInfo ri = new ResolveInfo();
5110                ri.serviceInfo = si;
5111                list.add(ri);
5112            }
5113            return list;
5114        }
5115
5116        // reader
5117        synchronized (mPackages) {
5118            String pkgName = intent.getPackage();
5119            if (pkgName == null) {
5120                return mServices.queryIntent(intent, resolvedType, flags, userId);
5121            }
5122            final PackageParser.Package pkg = mPackages.get(pkgName);
5123            if (pkg != null) {
5124                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5125                        userId);
5126            }
5127            return null;
5128        }
5129    }
5130
5131    @Override
5132    public List<ResolveInfo> queryIntentContentProviders(
5133            Intent intent, String resolvedType, int flags, int userId) {
5134        if (!sUserManager.exists(userId)) return Collections.emptyList();
5135        ComponentName comp = intent.getComponent();
5136        if (comp == null) {
5137            if (intent.getSelector() != null) {
5138                intent = intent.getSelector();
5139                comp = intent.getComponent();
5140            }
5141        }
5142        if (comp != null) {
5143            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5144            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5145            if (pi != null) {
5146                final ResolveInfo ri = new ResolveInfo();
5147                ri.providerInfo = pi;
5148                list.add(ri);
5149            }
5150            return list;
5151        }
5152
5153        // reader
5154        synchronized (mPackages) {
5155            String pkgName = intent.getPackage();
5156            if (pkgName == null) {
5157                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5158            }
5159            final PackageParser.Package pkg = mPackages.get(pkgName);
5160            if (pkg != null) {
5161                return mProviders.queryIntentForPackage(
5162                        intent, resolvedType, flags, pkg.providers, userId);
5163            }
5164            return null;
5165        }
5166    }
5167
5168    @Override
5169    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5170        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5171
5172        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5173
5174        // writer
5175        synchronized (mPackages) {
5176            ArrayList<PackageInfo> list;
5177            if (listUninstalled) {
5178                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5179                for (PackageSetting ps : mSettings.mPackages.values()) {
5180                    PackageInfo pi;
5181                    if (ps.pkg != null) {
5182                        pi = generatePackageInfo(ps.pkg, flags, userId);
5183                    } else {
5184                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5185                    }
5186                    if (pi != null) {
5187                        list.add(pi);
5188                    }
5189                }
5190            } else {
5191                list = new ArrayList<PackageInfo>(mPackages.size());
5192                for (PackageParser.Package p : mPackages.values()) {
5193                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5194                    if (pi != null) {
5195                        list.add(pi);
5196                    }
5197                }
5198            }
5199
5200            return new ParceledListSlice<PackageInfo>(list);
5201        }
5202    }
5203
5204    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5205            String[] permissions, boolean[] tmp, int flags, int userId) {
5206        int numMatch = 0;
5207        final PermissionsState permissionsState = ps.getPermissionsState();
5208        for (int i=0; i<permissions.length; i++) {
5209            final String permission = permissions[i];
5210            if (permissionsState.hasPermission(permission, userId)) {
5211                tmp[i] = true;
5212                numMatch++;
5213            } else {
5214                tmp[i] = false;
5215            }
5216        }
5217        if (numMatch == 0) {
5218            return;
5219        }
5220        PackageInfo pi;
5221        if (ps.pkg != null) {
5222            pi = generatePackageInfo(ps.pkg, flags, userId);
5223        } else {
5224            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5225        }
5226        // The above might return null in cases of uninstalled apps or install-state
5227        // skew across users/profiles.
5228        if (pi != null) {
5229            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5230                if (numMatch == permissions.length) {
5231                    pi.requestedPermissions = permissions;
5232                } else {
5233                    pi.requestedPermissions = new String[numMatch];
5234                    numMatch = 0;
5235                    for (int i=0; i<permissions.length; i++) {
5236                        if (tmp[i]) {
5237                            pi.requestedPermissions[numMatch] = permissions[i];
5238                            numMatch++;
5239                        }
5240                    }
5241                }
5242            }
5243            list.add(pi);
5244        }
5245    }
5246
5247    @Override
5248    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5249            String[] permissions, int flags, int userId) {
5250        if (!sUserManager.exists(userId)) return null;
5251        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5252
5253        // writer
5254        synchronized (mPackages) {
5255            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5256            boolean[] tmpBools = new boolean[permissions.length];
5257            if (listUninstalled) {
5258                for (PackageSetting ps : mSettings.mPackages.values()) {
5259                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5260                }
5261            } else {
5262                for (PackageParser.Package pkg : mPackages.values()) {
5263                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5264                    if (ps != null) {
5265                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5266                                userId);
5267                    }
5268                }
5269            }
5270
5271            return new ParceledListSlice<PackageInfo>(list);
5272        }
5273    }
5274
5275    @Override
5276    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5277        if (!sUserManager.exists(userId)) return null;
5278        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5279
5280        // writer
5281        synchronized (mPackages) {
5282            ArrayList<ApplicationInfo> list;
5283            if (listUninstalled) {
5284                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5285                for (PackageSetting ps : mSettings.mPackages.values()) {
5286                    ApplicationInfo ai;
5287                    if (ps.pkg != null) {
5288                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5289                                ps.readUserState(userId), userId);
5290                    } else {
5291                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5292                    }
5293                    if (ai != null) {
5294                        list.add(ai);
5295                    }
5296                }
5297            } else {
5298                list = new ArrayList<ApplicationInfo>(mPackages.size());
5299                for (PackageParser.Package p : mPackages.values()) {
5300                    if (p.mExtras != null) {
5301                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5302                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5303                        if (ai != null) {
5304                            list.add(ai);
5305                        }
5306                    }
5307                }
5308            }
5309
5310            return new ParceledListSlice<ApplicationInfo>(list);
5311        }
5312    }
5313
5314    public List<ApplicationInfo> getPersistentApplications(int flags) {
5315        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5316
5317        // reader
5318        synchronized (mPackages) {
5319            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5320            final int userId = UserHandle.getCallingUserId();
5321            while (i.hasNext()) {
5322                final PackageParser.Package p = i.next();
5323                if (p.applicationInfo != null
5324                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5325                        && (!mSafeMode || isSystemApp(p))) {
5326                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5327                    if (ps != null) {
5328                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5329                                ps.readUserState(userId), userId);
5330                        if (ai != null) {
5331                            finalList.add(ai);
5332                        }
5333                    }
5334                }
5335            }
5336        }
5337
5338        return finalList;
5339    }
5340
5341    @Override
5342    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5343        if (!sUserManager.exists(userId)) return null;
5344        // reader
5345        synchronized (mPackages) {
5346            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5347            PackageSetting ps = provider != null
5348                    ? mSettings.mPackages.get(provider.owner.packageName)
5349                    : null;
5350            return ps != null
5351                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5352                    && (!mSafeMode || (provider.info.applicationInfo.flags
5353                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5354                    ? PackageParser.generateProviderInfo(provider, flags,
5355                            ps.readUserState(userId), userId)
5356                    : null;
5357        }
5358    }
5359
5360    /**
5361     * @deprecated
5362     */
5363    @Deprecated
5364    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5365        // reader
5366        synchronized (mPackages) {
5367            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5368                    .entrySet().iterator();
5369            final int userId = UserHandle.getCallingUserId();
5370            while (i.hasNext()) {
5371                Map.Entry<String, PackageParser.Provider> entry = i.next();
5372                PackageParser.Provider p = entry.getValue();
5373                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5374
5375                if (ps != null && p.syncable
5376                        && (!mSafeMode || (p.info.applicationInfo.flags
5377                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5378                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5379                            ps.readUserState(userId), userId);
5380                    if (info != null) {
5381                        outNames.add(entry.getKey());
5382                        outInfo.add(info);
5383                    }
5384                }
5385            }
5386        }
5387    }
5388
5389    @Override
5390    public List<ProviderInfo> queryContentProviders(String processName,
5391            int uid, int flags) {
5392        ArrayList<ProviderInfo> finalList = null;
5393        // reader
5394        synchronized (mPackages) {
5395            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5396            final int userId = processName != null ?
5397                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5398            while (i.hasNext()) {
5399                final PackageParser.Provider p = i.next();
5400                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5401                if (ps != null && p.info.authority != null
5402                        && (processName == null
5403                                || (p.info.processName.equals(processName)
5404                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5405                        && mSettings.isEnabledLPr(p.info, flags, userId)
5406                        && (!mSafeMode
5407                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5408                    if (finalList == null) {
5409                        finalList = new ArrayList<ProviderInfo>(3);
5410                    }
5411                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5412                            ps.readUserState(userId), userId);
5413                    if (info != null) {
5414                        finalList.add(info);
5415                    }
5416                }
5417            }
5418        }
5419
5420        if (finalList != null) {
5421            Collections.sort(finalList, mProviderInitOrderSorter);
5422        }
5423
5424        return finalList;
5425    }
5426
5427    @Override
5428    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5429            int flags) {
5430        // reader
5431        synchronized (mPackages) {
5432            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5433            return PackageParser.generateInstrumentationInfo(i, flags);
5434        }
5435    }
5436
5437    @Override
5438    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5439            int flags) {
5440        ArrayList<InstrumentationInfo> finalList =
5441            new ArrayList<InstrumentationInfo>();
5442
5443        // reader
5444        synchronized (mPackages) {
5445            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5446            while (i.hasNext()) {
5447                final PackageParser.Instrumentation p = i.next();
5448                if (targetPackage == null
5449                        || targetPackage.equals(p.info.targetPackage)) {
5450                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5451                            flags);
5452                    if (ii != null) {
5453                        finalList.add(ii);
5454                    }
5455                }
5456            }
5457        }
5458
5459        return finalList;
5460    }
5461
5462    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5463        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5464        if (overlays == null) {
5465            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5466            return;
5467        }
5468        for (PackageParser.Package opkg : overlays.values()) {
5469            // Not much to do if idmap fails: we already logged the error
5470            // and we certainly don't want to abort installation of pkg simply
5471            // because an overlay didn't fit properly. For these reasons,
5472            // ignore the return value of createIdmapForPackagePairLI.
5473            createIdmapForPackagePairLI(pkg, opkg);
5474        }
5475    }
5476
5477    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5478            PackageParser.Package opkg) {
5479        if (!opkg.mTrustedOverlay) {
5480            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5481                    opkg.baseCodePath + ": overlay not trusted");
5482            return false;
5483        }
5484        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5485        if (overlaySet == null) {
5486            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5487                    opkg.baseCodePath + " but target package has no known overlays");
5488            return false;
5489        }
5490        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5491        // TODO: generate idmap for split APKs
5492        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5493            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5494                    + opkg.baseCodePath);
5495            return false;
5496        }
5497        PackageParser.Package[] overlayArray =
5498            overlaySet.values().toArray(new PackageParser.Package[0]);
5499        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5500            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5501                return p1.mOverlayPriority - p2.mOverlayPriority;
5502            }
5503        };
5504        Arrays.sort(overlayArray, cmp);
5505
5506        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5507        int i = 0;
5508        for (PackageParser.Package p : overlayArray) {
5509            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5510        }
5511        return true;
5512    }
5513
5514    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5515        final File[] files = dir.listFiles();
5516        if (ArrayUtils.isEmpty(files)) {
5517            Log.d(TAG, "No files in app dir " + dir);
5518            return;
5519        }
5520
5521        if (DEBUG_PACKAGE_SCANNING) {
5522            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5523                    + " flags=0x" + Integer.toHexString(parseFlags));
5524        }
5525
5526        for (File file : files) {
5527            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5528                    && !PackageInstallerService.isStageName(file.getName());
5529            if (!isPackage) {
5530                // Ignore entries which are not packages
5531                continue;
5532            }
5533            try {
5534                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5535                        scanFlags, currentTime, null);
5536            } catch (PackageManagerException e) {
5537                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5538
5539                // Delete invalid userdata apps
5540                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5541                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5542                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5543                    if (file.isDirectory()) {
5544                        mInstaller.rmPackageDir(file.getAbsolutePath());
5545                    } else {
5546                        file.delete();
5547                    }
5548                }
5549            }
5550        }
5551    }
5552
5553    private static File getSettingsProblemFile() {
5554        File dataDir = Environment.getDataDirectory();
5555        File systemDir = new File(dataDir, "system");
5556        File fname = new File(systemDir, "uiderrors.txt");
5557        return fname;
5558    }
5559
5560    static void reportSettingsProblem(int priority, String msg) {
5561        logCriticalInfo(priority, msg);
5562    }
5563
5564    static void logCriticalInfo(int priority, String msg) {
5565        Slog.println(priority, TAG, msg);
5566        EventLogTags.writePmCriticalInfo(msg);
5567        try {
5568            File fname = getSettingsProblemFile();
5569            FileOutputStream out = new FileOutputStream(fname, true);
5570            PrintWriter pw = new FastPrintWriter(out);
5571            SimpleDateFormat formatter = new SimpleDateFormat();
5572            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5573            pw.println(dateString + ": " + msg);
5574            pw.close();
5575            FileUtils.setPermissions(
5576                    fname.toString(),
5577                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5578                    -1, -1);
5579        } catch (java.io.IOException e) {
5580        }
5581    }
5582
5583    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5584            PackageParser.Package pkg, File srcFile, int parseFlags)
5585            throws PackageManagerException {
5586        if (ps != null
5587                && ps.codePath.equals(srcFile)
5588                && ps.timeStamp == srcFile.lastModified()
5589                && !isCompatSignatureUpdateNeeded(pkg)
5590                && !isRecoverSignatureUpdateNeeded(pkg)) {
5591            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5592            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5593            ArraySet<PublicKey> signingKs;
5594            synchronized (mPackages) {
5595                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5596            }
5597            if (ps.signatures.mSignatures != null
5598                    && ps.signatures.mSignatures.length != 0
5599                    && signingKs != null) {
5600                // Optimization: reuse the existing cached certificates
5601                // if the package appears to be unchanged.
5602                pkg.mSignatures = ps.signatures.mSignatures;
5603                pkg.mSigningKeys = signingKs;
5604                return;
5605            }
5606
5607            Slog.w(TAG, "PackageSetting for " + ps.name
5608                    + " is missing signatures.  Collecting certs again to recover them.");
5609        } else {
5610            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5611        }
5612
5613        try {
5614            pp.collectCertificates(pkg, parseFlags);
5615            pp.collectManifestDigest(pkg);
5616        } catch (PackageParserException e) {
5617            throw PackageManagerException.from(e);
5618        }
5619    }
5620
5621    /*
5622     *  Scan a package and return the newly parsed package.
5623     *  Returns null in case of errors and the error code is stored in mLastScanError
5624     */
5625    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5626            long currentTime, UserHandle user) throws PackageManagerException {
5627        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5628        parseFlags |= mDefParseFlags;
5629        PackageParser pp = new PackageParser();
5630        pp.setSeparateProcesses(mSeparateProcesses);
5631        pp.setOnlyCoreApps(mOnlyCore);
5632        pp.setDisplayMetrics(mMetrics);
5633
5634        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5635            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5636        }
5637
5638        final PackageParser.Package pkg;
5639        try {
5640            pkg = pp.parsePackage(scanFile, parseFlags);
5641        } catch (PackageParserException e) {
5642            throw PackageManagerException.from(e);
5643        }
5644
5645        PackageSetting ps = null;
5646        PackageSetting updatedPkg;
5647        // reader
5648        synchronized (mPackages) {
5649            // Look to see if we already know about this package.
5650            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5651            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5652                // This package has been renamed to its original name.  Let's
5653                // use that.
5654                ps = mSettings.peekPackageLPr(oldName);
5655            }
5656            // If there was no original package, see one for the real package name.
5657            if (ps == null) {
5658                ps = mSettings.peekPackageLPr(pkg.packageName);
5659            }
5660            // Check to see if this package could be hiding/updating a system
5661            // package.  Must look for it either under the original or real
5662            // package name depending on our state.
5663            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5664            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5665        }
5666        boolean updatedPkgBetter = false;
5667        // First check if this is a system package that may involve an update
5668        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5669            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5670            // it needs to drop FLAG_PRIVILEGED.
5671            if (locationIsPrivileged(scanFile)) {
5672                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5673            } else {
5674                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5675            }
5676
5677            if (ps != null && !ps.codePath.equals(scanFile)) {
5678                // The path has changed from what was last scanned...  check the
5679                // version of the new path against what we have stored to determine
5680                // what to do.
5681                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5682                if (pkg.mVersionCode <= ps.versionCode) {
5683                    // The system package has been updated and the code path does not match
5684                    // Ignore entry. Skip it.
5685                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5686                            + " ignored: updated version " + ps.versionCode
5687                            + " better than this " + pkg.mVersionCode);
5688                    if (!updatedPkg.codePath.equals(scanFile)) {
5689                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5690                                + ps.name + " changing from " + updatedPkg.codePathString
5691                                + " to " + scanFile);
5692                        updatedPkg.codePath = scanFile;
5693                        updatedPkg.codePathString = scanFile.toString();
5694                        updatedPkg.resourcePath = scanFile;
5695                        updatedPkg.resourcePathString = scanFile.toString();
5696                    }
5697                    updatedPkg.pkg = pkg;
5698                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5699                            "Package " + ps.name + " at " + scanFile
5700                                    + " ignored: updated version " + ps.versionCode
5701                                    + " better than this " + pkg.mVersionCode);
5702                } else {
5703                    // The current app on the system partition is better than
5704                    // what we have updated to on the data partition; switch
5705                    // back to the system partition version.
5706                    // At this point, its safely assumed that package installation for
5707                    // apps in system partition will go through. If not there won't be a working
5708                    // version of the app
5709                    // writer
5710                    synchronized (mPackages) {
5711                        // Just remove the loaded entries from package lists.
5712                        mPackages.remove(ps.name);
5713                    }
5714
5715                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5716                            + " reverting from " + ps.codePathString
5717                            + ": new version " + pkg.mVersionCode
5718                            + " better than installed " + ps.versionCode);
5719
5720                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5721                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5722                    synchronized (mInstallLock) {
5723                        args.cleanUpResourcesLI();
5724                    }
5725                    synchronized (mPackages) {
5726                        mSettings.enableSystemPackageLPw(ps.name);
5727                    }
5728                    updatedPkgBetter = true;
5729                }
5730            }
5731        }
5732
5733        if (updatedPkg != null) {
5734            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5735            // initially
5736            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5737
5738            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5739            // flag set initially
5740            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5741                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5742            }
5743        }
5744
5745        // Verify certificates against what was last scanned
5746        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5747
5748        /*
5749         * A new system app appeared, but we already had a non-system one of the
5750         * same name installed earlier.
5751         */
5752        boolean shouldHideSystemApp = false;
5753        if (updatedPkg == null && ps != null
5754                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5755            /*
5756             * Check to make sure the signatures match first. If they don't,
5757             * wipe the installed application and its data.
5758             */
5759            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5760                    != PackageManager.SIGNATURE_MATCH) {
5761                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5762                        + " signatures don't match existing userdata copy; removing");
5763                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5764                ps = null;
5765            } else {
5766                /*
5767                 * If the newly-added system app is an older version than the
5768                 * already installed version, hide it. It will be scanned later
5769                 * and re-added like an update.
5770                 */
5771                if (pkg.mVersionCode <= ps.versionCode) {
5772                    shouldHideSystemApp = true;
5773                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5774                            + " but new version " + pkg.mVersionCode + " better than installed "
5775                            + ps.versionCode + "; hiding system");
5776                } else {
5777                    /*
5778                     * The newly found system app is a newer version that the
5779                     * one previously installed. Simply remove the
5780                     * already-installed application and replace it with our own
5781                     * while keeping the application data.
5782                     */
5783                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5784                            + " reverting from " + ps.codePathString + ": new version "
5785                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5786                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5787                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5788                    synchronized (mInstallLock) {
5789                        args.cleanUpResourcesLI();
5790                    }
5791                }
5792            }
5793        }
5794
5795        // The apk is forward locked (not public) if its code and resources
5796        // are kept in different files. (except for app in either system or
5797        // vendor path).
5798        // TODO grab this value from PackageSettings
5799        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5800            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5801                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5802            }
5803        }
5804
5805        // TODO: extend to support forward-locked splits
5806        String resourcePath = null;
5807        String baseResourcePath = null;
5808        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5809            if (ps != null && ps.resourcePathString != null) {
5810                resourcePath = ps.resourcePathString;
5811                baseResourcePath = ps.resourcePathString;
5812            } else {
5813                // Should not happen at all. Just log an error.
5814                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5815            }
5816        } else {
5817            resourcePath = pkg.codePath;
5818            baseResourcePath = pkg.baseCodePath;
5819        }
5820
5821        // Set application objects path explicitly.
5822        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5823        pkg.applicationInfo.setCodePath(pkg.codePath);
5824        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5825        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5826        pkg.applicationInfo.setResourcePath(resourcePath);
5827        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5828        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5829
5830        // Note that we invoke the following method only if we are about to unpack an application
5831        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5832                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5833
5834        /*
5835         * If the system app should be overridden by a previously installed
5836         * data, hide the system app now and let the /data/app scan pick it up
5837         * again.
5838         */
5839        if (shouldHideSystemApp) {
5840            synchronized (mPackages) {
5841                /*
5842                 * We have to grant systems permissions before we hide, because
5843                 * grantPermissions will assume the package update is trying to
5844                 * expand its permissions.
5845                 */
5846                grantPermissionsLPw(pkg, true, pkg.packageName);
5847                mSettings.disableSystemPackageLPw(pkg.packageName);
5848            }
5849        }
5850
5851        return scannedPkg;
5852    }
5853
5854    private static String fixProcessName(String defProcessName,
5855            String processName, int uid) {
5856        if (processName == null) {
5857            return defProcessName;
5858        }
5859        return processName;
5860    }
5861
5862    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5863            throws PackageManagerException {
5864        if (pkgSetting.signatures.mSignatures != null) {
5865            // Already existing package. Make sure signatures match
5866            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5867                    == PackageManager.SIGNATURE_MATCH;
5868            if (!match) {
5869                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5870                        == PackageManager.SIGNATURE_MATCH;
5871            }
5872            if (!match) {
5873                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5874                        == PackageManager.SIGNATURE_MATCH;
5875            }
5876            if (!match) {
5877                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5878                        + pkg.packageName + " signatures do not match the "
5879                        + "previously installed version; ignoring!");
5880            }
5881        }
5882
5883        // Check for shared user signatures
5884        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5885            // Already existing package. Make sure signatures match
5886            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5887                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5888            if (!match) {
5889                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5890                        == PackageManager.SIGNATURE_MATCH;
5891            }
5892            if (!match) {
5893                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5894                        == PackageManager.SIGNATURE_MATCH;
5895            }
5896            if (!match) {
5897                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5898                        "Package " + pkg.packageName
5899                        + " has no signatures that match those in shared user "
5900                        + pkgSetting.sharedUser.name + "; ignoring!");
5901            }
5902        }
5903    }
5904
5905    /**
5906     * Enforces that only the system UID or root's UID can call a method exposed
5907     * via Binder.
5908     *
5909     * @param message used as message if SecurityException is thrown
5910     * @throws SecurityException if the caller is not system or root
5911     */
5912    private static final void enforceSystemOrRoot(String message) {
5913        final int uid = Binder.getCallingUid();
5914        if (uid != Process.SYSTEM_UID && uid != 0) {
5915            throw new SecurityException(message);
5916        }
5917    }
5918
5919    @Override
5920    public void performBootDexOpt() {
5921        enforceSystemOrRoot("Only the system can request dexopt be performed");
5922
5923        // Before everything else, see whether we need to fstrim.
5924        try {
5925            IMountService ms = PackageHelper.getMountService();
5926            if (ms != null) {
5927                final boolean isUpgrade = isUpgrade();
5928                boolean doTrim = isUpgrade;
5929                if (doTrim) {
5930                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5931                } else {
5932                    final long interval = android.provider.Settings.Global.getLong(
5933                            mContext.getContentResolver(),
5934                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5935                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5936                    if (interval > 0) {
5937                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5938                        if (timeSinceLast > interval) {
5939                            doTrim = true;
5940                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5941                                    + "; running immediately");
5942                        }
5943                    }
5944                }
5945                if (doTrim) {
5946                    if (!isFirstBoot()) {
5947                        try {
5948                            ActivityManagerNative.getDefault().showBootMessage(
5949                                    mContext.getResources().getString(
5950                                            R.string.android_upgrading_fstrim), true);
5951                        } catch (RemoteException e) {
5952                        }
5953                    }
5954                    ms.runMaintenance();
5955                }
5956            } else {
5957                Slog.e(TAG, "Mount service unavailable!");
5958            }
5959        } catch (RemoteException e) {
5960            // Can't happen; MountService is local
5961        }
5962
5963        final ArraySet<PackageParser.Package> pkgs;
5964        synchronized (mPackages) {
5965            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5966        }
5967
5968        if (pkgs != null) {
5969            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5970            // in case the device runs out of space.
5971            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5972            // Give priority to core apps.
5973            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5974                PackageParser.Package pkg = it.next();
5975                if (pkg.coreApp) {
5976                    if (DEBUG_DEXOPT) {
5977                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5978                    }
5979                    sortedPkgs.add(pkg);
5980                    it.remove();
5981                }
5982            }
5983            // Give priority to system apps that listen for pre boot complete.
5984            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5985            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5986            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5987                PackageParser.Package pkg = it.next();
5988                if (pkgNames.contains(pkg.packageName)) {
5989                    if (DEBUG_DEXOPT) {
5990                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5991                    }
5992                    sortedPkgs.add(pkg);
5993                    it.remove();
5994                }
5995            }
5996            // Give priority to system apps.
5997            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5998                PackageParser.Package pkg = it.next();
5999                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6000                    if (DEBUG_DEXOPT) {
6001                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6002                    }
6003                    sortedPkgs.add(pkg);
6004                    it.remove();
6005                }
6006            }
6007            // Give priority to updated system apps.
6008            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6009                PackageParser.Package pkg = it.next();
6010                if (pkg.isUpdatedSystemApp()) {
6011                    if (DEBUG_DEXOPT) {
6012                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6013                    }
6014                    sortedPkgs.add(pkg);
6015                    it.remove();
6016                }
6017            }
6018            // Give priority to apps that listen for boot complete.
6019            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6020            pkgNames = getPackageNamesForIntent(intent);
6021            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6022                PackageParser.Package pkg = it.next();
6023                if (pkgNames.contains(pkg.packageName)) {
6024                    if (DEBUG_DEXOPT) {
6025                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6026                    }
6027                    sortedPkgs.add(pkg);
6028                    it.remove();
6029                }
6030            }
6031            // Filter out packages that aren't recently used.
6032            filterRecentlyUsedApps(pkgs);
6033            // Add all remaining apps.
6034            for (PackageParser.Package pkg : pkgs) {
6035                if (DEBUG_DEXOPT) {
6036                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6037                }
6038                sortedPkgs.add(pkg);
6039            }
6040
6041            // If we want to be lazy, filter everything that wasn't recently used.
6042            if (mLazyDexOpt) {
6043                filterRecentlyUsedApps(sortedPkgs);
6044            }
6045
6046            int i = 0;
6047            int total = sortedPkgs.size();
6048            File dataDir = Environment.getDataDirectory();
6049            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6050            if (lowThreshold == 0) {
6051                throw new IllegalStateException("Invalid low memory threshold");
6052            }
6053            for (PackageParser.Package pkg : sortedPkgs) {
6054                long usableSpace = dataDir.getUsableSpace();
6055                if (usableSpace < lowThreshold) {
6056                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6057                    break;
6058                }
6059                performBootDexOpt(pkg, ++i, total);
6060            }
6061        }
6062    }
6063
6064    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6065        // Filter out packages that aren't recently used.
6066        //
6067        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6068        // should do a full dexopt.
6069        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6070            int total = pkgs.size();
6071            int skipped = 0;
6072            long now = System.currentTimeMillis();
6073            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6074                PackageParser.Package pkg = i.next();
6075                long then = pkg.mLastPackageUsageTimeInMills;
6076                if (then + mDexOptLRUThresholdInMills < now) {
6077                    if (DEBUG_DEXOPT) {
6078                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6079                              ((then == 0) ? "never" : new Date(then)));
6080                    }
6081                    i.remove();
6082                    skipped++;
6083                }
6084            }
6085            if (DEBUG_DEXOPT) {
6086                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6087            }
6088        }
6089    }
6090
6091    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6092        List<ResolveInfo> ris = null;
6093        try {
6094            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6095                    intent, null, 0, UserHandle.USER_OWNER);
6096        } catch (RemoteException e) {
6097        }
6098        ArraySet<String> pkgNames = new ArraySet<String>();
6099        if (ris != null) {
6100            for (ResolveInfo ri : ris) {
6101                pkgNames.add(ri.activityInfo.packageName);
6102            }
6103        }
6104        return pkgNames;
6105    }
6106
6107    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6108        if (DEBUG_DEXOPT) {
6109            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6110        }
6111        if (!isFirstBoot()) {
6112            try {
6113                ActivityManagerNative.getDefault().showBootMessage(
6114                        mContext.getResources().getString(R.string.android_upgrading_apk,
6115                                curr, total), true);
6116            } catch (RemoteException e) {
6117            }
6118        }
6119        PackageParser.Package p = pkg;
6120        synchronized (mInstallLock) {
6121            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6122                    false /* force dex */, false /* defer */, true /* include dependencies */);
6123        }
6124    }
6125
6126    @Override
6127    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6128        return performDexOpt(packageName, instructionSet, false);
6129    }
6130
6131    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6132        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6133        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6134        if (!dexopt && !updateUsage) {
6135            // We aren't going to dexopt or update usage, so bail early.
6136            return false;
6137        }
6138        PackageParser.Package p;
6139        final String targetInstructionSet;
6140        synchronized (mPackages) {
6141            p = mPackages.get(packageName);
6142            if (p == null) {
6143                return false;
6144            }
6145            if (updateUsage) {
6146                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6147            }
6148            mPackageUsage.write(false);
6149            if (!dexopt) {
6150                // We aren't going to dexopt, so bail early.
6151                return false;
6152            }
6153
6154            targetInstructionSet = instructionSet != null ? instructionSet :
6155                    getPrimaryInstructionSet(p.applicationInfo);
6156            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6157                return false;
6158            }
6159        }
6160
6161        synchronized (mInstallLock) {
6162            final String[] instructionSets = new String[] { targetInstructionSet };
6163            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6164                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6165            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6166        }
6167    }
6168
6169    public ArraySet<String> getPackagesThatNeedDexOpt() {
6170        ArraySet<String> pkgs = null;
6171        synchronized (mPackages) {
6172            for (PackageParser.Package p : mPackages.values()) {
6173                if (DEBUG_DEXOPT) {
6174                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6175                }
6176                if (!p.mDexOptPerformed.isEmpty()) {
6177                    continue;
6178                }
6179                if (pkgs == null) {
6180                    pkgs = new ArraySet<String>();
6181                }
6182                pkgs.add(p.packageName);
6183            }
6184        }
6185        return pkgs;
6186    }
6187
6188    public void shutdown() {
6189        mPackageUsage.write(true);
6190    }
6191
6192    @Override
6193    public void forceDexOpt(String packageName) {
6194        enforceSystemOrRoot("forceDexOpt");
6195
6196        PackageParser.Package pkg;
6197        synchronized (mPackages) {
6198            pkg = mPackages.get(packageName);
6199            if (pkg == null) {
6200                throw new IllegalArgumentException("Missing package: " + packageName);
6201            }
6202        }
6203
6204        synchronized (mInstallLock) {
6205            final String[] instructionSets = new String[] {
6206                    getPrimaryInstructionSet(pkg.applicationInfo) };
6207            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6208                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6209            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6210                throw new IllegalStateException("Failed to dexopt: " + res);
6211            }
6212        }
6213    }
6214
6215    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6216        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6217            Slog.w(TAG, "Unable to update from " + oldPkg.name
6218                    + " to " + newPkg.packageName
6219                    + ": old package not in system partition");
6220            return false;
6221        } else if (mPackages.get(oldPkg.name) != null) {
6222            Slog.w(TAG, "Unable to update from " + oldPkg.name
6223                    + " to " + newPkg.packageName
6224                    + ": old package still exists");
6225            return false;
6226        }
6227        return true;
6228    }
6229
6230    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6231        int[] users = sUserManager.getUserIds();
6232        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6233        if (res < 0) {
6234            return res;
6235        }
6236        for (int user : users) {
6237            if (user != 0) {
6238                res = mInstaller.createUserData(volumeUuid, packageName,
6239                        UserHandle.getUid(user, uid), user, seinfo);
6240                if (res < 0) {
6241                    return res;
6242                }
6243            }
6244        }
6245        return res;
6246    }
6247
6248    private int removeDataDirsLI(String volumeUuid, String packageName) {
6249        int[] users = sUserManager.getUserIds();
6250        int res = 0;
6251        for (int user : users) {
6252            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6253            if (resInner < 0) {
6254                res = resInner;
6255            }
6256        }
6257
6258        return res;
6259    }
6260
6261    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6262        int[] users = sUserManager.getUserIds();
6263        int res = 0;
6264        for (int user : users) {
6265            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6266            if (resInner < 0) {
6267                res = resInner;
6268            }
6269        }
6270        return res;
6271    }
6272
6273    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6274            PackageParser.Package changingLib) {
6275        if (file.path != null) {
6276            usesLibraryFiles.add(file.path);
6277            return;
6278        }
6279        PackageParser.Package p = mPackages.get(file.apk);
6280        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6281            // If we are doing this while in the middle of updating a library apk,
6282            // then we need to make sure to use that new apk for determining the
6283            // dependencies here.  (We haven't yet finished committing the new apk
6284            // to the package manager state.)
6285            if (p == null || p.packageName.equals(changingLib.packageName)) {
6286                p = changingLib;
6287            }
6288        }
6289        if (p != null) {
6290            usesLibraryFiles.addAll(p.getAllCodePaths());
6291        }
6292    }
6293
6294    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6295            PackageParser.Package changingLib) throws PackageManagerException {
6296        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6297            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6298            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6299            for (int i=0; i<N; i++) {
6300                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6301                if (file == null) {
6302                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6303                            "Package " + pkg.packageName + " requires unavailable shared library "
6304                            + pkg.usesLibraries.get(i) + "; failing!");
6305                }
6306                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6307            }
6308            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6309            for (int i=0; i<N; i++) {
6310                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6311                if (file == null) {
6312                    Slog.w(TAG, "Package " + pkg.packageName
6313                            + " desires unavailable shared library "
6314                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6315                } else {
6316                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6317                }
6318            }
6319            N = usesLibraryFiles.size();
6320            if (N > 0) {
6321                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6322            } else {
6323                pkg.usesLibraryFiles = null;
6324            }
6325        }
6326    }
6327
6328    private static boolean hasString(List<String> list, List<String> which) {
6329        if (list == null) {
6330            return false;
6331        }
6332        for (int i=list.size()-1; i>=0; i--) {
6333            for (int j=which.size()-1; j>=0; j--) {
6334                if (which.get(j).equals(list.get(i))) {
6335                    return true;
6336                }
6337            }
6338        }
6339        return false;
6340    }
6341
6342    private void updateAllSharedLibrariesLPw() {
6343        for (PackageParser.Package pkg : mPackages.values()) {
6344            try {
6345                updateSharedLibrariesLPw(pkg, null);
6346            } catch (PackageManagerException e) {
6347                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6348            }
6349        }
6350    }
6351
6352    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6353            PackageParser.Package changingPkg) {
6354        ArrayList<PackageParser.Package> res = null;
6355        for (PackageParser.Package pkg : mPackages.values()) {
6356            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6357                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6358                if (res == null) {
6359                    res = new ArrayList<PackageParser.Package>();
6360                }
6361                res.add(pkg);
6362                try {
6363                    updateSharedLibrariesLPw(pkg, changingPkg);
6364                } catch (PackageManagerException e) {
6365                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6366                }
6367            }
6368        }
6369        return res;
6370    }
6371
6372    /**
6373     * Derive the value of the {@code cpuAbiOverride} based on the provided
6374     * value and an optional stored value from the package settings.
6375     */
6376    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6377        String cpuAbiOverride = null;
6378
6379        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6380            cpuAbiOverride = null;
6381        } else if (abiOverride != null) {
6382            cpuAbiOverride = abiOverride;
6383        } else if (settings != null) {
6384            cpuAbiOverride = settings.cpuAbiOverrideString;
6385        }
6386
6387        return cpuAbiOverride;
6388    }
6389
6390    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6391            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6392        boolean success = false;
6393        try {
6394            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6395                    currentTime, user);
6396            success = true;
6397            return res;
6398        } finally {
6399            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6400                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6401            }
6402        }
6403    }
6404
6405    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6406            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6407        final File scanFile = new File(pkg.codePath);
6408        if (pkg.applicationInfo.getCodePath() == null ||
6409                pkg.applicationInfo.getResourcePath() == null) {
6410            // Bail out. The resource and code paths haven't been set.
6411            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6412                    "Code and resource paths haven't been set correctly");
6413        }
6414
6415        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6416            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6417        } else {
6418            // Only allow system apps to be flagged as core apps.
6419            pkg.coreApp = false;
6420        }
6421
6422        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6423            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6424        }
6425
6426        if (mCustomResolverComponentName != null &&
6427                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6428            setUpCustomResolverActivity(pkg);
6429        }
6430
6431        if (pkg.packageName.equals("android")) {
6432            synchronized (mPackages) {
6433                if (mAndroidApplication != null) {
6434                    Slog.w(TAG, "*************************************************");
6435                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6436                    Slog.w(TAG, " file=" + scanFile);
6437                    Slog.w(TAG, "*************************************************");
6438                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6439                            "Core android package being redefined.  Skipping.");
6440                }
6441
6442                // Set up information for our fall-back user intent resolution activity.
6443                mPlatformPackage = pkg;
6444                pkg.mVersionCode = mSdkVersion;
6445                mAndroidApplication = pkg.applicationInfo;
6446
6447                if (!mResolverReplaced) {
6448                    mResolveActivity.applicationInfo = mAndroidApplication;
6449                    mResolveActivity.name = ResolverActivity.class.getName();
6450                    mResolveActivity.packageName = mAndroidApplication.packageName;
6451                    mResolveActivity.processName = "system:ui";
6452                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6453                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6454                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6455                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6456                    mResolveActivity.exported = true;
6457                    mResolveActivity.enabled = true;
6458                    mResolveInfo.activityInfo = mResolveActivity;
6459                    mResolveInfo.priority = 0;
6460                    mResolveInfo.preferredOrder = 0;
6461                    mResolveInfo.match = 0;
6462                    mResolveComponentName = new ComponentName(
6463                            mAndroidApplication.packageName, mResolveActivity.name);
6464                }
6465            }
6466        }
6467
6468        if (DEBUG_PACKAGE_SCANNING) {
6469            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6470                Log.d(TAG, "Scanning package " + pkg.packageName);
6471        }
6472
6473        if (mPackages.containsKey(pkg.packageName)
6474                || mSharedLibraries.containsKey(pkg.packageName)) {
6475            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6476                    "Application package " + pkg.packageName
6477                    + " already installed.  Skipping duplicate.");
6478        }
6479
6480        // If we're only installing presumed-existing packages, require that the
6481        // scanned APK is both already known and at the path previously established
6482        // for it.  Previously unknown packages we pick up normally, but if we have an
6483        // a priori expectation about this package's install presence, enforce it.
6484        // With a singular exception for new system packages. When an OTA contains
6485        // a new system package, we allow the codepath to change from a system location
6486        // to the user-installed location. If we don't allow this change, any newer,
6487        // user-installed version of the application will be ignored.
6488        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6489            if (mExpectingBetter.containsKey(pkg.packageName)) {
6490                logCriticalInfo(Log.WARN,
6491                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6492            } else {
6493                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6494                if (known != null) {
6495                    if (DEBUG_PACKAGE_SCANNING) {
6496                        Log.d(TAG, "Examining " + pkg.codePath
6497                                + " and requiring known paths " + known.codePathString
6498                                + " & " + known.resourcePathString);
6499                    }
6500                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6501                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6502                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6503                                "Application package " + pkg.packageName
6504                                + " found at " + pkg.applicationInfo.getCodePath()
6505                                + " but expected at " + known.codePathString + "; ignoring.");
6506                    }
6507                }
6508            }
6509        }
6510
6511        // Initialize package source and resource directories
6512        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6513        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6514
6515        SharedUserSetting suid = null;
6516        PackageSetting pkgSetting = null;
6517
6518        if (!isSystemApp(pkg)) {
6519            // Only system apps can use these features.
6520            pkg.mOriginalPackages = null;
6521            pkg.mRealPackage = null;
6522            pkg.mAdoptPermissions = null;
6523        }
6524
6525        // writer
6526        synchronized (mPackages) {
6527            if (pkg.mSharedUserId != null) {
6528                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6529                if (suid == null) {
6530                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6531                            "Creating application package " + pkg.packageName
6532                            + " for shared user failed");
6533                }
6534                if (DEBUG_PACKAGE_SCANNING) {
6535                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6536                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6537                                + "): packages=" + suid.packages);
6538                }
6539            }
6540
6541            // Check if we are renaming from an original package name.
6542            PackageSetting origPackage = null;
6543            String realName = null;
6544            if (pkg.mOriginalPackages != null) {
6545                // This package may need to be renamed to a previously
6546                // installed name.  Let's check on that...
6547                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6548                if (pkg.mOriginalPackages.contains(renamed)) {
6549                    // This package had originally been installed as the
6550                    // original name, and we have already taken care of
6551                    // transitioning to the new one.  Just update the new
6552                    // one to continue using the old name.
6553                    realName = pkg.mRealPackage;
6554                    if (!pkg.packageName.equals(renamed)) {
6555                        // Callers into this function may have already taken
6556                        // care of renaming the package; only do it here if
6557                        // it is not already done.
6558                        pkg.setPackageName(renamed);
6559                    }
6560
6561                } else {
6562                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6563                        if ((origPackage = mSettings.peekPackageLPr(
6564                                pkg.mOriginalPackages.get(i))) != null) {
6565                            // We do have the package already installed under its
6566                            // original name...  should we use it?
6567                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6568                                // New package is not compatible with original.
6569                                origPackage = null;
6570                                continue;
6571                            } else if (origPackage.sharedUser != null) {
6572                                // Make sure uid is compatible between packages.
6573                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6574                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6575                                            + " to " + pkg.packageName + ": old uid "
6576                                            + origPackage.sharedUser.name
6577                                            + " differs from " + pkg.mSharedUserId);
6578                                    origPackage = null;
6579                                    continue;
6580                                }
6581                            } else {
6582                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6583                                        + pkg.packageName + " to old name " + origPackage.name);
6584                            }
6585                            break;
6586                        }
6587                    }
6588                }
6589            }
6590
6591            if (mTransferedPackages.contains(pkg.packageName)) {
6592                Slog.w(TAG, "Package " + pkg.packageName
6593                        + " was transferred to another, but its .apk remains");
6594            }
6595
6596            // Just create the setting, don't add it yet. For already existing packages
6597            // the PkgSetting exists already and doesn't have to be created.
6598            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6599                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6600                    pkg.applicationInfo.primaryCpuAbi,
6601                    pkg.applicationInfo.secondaryCpuAbi,
6602                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6603                    user, false);
6604            if (pkgSetting == null) {
6605                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6606                        "Creating application package " + pkg.packageName + " failed");
6607            }
6608
6609            if (pkgSetting.origPackage != null) {
6610                // If we are first transitioning from an original package,
6611                // fix up the new package's name now.  We need to do this after
6612                // looking up the package under its new name, so getPackageLP
6613                // can take care of fiddling things correctly.
6614                pkg.setPackageName(origPackage.name);
6615
6616                // File a report about this.
6617                String msg = "New package " + pkgSetting.realName
6618                        + " renamed to replace old package " + pkgSetting.name;
6619                reportSettingsProblem(Log.WARN, msg);
6620
6621                // Make a note of it.
6622                mTransferedPackages.add(origPackage.name);
6623
6624                // No longer need to retain this.
6625                pkgSetting.origPackage = null;
6626            }
6627
6628            if (realName != null) {
6629                // Make a note of it.
6630                mTransferedPackages.add(pkg.packageName);
6631            }
6632
6633            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6634                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6635            }
6636
6637            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6638                // Check all shared libraries and map to their actual file path.
6639                // We only do this here for apps not on a system dir, because those
6640                // are the only ones that can fail an install due to this.  We
6641                // will take care of the system apps by updating all of their
6642                // library paths after the scan is done.
6643                updateSharedLibrariesLPw(pkg, null);
6644            }
6645
6646            if (mFoundPolicyFile) {
6647                SELinuxMMAC.assignSeinfoValue(pkg);
6648            }
6649
6650            pkg.applicationInfo.uid = pkgSetting.appId;
6651            pkg.mExtras = pkgSetting;
6652            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6653                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6654                    // We just determined the app is signed correctly, so bring
6655                    // over the latest parsed certs.
6656                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6657                } else {
6658                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6659                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6660                                "Package " + pkg.packageName + " upgrade keys do not match the "
6661                                + "previously installed version");
6662                    } else {
6663                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6664                        String msg = "System package " + pkg.packageName
6665                            + " signature changed; retaining data.";
6666                        reportSettingsProblem(Log.WARN, msg);
6667                    }
6668                }
6669            } else {
6670                try {
6671                    verifySignaturesLP(pkgSetting, pkg);
6672                    // We just determined the app is signed correctly, so bring
6673                    // over the latest parsed certs.
6674                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6675                } catch (PackageManagerException e) {
6676                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6677                        throw e;
6678                    }
6679                    // The signature has changed, but this package is in the system
6680                    // image...  let's recover!
6681                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6682                    // However...  if this package is part of a shared user, but it
6683                    // doesn't match the signature of the shared user, let's fail.
6684                    // What this means is that you can't change the signatures
6685                    // associated with an overall shared user, which doesn't seem all
6686                    // that unreasonable.
6687                    if (pkgSetting.sharedUser != null) {
6688                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6689                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6690                            throw new PackageManagerException(
6691                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6692                                            "Signature mismatch for shared user : "
6693                                            + pkgSetting.sharedUser);
6694                        }
6695                    }
6696                    // File a report about this.
6697                    String msg = "System package " + pkg.packageName
6698                        + " signature changed; retaining data.";
6699                    reportSettingsProblem(Log.WARN, msg);
6700                }
6701            }
6702            // Verify that this new package doesn't have any content providers
6703            // that conflict with existing packages.  Only do this if the
6704            // package isn't already installed, since we don't want to break
6705            // things that are installed.
6706            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6707                final int N = pkg.providers.size();
6708                int i;
6709                for (i=0; i<N; i++) {
6710                    PackageParser.Provider p = pkg.providers.get(i);
6711                    if (p.info.authority != null) {
6712                        String names[] = p.info.authority.split(";");
6713                        for (int j = 0; j < names.length; j++) {
6714                            if (mProvidersByAuthority.containsKey(names[j])) {
6715                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6716                                final String otherPackageName =
6717                                        ((other != null && other.getComponentName() != null) ?
6718                                                other.getComponentName().getPackageName() : "?");
6719                                throw new PackageManagerException(
6720                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6721                                                "Can't install because provider name " + names[j]
6722                                                + " (in package " + pkg.applicationInfo.packageName
6723                                                + ") is already used by " + otherPackageName);
6724                            }
6725                        }
6726                    }
6727                }
6728            }
6729
6730            if (pkg.mAdoptPermissions != null) {
6731                // This package wants to adopt ownership of permissions from
6732                // another package.
6733                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6734                    final String origName = pkg.mAdoptPermissions.get(i);
6735                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6736                    if (orig != null) {
6737                        if (verifyPackageUpdateLPr(orig, pkg)) {
6738                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6739                                    + pkg.packageName);
6740                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6741                        }
6742                    }
6743                }
6744            }
6745        }
6746
6747        final String pkgName = pkg.packageName;
6748
6749        final long scanFileTime = scanFile.lastModified();
6750        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6751        pkg.applicationInfo.processName = fixProcessName(
6752                pkg.applicationInfo.packageName,
6753                pkg.applicationInfo.processName,
6754                pkg.applicationInfo.uid);
6755
6756        File dataPath;
6757        if (mPlatformPackage == pkg) {
6758            // The system package is special.
6759            dataPath = new File(Environment.getDataDirectory(), "system");
6760
6761            pkg.applicationInfo.dataDir = dataPath.getPath();
6762
6763        } else {
6764            // This is a normal package, need to make its data directory.
6765            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6766                    UserHandle.USER_OWNER, pkg.packageName);
6767
6768            boolean uidError = false;
6769            if (dataPath.exists()) {
6770                int currentUid = 0;
6771                try {
6772                    StructStat stat = Os.stat(dataPath.getPath());
6773                    currentUid = stat.st_uid;
6774                } catch (ErrnoException e) {
6775                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6776                }
6777
6778                // If we have mismatched owners for the data path, we have a problem.
6779                if (currentUid != pkg.applicationInfo.uid) {
6780                    boolean recovered = false;
6781                    if (currentUid == 0) {
6782                        // The directory somehow became owned by root.  Wow.
6783                        // This is probably because the system was stopped while
6784                        // installd was in the middle of messing with its libs
6785                        // directory.  Ask installd to fix that.
6786                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6787                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6788                        if (ret >= 0) {
6789                            recovered = true;
6790                            String msg = "Package " + pkg.packageName
6791                                    + " unexpectedly changed to uid 0; recovered to " +
6792                                    + pkg.applicationInfo.uid;
6793                            reportSettingsProblem(Log.WARN, msg);
6794                        }
6795                    }
6796                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6797                            || (scanFlags&SCAN_BOOTING) != 0)) {
6798                        // If this is a system app, we can at least delete its
6799                        // current data so the application will still work.
6800                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6801                        if (ret >= 0) {
6802                            // TODO: Kill the processes first
6803                            // Old data gone!
6804                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6805                                    ? "System package " : "Third party package ";
6806                            String msg = prefix + pkg.packageName
6807                                    + " has changed from uid: "
6808                                    + currentUid + " to "
6809                                    + pkg.applicationInfo.uid + "; old data erased";
6810                            reportSettingsProblem(Log.WARN, msg);
6811                            recovered = true;
6812
6813                            // And now re-install the app.
6814                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6815                                    pkg.applicationInfo.seinfo);
6816                            if (ret == -1) {
6817                                // Ack should not happen!
6818                                msg = prefix + pkg.packageName
6819                                        + " could not have data directory re-created after delete.";
6820                                reportSettingsProblem(Log.WARN, msg);
6821                                throw new PackageManagerException(
6822                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6823                            }
6824                        }
6825                        if (!recovered) {
6826                            mHasSystemUidErrors = true;
6827                        }
6828                    } else if (!recovered) {
6829                        // If we allow this install to proceed, we will be broken.
6830                        // Abort, abort!
6831                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6832                                "scanPackageLI");
6833                    }
6834                    if (!recovered) {
6835                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6836                            + pkg.applicationInfo.uid + "/fs_"
6837                            + currentUid;
6838                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6839                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6840                        String msg = "Package " + pkg.packageName
6841                                + " has mismatched uid: "
6842                                + currentUid + " on disk, "
6843                                + pkg.applicationInfo.uid + " in settings";
6844                        // writer
6845                        synchronized (mPackages) {
6846                            mSettings.mReadMessages.append(msg);
6847                            mSettings.mReadMessages.append('\n');
6848                            uidError = true;
6849                            if (!pkgSetting.uidError) {
6850                                reportSettingsProblem(Log.ERROR, msg);
6851                            }
6852                        }
6853                    }
6854                }
6855                pkg.applicationInfo.dataDir = dataPath.getPath();
6856                if (mShouldRestoreconData) {
6857                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6858                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6859                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6860                }
6861            } else {
6862                if (DEBUG_PACKAGE_SCANNING) {
6863                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6864                        Log.v(TAG, "Want this data dir: " + dataPath);
6865                }
6866                //invoke installer to do the actual installation
6867                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6868                        pkg.applicationInfo.seinfo);
6869                if (ret < 0) {
6870                    // Error from installer
6871                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6872                            "Unable to create data dirs [errorCode=" + ret + "]");
6873                }
6874
6875                if (dataPath.exists()) {
6876                    pkg.applicationInfo.dataDir = dataPath.getPath();
6877                } else {
6878                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6879                    pkg.applicationInfo.dataDir = null;
6880                }
6881            }
6882
6883            pkgSetting.uidError = uidError;
6884        }
6885
6886        final String path = scanFile.getPath();
6887        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6888
6889        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6890            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6891
6892            // Some system apps still use directory structure for native libraries
6893            // in which case we might end up not detecting abi solely based on apk
6894            // structure. Try to detect abi based on directory structure.
6895            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6896                    pkg.applicationInfo.primaryCpuAbi == null) {
6897                setBundledAppAbisAndRoots(pkg, pkgSetting);
6898                setNativeLibraryPaths(pkg);
6899            }
6900
6901        } else {
6902            if ((scanFlags & SCAN_MOVE) != 0) {
6903                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6904                // but we already have this packages package info in the PackageSetting. We just
6905                // use that and derive the native library path based on the new codepath.
6906                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6907                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6908            }
6909
6910            // Set native library paths again. For moves, the path will be updated based on the
6911            // ABIs we've determined above. For non-moves, the path will be updated based on the
6912            // ABIs we determined during compilation, but the path will depend on the final
6913            // package path (after the rename away from the stage path).
6914            setNativeLibraryPaths(pkg);
6915        }
6916
6917        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6918        final int[] userIds = sUserManager.getUserIds();
6919        synchronized (mInstallLock) {
6920            // Make sure all user data directories are ready to roll; we're okay
6921            // if they already exist
6922            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6923                for (int userId : userIds) {
6924                    if (userId != 0) {
6925                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6926                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6927                                pkg.applicationInfo.seinfo);
6928                    }
6929                }
6930            }
6931
6932            // Create a native library symlink only if we have native libraries
6933            // and if the native libraries are 32 bit libraries. We do not provide
6934            // this symlink for 64 bit libraries.
6935            if (pkg.applicationInfo.primaryCpuAbi != null &&
6936                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6937                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6938                for (int userId : userIds) {
6939                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6940                            nativeLibPath, userId) < 0) {
6941                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6942                                "Failed linking native library dir (user=" + userId + ")");
6943                    }
6944                }
6945            }
6946        }
6947
6948        // This is a special case for the "system" package, where the ABI is
6949        // dictated by the zygote configuration (and init.rc). We should keep track
6950        // of this ABI so that we can deal with "normal" applications that run under
6951        // the same UID correctly.
6952        if (mPlatformPackage == pkg) {
6953            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6954                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6955        }
6956
6957        // If there's a mismatch between the abi-override in the package setting
6958        // and the abiOverride specified for the install. Warn about this because we
6959        // would've already compiled the app without taking the package setting into
6960        // account.
6961        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6962            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6963                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6964                        " for package: " + pkg.packageName);
6965            }
6966        }
6967
6968        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6969        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6970        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6971
6972        // Copy the derived override back to the parsed package, so that we can
6973        // update the package settings accordingly.
6974        pkg.cpuAbiOverride = cpuAbiOverride;
6975
6976        if (DEBUG_ABI_SELECTION) {
6977            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6978                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6979                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6980        }
6981
6982        // Push the derived path down into PackageSettings so we know what to
6983        // clean up at uninstall time.
6984        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6985
6986        if (DEBUG_ABI_SELECTION) {
6987            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6988                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6989                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6990        }
6991
6992        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6993            // We don't do this here during boot because we can do it all
6994            // at once after scanning all existing packages.
6995            //
6996            // We also do this *before* we perform dexopt on this package, so that
6997            // we can avoid redundant dexopts, and also to make sure we've got the
6998            // code and package path correct.
6999            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7000                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7001        }
7002
7003        if ((scanFlags & SCAN_NO_DEX) == 0) {
7004            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7005                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7006            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7007                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7008            }
7009        }
7010        if (mFactoryTest && pkg.requestedPermissions.contains(
7011                android.Manifest.permission.FACTORY_TEST)) {
7012            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7013        }
7014
7015        ArrayList<PackageParser.Package> clientLibPkgs = null;
7016
7017        // writer
7018        synchronized (mPackages) {
7019            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7020                // Only system apps can add new shared libraries.
7021                if (pkg.libraryNames != null) {
7022                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7023                        String name = pkg.libraryNames.get(i);
7024                        boolean allowed = false;
7025                        if (pkg.isUpdatedSystemApp()) {
7026                            // New library entries can only be added through the
7027                            // system image.  This is important to get rid of a lot
7028                            // of nasty edge cases: for example if we allowed a non-
7029                            // system update of the app to add a library, then uninstalling
7030                            // the update would make the library go away, and assumptions
7031                            // we made such as through app install filtering would now
7032                            // have allowed apps on the device which aren't compatible
7033                            // with it.  Better to just have the restriction here, be
7034                            // conservative, and create many fewer cases that can negatively
7035                            // impact the user experience.
7036                            final PackageSetting sysPs = mSettings
7037                                    .getDisabledSystemPkgLPr(pkg.packageName);
7038                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7039                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7040                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7041                                        allowed = true;
7042                                        allowed = true;
7043                                        break;
7044                                    }
7045                                }
7046                            }
7047                        } else {
7048                            allowed = true;
7049                        }
7050                        if (allowed) {
7051                            if (!mSharedLibraries.containsKey(name)) {
7052                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7053                            } else if (!name.equals(pkg.packageName)) {
7054                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7055                                        + name + " already exists; skipping");
7056                            }
7057                        } else {
7058                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7059                                    + name + " that is not declared on system image; skipping");
7060                        }
7061                    }
7062                    if ((scanFlags&SCAN_BOOTING) == 0) {
7063                        // If we are not booting, we need to update any applications
7064                        // that are clients of our shared library.  If we are booting,
7065                        // this will all be done once the scan is complete.
7066                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7067                    }
7068                }
7069            }
7070        }
7071
7072        // We also need to dexopt any apps that are dependent on this library.  Note that
7073        // if these fail, we should abort the install since installing the library will
7074        // result in some apps being broken.
7075        if (clientLibPkgs != null) {
7076            if ((scanFlags & SCAN_NO_DEX) == 0) {
7077                for (int i = 0; i < clientLibPkgs.size(); i++) {
7078                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7079                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7080                            null /* instruction sets */, forceDex,
7081                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7082                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7083                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7084                                "scanPackageLI failed to dexopt clientLibPkgs");
7085                    }
7086                }
7087            }
7088        }
7089
7090        // Also need to kill any apps that are dependent on the library.
7091        if (clientLibPkgs != null) {
7092            for (int i=0; i<clientLibPkgs.size(); i++) {
7093                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7094                killApplication(clientPkg.applicationInfo.packageName,
7095                        clientPkg.applicationInfo.uid, "update lib");
7096            }
7097        }
7098
7099        // Make sure we're not adding any bogus keyset info
7100        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7101        ksms.assertScannedPackageValid(pkg);
7102
7103        // writer
7104        synchronized (mPackages) {
7105            // We don't expect installation to fail beyond this point
7106
7107            // Add the new setting to mSettings
7108            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7109            // Add the new setting to mPackages
7110            mPackages.put(pkg.applicationInfo.packageName, pkg);
7111            // Make sure we don't accidentally delete its data.
7112            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7113            while (iter.hasNext()) {
7114                PackageCleanItem item = iter.next();
7115                if (pkgName.equals(item.packageName)) {
7116                    iter.remove();
7117                }
7118            }
7119
7120            // Take care of first install / last update times.
7121            if (currentTime != 0) {
7122                if (pkgSetting.firstInstallTime == 0) {
7123                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7124                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7125                    pkgSetting.lastUpdateTime = currentTime;
7126                }
7127            } else if (pkgSetting.firstInstallTime == 0) {
7128                // We need *something*.  Take time time stamp of the file.
7129                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7130            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7131                if (scanFileTime != pkgSetting.timeStamp) {
7132                    // A package on the system image has changed; consider this
7133                    // to be an update.
7134                    pkgSetting.lastUpdateTime = scanFileTime;
7135                }
7136            }
7137
7138            // Add the package's KeySets to the global KeySetManagerService
7139            ksms.addScannedPackageLPw(pkg);
7140
7141            int N = pkg.providers.size();
7142            StringBuilder r = null;
7143            int i;
7144            for (i=0; i<N; i++) {
7145                PackageParser.Provider p = pkg.providers.get(i);
7146                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7147                        p.info.processName, pkg.applicationInfo.uid);
7148                mProviders.addProvider(p);
7149                p.syncable = p.info.isSyncable;
7150                if (p.info.authority != null) {
7151                    String names[] = p.info.authority.split(";");
7152                    p.info.authority = null;
7153                    for (int j = 0; j < names.length; j++) {
7154                        if (j == 1 && p.syncable) {
7155                            // We only want the first authority for a provider to possibly be
7156                            // syncable, so if we already added this provider using a different
7157                            // authority clear the syncable flag. We copy the provider before
7158                            // changing it because the mProviders object contains a reference
7159                            // to a provider that we don't want to change.
7160                            // Only do this for the second authority since the resulting provider
7161                            // object can be the same for all future authorities for this provider.
7162                            p = new PackageParser.Provider(p);
7163                            p.syncable = false;
7164                        }
7165                        if (!mProvidersByAuthority.containsKey(names[j])) {
7166                            mProvidersByAuthority.put(names[j], p);
7167                            if (p.info.authority == null) {
7168                                p.info.authority = names[j];
7169                            } else {
7170                                p.info.authority = p.info.authority + ";" + names[j];
7171                            }
7172                            if (DEBUG_PACKAGE_SCANNING) {
7173                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7174                                    Log.d(TAG, "Registered content provider: " + names[j]
7175                                            + ", className = " + p.info.name + ", isSyncable = "
7176                                            + p.info.isSyncable);
7177                            }
7178                        } else {
7179                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7180                            Slog.w(TAG, "Skipping provider name " + names[j] +
7181                                    " (in package " + pkg.applicationInfo.packageName +
7182                                    "): name already used by "
7183                                    + ((other != null && other.getComponentName() != null)
7184                                            ? other.getComponentName().getPackageName() : "?"));
7185                        }
7186                    }
7187                }
7188                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7189                    if (r == null) {
7190                        r = new StringBuilder(256);
7191                    } else {
7192                        r.append(' ');
7193                    }
7194                    r.append(p.info.name);
7195                }
7196            }
7197            if (r != null) {
7198                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7199            }
7200
7201            N = pkg.services.size();
7202            r = null;
7203            for (i=0; i<N; i++) {
7204                PackageParser.Service s = pkg.services.get(i);
7205                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7206                        s.info.processName, pkg.applicationInfo.uid);
7207                mServices.addService(s);
7208                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7209                    if (r == null) {
7210                        r = new StringBuilder(256);
7211                    } else {
7212                        r.append(' ');
7213                    }
7214                    r.append(s.info.name);
7215                }
7216            }
7217            if (r != null) {
7218                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7219            }
7220
7221            N = pkg.receivers.size();
7222            r = null;
7223            for (i=0; i<N; i++) {
7224                PackageParser.Activity a = pkg.receivers.get(i);
7225                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7226                        a.info.processName, pkg.applicationInfo.uid);
7227                mReceivers.addActivity(a, "receiver");
7228                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7229                    if (r == null) {
7230                        r = new StringBuilder(256);
7231                    } else {
7232                        r.append(' ');
7233                    }
7234                    r.append(a.info.name);
7235                }
7236            }
7237            if (r != null) {
7238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7239            }
7240
7241            N = pkg.activities.size();
7242            r = null;
7243            for (i=0; i<N; i++) {
7244                PackageParser.Activity a = pkg.activities.get(i);
7245                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7246                        a.info.processName, pkg.applicationInfo.uid);
7247                mActivities.addActivity(a, "activity");
7248                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7249                    if (r == null) {
7250                        r = new StringBuilder(256);
7251                    } else {
7252                        r.append(' ');
7253                    }
7254                    r.append(a.info.name);
7255                }
7256            }
7257            if (r != null) {
7258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7259            }
7260
7261            N = pkg.permissionGroups.size();
7262            r = null;
7263            for (i=0; i<N; i++) {
7264                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7265                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7266                if (cur == null) {
7267                    mPermissionGroups.put(pg.info.name, pg);
7268                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7269                        if (r == null) {
7270                            r = new StringBuilder(256);
7271                        } else {
7272                            r.append(' ');
7273                        }
7274                        r.append(pg.info.name);
7275                    }
7276                } else {
7277                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7278                            + pg.info.packageName + " ignored: original from "
7279                            + cur.info.packageName);
7280                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7281                        if (r == null) {
7282                            r = new StringBuilder(256);
7283                        } else {
7284                            r.append(' ');
7285                        }
7286                        r.append("DUP:");
7287                        r.append(pg.info.name);
7288                    }
7289                }
7290            }
7291            if (r != null) {
7292                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7293            }
7294
7295            N = pkg.permissions.size();
7296            r = null;
7297            for (i=0; i<N; i++) {
7298                PackageParser.Permission p = pkg.permissions.get(i);
7299
7300                // Now that permission groups have a special meaning, we ignore permission
7301                // groups for legacy apps to prevent unexpected behavior. In particular,
7302                // permissions for one app being granted to someone just becuase they happen
7303                // to be in a group defined by another app (before this had no implications).
7304                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7305                    p.group = mPermissionGroups.get(p.info.group);
7306                    // Warn for a permission in an unknown group.
7307                    if (p.info.group != null && p.group == null) {
7308                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7309                                + p.info.packageName + " in an unknown group " + p.info.group);
7310                    }
7311                }
7312
7313                ArrayMap<String, BasePermission> permissionMap =
7314                        p.tree ? mSettings.mPermissionTrees
7315                                : mSettings.mPermissions;
7316                BasePermission bp = permissionMap.get(p.info.name);
7317
7318                // Allow system apps to redefine non-system permissions
7319                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7320                    final boolean currentOwnerIsSystem = (bp.perm != null
7321                            && isSystemApp(bp.perm.owner));
7322                    if (isSystemApp(p.owner)) {
7323                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7324                            // It's a built-in permission and no owner, take ownership now
7325                            bp.packageSetting = pkgSetting;
7326                            bp.perm = p;
7327                            bp.uid = pkg.applicationInfo.uid;
7328                            bp.sourcePackage = p.info.packageName;
7329                        } else if (!currentOwnerIsSystem) {
7330                            String msg = "New decl " + p.owner + " of permission  "
7331                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7332                            reportSettingsProblem(Log.WARN, msg);
7333                            bp = null;
7334                        }
7335                    }
7336                }
7337
7338                if (bp == null) {
7339                    bp = new BasePermission(p.info.name, p.info.packageName,
7340                            BasePermission.TYPE_NORMAL);
7341                    permissionMap.put(p.info.name, bp);
7342                }
7343
7344                if (bp.perm == null) {
7345                    if (bp.sourcePackage == null
7346                            || bp.sourcePackage.equals(p.info.packageName)) {
7347                        BasePermission tree = findPermissionTreeLP(p.info.name);
7348                        if (tree == null
7349                                || tree.sourcePackage.equals(p.info.packageName)) {
7350                            bp.packageSetting = pkgSetting;
7351                            bp.perm = p;
7352                            bp.uid = pkg.applicationInfo.uid;
7353                            bp.sourcePackage = p.info.packageName;
7354                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7355                                if (r == null) {
7356                                    r = new StringBuilder(256);
7357                                } else {
7358                                    r.append(' ');
7359                                }
7360                                r.append(p.info.name);
7361                            }
7362                        } else {
7363                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7364                                    + p.info.packageName + " ignored: base tree "
7365                                    + tree.name + " is from package "
7366                                    + tree.sourcePackage);
7367                        }
7368                    } else {
7369                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7370                                + p.info.packageName + " ignored: original from "
7371                                + bp.sourcePackage);
7372                    }
7373                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7374                    if (r == null) {
7375                        r = new StringBuilder(256);
7376                    } else {
7377                        r.append(' ');
7378                    }
7379                    r.append("DUP:");
7380                    r.append(p.info.name);
7381                }
7382                if (bp.perm == p) {
7383                    bp.protectionLevel = p.info.protectionLevel;
7384                }
7385            }
7386
7387            if (r != null) {
7388                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7389            }
7390
7391            N = pkg.instrumentation.size();
7392            r = null;
7393            for (i=0; i<N; i++) {
7394                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7395                a.info.packageName = pkg.applicationInfo.packageName;
7396                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7397                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7398                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7399                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7400                a.info.dataDir = pkg.applicationInfo.dataDir;
7401
7402                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7403                // need other information about the application, like the ABI and what not ?
7404                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7405                mInstrumentation.put(a.getComponentName(), a);
7406                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7407                    if (r == null) {
7408                        r = new StringBuilder(256);
7409                    } else {
7410                        r.append(' ');
7411                    }
7412                    r.append(a.info.name);
7413                }
7414            }
7415            if (r != null) {
7416                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7417            }
7418
7419            if (pkg.protectedBroadcasts != null) {
7420                N = pkg.protectedBroadcasts.size();
7421                for (i=0; i<N; i++) {
7422                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7423                }
7424            }
7425
7426            pkgSetting.setTimeStamp(scanFileTime);
7427
7428            // Create idmap files for pairs of (packages, overlay packages).
7429            // Note: "android", ie framework-res.apk, is handled by native layers.
7430            if (pkg.mOverlayTarget != null) {
7431                // This is an overlay package.
7432                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7433                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7434                        mOverlays.put(pkg.mOverlayTarget,
7435                                new ArrayMap<String, PackageParser.Package>());
7436                    }
7437                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7438                    map.put(pkg.packageName, pkg);
7439                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7440                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7441                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7442                                "scanPackageLI failed to createIdmap");
7443                    }
7444                }
7445            } else if (mOverlays.containsKey(pkg.packageName) &&
7446                    !pkg.packageName.equals("android")) {
7447                // This is a regular package, with one or more known overlay packages.
7448                createIdmapsForPackageLI(pkg);
7449            }
7450        }
7451
7452        return pkg;
7453    }
7454
7455    /**
7456     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7457     * is derived purely on the basis of the contents of {@code scanFile} and
7458     * {@code cpuAbiOverride}.
7459     *
7460     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7461     */
7462    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7463                                 String cpuAbiOverride, boolean extractLibs)
7464            throws PackageManagerException {
7465        // TODO: We can probably be smarter about this stuff. For installed apps,
7466        // we can calculate this information at install time once and for all. For
7467        // system apps, we can probably assume that this information doesn't change
7468        // after the first boot scan. As things stand, we do lots of unnecessary work.
7469
7470        // Give ourselves some initial paths; we'll come back for another
7471        // pass once we've determined ABI below.
7472        setNativeLibraryPaths(pkg);
7473
7474        // We would never need to extract libs for forward-locked and external packages,
7475        // since the container service will do it for us. We shouldn't attempt to
7476        // extract libs from system app when it was not updated.
7477        if (pkg.isForwardLocked() || isExternal(pkg) ||
7478            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7479            extractLibs = false;
7480        }
7481
7482        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7483        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7484
7485        NativeLibraryHelper.Handle handle = null;
7486        try {
7487            handle = NativeLibraryHelper.Handle.create(pkg);
7488            // TODO(multiArch): This can be null for apps that didn't go through the
7489            // usual installation process. We can calculate it again, like we
7490            // do during install time.
7491            //
7492            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7493            // unnecessary.
7494            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7495
7496            // Null out the abis so that they can be recalculated.
7497            pkg.applicationInfo.primaryCpuAbi = null;
7498            pkg.applicationInfo.secondaryCpuAbi = null;
7499            if (isMultiArch(pkg.applicationInfo)) {
7500                // Warn if we've set an abiOverride for multi-lib packages..
7501                // By definition, we need to copy both 32 and 64 bit libraries for
7502                // such packages.
7503                if (pkg.cpuAbiOverride != null
7504                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7505                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7506                }
7507
7508                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7509                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7510                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7511                    if (extractLibs) {
7512                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7513                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7514                                useIsaSpecificSubdirs);
7515                    } else {
7516                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7517                    }
7518                }
7519
7520                maybeThrowExceptionForMultiArchCopy(
7521                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7522
7523                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7524                    if (extractLibs) {
7525                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7526                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7527                                useIsaSpecificSubdirs);
7528                    } else {
7529                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7530                    }
7531                }
7532
7533                maybeThrowExceptionForMultiArchCopy(
7534                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7535
7536                if (abi64 >= 0) {
7537                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7538                }
7539
7540                if (abi32 >= 0) {
7541                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7542                    if (abi64 >= 0) {
7543                        pkg.applicationInfo.secondaryCpuAbi = abi;
7544                    } else {
7545                        pkg.applicationInfo.primaryCpuAbi = abi;
7546                    }
7547                }
7548            } else {
7549                String[] abiList = (cpuAbiOverride != null) ?
7550                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7551
7552                // Enable gross and lame hacks for apps that are built with old
7553                // SDK tools. We must scan their APKs for renderscript bitcode and
7554                // not launch them if it's present. Don't bother checking on devices
7555                // that don't have 64 bit support.
7556                boolean needsRenderScriptOverride = false;
7557                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7558                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7559                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7560                    needsRenderScriptOverride = true;
7561                }
7562
7563                final int copyRet;
7564                if (extractLibs) {
7565                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7566                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7567                } else {
7568                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7569                }
7570
7571                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7572                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7573                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7574                }
7575
7576                if (copyRet >= 0) {
7577                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7578                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7579                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7580                } else if (needsRenderScriptOverride) {
7581                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7582                }
7583            }
7584        } catch (IOException ioe) {
7585            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7586        } finally {
7587            IoUtils.closeQuietly(handle);
7588        }
7589
7590        // Now that we've calculated the ABIs and determined if it's an internal app,
7591        // we will go ahead and populate the nativeLibraryPath.
7592        setNativeLibraryPaths(pkg);
7593    }
7594
7595    /**
7596     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7597     * i.e, so that all packages can be run inside a single process if required.
7598     *
7599     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7600     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7601     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7602     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7603     * updating a package that belongs to a shared user.
7604     *
7605     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7606     * adds unnecessary complexity.
7607     */
7608    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7609            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7610        String requiredInstructionSet = null;
7611        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7612            requiredInstructionSet = VMRuntime.getInstructionSet(
7613                     scannedPackage.applicationInfo.primaryCpuAbi);
7614        }
7615
7616        PackageSetting requirer = null;
7617        for (PackageSetting ps : packagesForUser) {
7618            // If packagesForUser contains scannedPackage, we skip it. This will happen
7619            // when scannedPackage is an update of an existing package. Without this check,
7620            // we will never be able to change the ABI of any package belonging to a shared
7621            // user, even if it's compatible with other packages.
7622            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7623                if (ps.primaryCpuAbiString == null) {
7624                    continue;
7625                }
7626
7627                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7628                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7629                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7630                    // this but there's not much we can do.
7631                    String errorMessage = "Instruction set mismatch, "
7632                            + ((requirer == null) ? "[caller]" : requirer)
7633                            + " requires " + requiredInstructionSet + " whereas " + ps
7634                            + " requires " + instructionSet;
7635                    Slog.w(TAG, errorMessage);
7636                }
7637
7638                if (requiredInstructionSet == null) {
7639                    requiredInstructionSet = instructionSet;
7640                    requirer = ps;
7641                }
7642            }
7643        }
7644
7645        if (requiredInstructionSet != null) {
7646            String adjustedAbi;
7647            if (requirer != null) {
7648                // requirer != null implies that either scannedPackage was null or that scannedPackage
7649                // did not require an ABI, in which case we have to adjust scannedPackage to match
7650                // the ABI of the set (which is the same as requirer's ABI)
7651                adjustedAbi = requirer.primaryCpuAbiString;
7652                if (scannedPackage != null) {
7653                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7654                }
7655            } else {
7656                // requirer == null implies that we're updating all ABIs in the set to
7657                // match scannedPackage.
7658                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7659            }
7660
7661            for (PackageSetting ps : packagesForUser) {
7662                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7663                    if (ps.primaryCpuAbiString != null) {
7664                        continue;
7665                    }
7666
7667                    ps.primaryCpuAbiString = adjustedAbi;
7668                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7669                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7670                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7671
7672                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7673                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7674                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7675                            ps.primaryCpuAbiString = null;
7676                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7677                            return;
7678                        } else {
7679                            mInstaller.rmdex(ps.codePathString,
7680                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7681                        }
7682                    }
7683                }
7684            }
7685        }
7686    }
7687
7688    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7689        synchronized (mPackages) {
7690            mResolverReplaced = true;
7691            // Set up information for custom user intent resolution activity.
7692            mResolveActivity.applicationInfo = pkg.applicationInfo;
7693            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7694            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7695            mResolveActivity.processName = pkg.applicationInfo.packageName;
7696            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7697            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7698                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7699            mResolveActivity.theme = 0;
7700            mResolveActivity.exported = true;
7701            mResolveActivity.enabled = true;
7702            mResolveInfo.activityInfo = mResolveActivity;
7703            mResolveInfo.priority = 0;
7704            mResolveInfo.preferredOrder = 0;
7705            mResolveInfo.match = 0;
7706            mResolveComponentName = mCustomResolverComponentName;
7707            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7708                    mResolveComponentName);
7709        }
7710    }
7711
7712    private static String calculateBundledApkRoot(final String codePathString) {
7713        final File codePath = new File(codePathString);
7714        final File codeRoot;
7715        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7716            codeRoot = Environment.getRootDirectory();
7717        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7718            codeRoot = Environment.getOemDirectory();
7719        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7720            codeRoot = Environment.getVendorDirectory();
7721        } else {
7722            // Unrecognized code path; take its top real segment as the apk root:
7723            // e.g. /something/app/blah.apk => /something
7724            try {
7725                File f = codePath.getCanonicalFile();
7726                File parent = f.getParentFile();    // non-null because codePath is a file
7727                File tmp;
7728                while ((tmp = parent.getParentFile()) != null) {
7729                    f = parent;
7730                    parent = tmp;
7731                }
7732                codeRoot = f;
7733                Slog.w(TAG, "Unrecognized code path "
7734                        + codePath + " - using " + codeRoot);
7735            } catch (IOException e) {
7736                // Can't canonicalize the code path -- shenanigans?
7737                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7738                return Environment.getRootDirectory().getPath();
7739            }
7740        }
7741        return codeRoot.getPath();
7742    }
7743
7744    /**
7745     * Derive and set the location of native libraries for the given package,
7746     * which varies depending on where and how the package was installed.
7747     */
7748    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7749        final ApplicationInfo info = pkg.applicationInfo;
7750        final String codePath = pkg.codePath;
7751        final File codeFile = new File(codePath);
7752        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7753        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7754
7755        info.nativeLibraryRootDir = null;
7756        info.nativeLibraryRootRequiresIsa = false;
7757        info.nativeLibraryDir = null;
7758        info.secondaryNativeLibraryDir = null;
7759
7760        if (isApkFile(codeFile)) {
7761            // Monolithic install
7762            if (bundledApp) {
7763                // If "/system/lib64/apkname" exists, assume that is the per-package
7764                // native library directory to use; otherwise use "/system/lib/apkname".
7765                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7766                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7767                        getPrimaryInstructionSet(info));
7768
7769                // This is a bundled system app so choose the path based on the ABI.
7770                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7771                // is just the default path.
7772                final String apkName = deriveCodePathName(codePath);
7773                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7774                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7775                        apkName).getAbsolutePath();
7776
7777                if (info.secondaryCpuAbi != null) {
7778                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7779                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7780                            secondaryLibDir, apkName).getAbsolutePath();
7781                }
7782            } else if (asecApp) {
7783                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7784                        .getAbsolutePath();
7785            } else {
7786                final String apkName = deriveCodePathName(codePath);
7787                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7788                        .getAbsolutePath();
7789            }
7790
7791            info.nativeLibraryRootRequiresIsa = false;
7792            info.nativeLibraryDir = info.nativeLibraryRootDir;
7793        } else {
7794            // Cluster install
7795            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7796            info.nativeLibraryRootRequiresIsa = true;
7797
7798            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7799                    getPrimaryInstructionSet(info)).getAbsolutePath();
7800
7801            if (info.secondaryCpuAbi != null) {
7802                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7803                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7804            }
7805        }
7806    }
7807
7808    /**
7809     * Calculate the abis and roots for a bundled app. These can uniquely
7810     * be determined from the contents of the system partition, i.e whether
7811     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7812     * of this information, and instead assume that the system was built
7813     * sensibly.
7814     */
7815    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7816                                           PackageSetting pkgSetting) {
7817        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7818
7819        // If "/system/lib64/apkname" exists, assume that is the per-package
7820        // native library directory to use; otherwise use "/system/lib/apkname".
7821        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7822        setBundledAppAbi(pkg, apkRoot, apkName);
7823        // pkgSetting might be null during rescan following uninstall of updates
7824        // to a bundled app, so accommodate that possibility.  The settings in
7825        // that case will be established later from the parsed package.
7826        //
7827        // If the settings aren't null, sync them up with what we've just derived.
7828        // note that apkRoot isn't stored in the package settings.
7829        if (pkgSetting != null) {
7830            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7831            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7832        }
7833    }
7834
7835    /**
7836     * Deduces the ABI of a bundled app and sets the relevant fields on the
7837     * parsed pkg object.
7838     *
7839     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7840     *        under which system libraries are installed.
7841     * @param apkName the name of the installed package.
7842     */
7843    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7844        final File codeFile = new File(pkg.codePath);
7845
7846        final boolean has64BitLibs;
7847        final boolean has32BitLibs;
7848        if (isApkFile(codeFile)) {
7849            // Monolithic install
7850            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7851            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7852        } else {
7853            // Cluster install
7854            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7855            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7856                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7857                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7858                has64BitLibs = (new File(rootDir, isa)).exists();
7859            } else {
7860                has64BitLibs = false;
7861            }
7862            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7863                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7864                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7865                has32BitLibs = (new File(rootDir, isa)).exists();
7866            } else {
7867                has32BitLibs = false;
7868            }
7869        }
7870
7871        if (has64BitLibs && !has32BitLibs) {
7872            // The package has 64 bit libs, but not 32 bit libs. Its primary
7873            // ABI should be 64 bit. We can safely assume here that the bundled
7874            // native libraries correspond to the most preferred ABI in the list.
7875
7876            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7877            pkg.applicationInfo.secondaryCpuAbi = null;
7878        } else if (has32BitLibs && !has64BitLibs) {
7879            // The package has 32 bit libs but not 64 bit libs. Its primary
7880            // ABI should be 32 bit.
7881
7882            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7883            pkg.applicationInfo.secondaryCpuAbi = null;
7884        } else if (has32BitLibs && has64BitLibs) {
7885            // The application has both 64 and 32 bit bundled libraries. We check
7886            // here that the app declares multiArch support, and warn if it doesn't.
7887            //
7888            // We will be lenient here and record both ABIs. The primary will be the
7889            // ABI that's higher on the list, i.e, a device that's configured to prefer
7890            // 64 bit apps will see a 64 bit primary ABI,
7891
7892            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7893                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7894            }
7895
7896            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7897                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7898                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7899            } else {
7900                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7901                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7902            }
7903        } else {
7904            pkg.applicationInfo.primaryCpuAbi = null;
7905            pkg.applicationInfo.secondaryCpuAbi = null;
7906        }
7907    }
7908
7909    private void killApplication(String pkgName, int appId, String reason) {
7910        // Request the ActivityManager to kill the process(only for existing packages)
7911        // so that we do not end up in a confused state while the user is still using the older
7912        // version of the application while the new one gets installed.
7913        IActivityManager am = ActivityManagerNative.getDefault();
7914        if (am != null) {
7915            try {
7916                am.killApplicationWithAppId(pkgName, appId, reason);
7917            } catch (RemoteException e) {
7918            }
7919        }
7920    }
7921
7922    void removePackageLI(PackageSetting ps, boolean chatty) {
7923        if (DEBUG_INSTALL) {
7924            if (chatty)
7925                Log.d(TAG, "Removing package " + ps.name);
7926        }
7927
7928        // writer
7929        synchronized (mPackages) {
7930            mPackages.remove(ps.name);
7931            final PackageParser.Package pkg = ps.pkg;
7932            if (pkg != null) {
7933                cleanPackageDataStructuresLILPw(pkg, chatty);
7934            }
7935        }
7936    }
7937
7938    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7939        if (DEBUG_INSTALL) {
7940            if (chatty)
7941                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7942        }
7943
7944        // writer
7945        synchronized (mPackages) {
7946            mPackages.remove(pkg.applicationInfo.packageName);
7947            cleanPackageDataStructuresLILPw(pkg, chatty);
7948        }
7949    }
7950
7951    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7952        int N = pkg.providers.size();
7953        StringBuilder r = null;
7954        int i;
7955        for (i=0; i<N; i++) {
7956            PackageParser.Provider p = pkg.providers.get(i);
7957            mProviders.removeProvider(p);
7958            if (p.info.authority == null) {
7959
7960                /* There was another ContentProvider with this authority when
7961                 * this app was installed so this authority is null,
7962                 * Ignore it as we don't have to unregister the provider.
7963                 */
7964                continue;
7965            }
7966            String names[] = p.info.authority.split(";");
7967            for (int j = 0; j < names.length; j++) {
7968                if (mProvidersByAuthority.get(names[j]) == p) {
7969                    mProvidersByAuthority.remove(names[j]);
7970                    if (DEBUG_REMOVE) {
7971                        if (chatty)
7972                            Log.d(TAG, "Unregistered content provider: " + names[j]
7973                                    + ", className = " + p.info.name + ", isSyncable = "
7974                                    + p.info.isSyncable);
7975                    }
7976                }
7977            }
7978            if (DEBUG_REMOVE && chatty) {
7979                if (r == null) {
7980                    r = new StringBuilder(256);
7981                } else {
7982                    r.append(' ');
7983                }
7984                r.append(p.info.name);
7985            }
7986        }
7987        if (r != null) {
7988            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7989        }
7990
7991        N = pkg.services.size();
7992        r = null;
7993        for (i=0; i<N; i++) {
7994            PackageParser.Service s = pkg.services.get(i);
7995            mServices.removeService(s);
7996            if (chatty) {
7997                if (r == null) {
7998                    r = new StringBuilder(256);
7999                } else {
8000                    r.append(' ');
8001                }
8002                r.append(s.info.name);
8003            }
8004        }
8005        if (r != null) {
8006            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8007        }
8008
8009        N = pkg.receivers.size();
8010        r = null;
8011        for (i=0; i<N; i++) {
8012            PackageParser.Activity a = pkg.receivers.get(i);
8013            mReceivers.removeActivity(a, "receiver");
8014            if (DEBUG_REMOVE && chatty) {
8015                if (r == null) {
8016                    r = new StringBuilder(256);
8017                } else {
8018                    r.append(' ');
8019                }
8020                r.append(a.info.name);
8021            }
8022        }
8023        if (r != null) {
8024            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8025        }
8026
8027        N = pkg.activities.size();
8028        r = null;
8029        for (i=0; i<N; i++) {
8030            PackageParser.Activity a = pkg.activities.get(i);
8031            mActivities.removeActivity(a, "activity");
8032            if (DEBUG_REMOVE && chatty) {
8033                if (r == null) {
8034                    r = new StringBuilder(256);
8035                } else {
8036                    r.append(' ');
8037                }
8038                r.append(a.info.name);
8039            }
8040        }
8041        if (r != null) {
8042            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8043        }
8044
8045        N = pkg.permissions.size();
8046        r = null;
8047        for (i=0; i<N; i++) {
8048            PackageParser.Permission p = pkg.permissions.get(i);
8049            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8050            if (bp == null) {
8051                bp = mSettings.mPermissionTrees.get(p.info.name);
8052            }
8053            if (bp != null && bp.perm == p) {
8054                bp.perm = null;
8055                if (DEBUG_REMOVE && chatty) {
8056                    if (r == null) {
8057                        r = new StringBuilder(256);
8058                    } else {
8059                        r.append(' ');
8060                    }
8061                    r.append(p.info.name);
8062                }
8063            }
8064            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8065                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8066                if (appOpPerms != null) {
8067                    appOpPerms.remove(pkg.packageName);
8068                }
8069            }
8070        }
8071        if (r != null) {
8072            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8073        }
8074
8075        N = pkg.requestedPermissions.size();
8076        r = null;
8077        for (i=0; i<N; i++) {
8078            String perm = pkg.requestedPermissions.get(i);
8079            BasePermission bp = mSettings.mPermissions.get(perm);
8080            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8081                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8082                if (appOpPerms != null) {
8083                    appOpPerms.remove(pkg.packageName);
8084                    if (appOpPerms.isEmpty()) {
8085                        mAppOpPermissionPackages.remove(perm);
8086                    }
8087                }
8088            }
8089        }
8090        if (r != null) {
8091            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8092        }
8093
8094        N = pkg.instrumentation.size();
8095        r = null;
8096        for (i=0; i<N; i++) {
8097            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8098            mInstrumentation.remove(a.getComponentName());
8099            if (DEBUG_REMOVE && chatty) {
8100                if (r == null) {
8101                    r = new StringBuilder(256);
8102                } else {
8103                    r.append(' ');
8104                }
8105                r.append(a.info.name);
8106            }
8107        }
8108        if (r != null) {
8109            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8110        }
8111
8112        r = null;
8113        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8114            // Only system apps can hold shared libraries.
8115            if (pkg.libraryNames != null) {
8116                for (i=0; i<pkg.libraryNames.size(); i++) {
8117                    String name = pkg.libraryNames.get(i);
8118                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8119                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8120                        mSharedLibraries.remove(name);
8121                        if (DEBUG_REMOVE && chatty) {
8122                            if (r == null) {
8123                                r = new StringBuilder(256);
8124                            } else {
8125                                r.append(' ');
8126                            }
8127                            r.append(name);
8128                        }
8129                    }
8130                }
8131            }
8132        }
8133        if (r != null) {
8134            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8135        }
8136    }
8137
8138    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8139        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8140            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8141                return true;
8142            }
8143        }
8144        return false;
8145    }
8146
8147    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8148    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8149    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8150
8151    private void updatePermissionsLPw(String changingPkg,
8152            PackageParser.Package pkgInfo, int flags) {
8153        // Make sure there are no dangling permission trees.
8154        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8155        while (it.hasNext()) {
8156            final BasePermission bp = it.next();
8157            if (bp.packageSetting == null) {
8158                // We may not yet have parsed the package, so just see if
8159                // we still know about its settings.
8160                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8161            }
8162            if (bp.packageSetting == null) {
8163                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8164                        + " from package " + bp.sourcePackage);
8165                it.remove();
8166            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8167                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8168                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8169                            + " from package " + bp.sourcePackage);
8170                    flags |= UPDATE_PERMISSIONS_ALL;
8171                    it.remove();
8172                }
8173            }
8174        }
8175
8176        // Make sure all dynamic permissions have been assigned to a package,
8177        // and make sure there are no dangling permissions.
8178        it = mSettings.mPermissions.values().iterator();
8179        while (it.hasNext()) {
8180            final BasePermission bp = it.next();
8181            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8182                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8183                        + bp.name + " pkg=" + bp.sourcePackage
8184                        + " info=" + bp.pendingInfo);
8185                if (bp.packageSetting == null && bp.pendingInfo != null) {
8186                    final BasePermission tree = findPermissionTreeLP(bp.name);
8187                    if (tree != null && tree.perm != null) {
8188                        bp.packageSetting = tree.packageSetting;
8189                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8190                                new PermissionInfo(bp.pendingInfo));
8191                        bp.perm.info.packageName = tree.perm.info.packageName;
8192                        bp.perm.info.name = bp.name;
8193                        bp.uid = tree.uid;
8194                    }
8195                }
8196            }
8197            if (bp.packageSetting == null) {
8198                // We may not yet have parsed the package, so just see if
8199                // we still know about its settings.
8200                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8201            }
8202            if (bp.packageSetting == null) {
8203                Slog.w(TAG, "Removing dangling permission: " + bp.name
8204                        + " from package " + bp.sourcePackage);
8205                it.remove();
8206            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8207                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8208                    Slog.i(TAG, "Removing old permission: " + bp.name
8209                            + " from package " + bp.sourcePackage);
8210                    flags |= UPDATE_PERMISSIONS_ALL;
8211                    it.remove();
8212                }
8213            }
8214        }
8215
8216        // Now update the permissions for all packages, in particular
8217        // replace the granted permissions of the system packages.
8218        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8219            for (PackageParser.Package pkg : mPackages.values()) {
8220                if (pkg != pkgInfo) {
8221                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8222                            changingPkg);
8223                }
8224            }
8225        }
8226
8227        if (pkgInfo != null) {
8228            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8229        }
8230    }
8231
8232    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8233            String packageOfInterest) {
8234        // IMPORTANT: There are two types of permissions: install and runtime.
8235        // Install time permissions are granted when the app is installed to
8236        // all device users and users added in the future. Runtime permissions
8237        // are granted at runtime explicitly to specific users. Normal and signature
8238        // protected permissions are install time permissions. Dangerous permissions
8239        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8240        // otherwise they are runtime permissions. This function does not manage
8241        // runtime permissions except for the case an app targeting Lollipop MR1
8242        // being upgraded to target a newer SDK, in which case dangerous permissions
8243        // are transformed from install time to runtime ones.
8244
8245        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8246        if (ps == null) {
8247            return;
8248        }
8249
8250        PermissionsState permissionsState = ps.getPermissionsState();
8251        PermissionsState origPermissions = permissionsState;
8252
8253        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8254
8255        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8256
8257        boolean changedInstallPermission = false;
8258
8259        if (replace) {
8260            ps.installPermissionsFixed = false;
8261            if (!ps.isSharedUser()) {
8262                origPermissions = new PermissionsState(permissionsState);
8263                permissionsState.reset();
8264            }
8265        }
8266
8267        permissionsState.setGlobalGids(mGlobalGids);
8268
8269        final int N = pkg.requestedPermissions.size();
8270        for (int i=0; i<N; i++) {
8271            final String name = pkg.requestedPermissions.get(i);
8272            final BasePermission bp = mSettings.mPermissions.get(name);
8273
8274            if (DEBUG_INSTALL) {
8275                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8276            }
8277
8278            if (bp == null || bp.packageSetting == null) {
8279                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8280                    Slog.w(TAG, "Unknown permission " + name
8281                            + " in package " + pkg.packageName);
8282                }
8283                continue;
8284            }
8285
8286            final String perm = bp.name;
8287            boolean allowedSig = false;
8288            int grant = GRANT_DENIED;
8289
8290            // Keep track of app op permissions.
8291            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8292                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8293                if (pkgs == null) {
8294                    pkgs = new ArraySet<>();
8295                    mAppOpPermissionPackages.put(bp.name, pkgs);
8296                }
8297                pkgs.add(pkg.packageName);
8298            }
8299
8300            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8301            switch (level) {
8302                case PermissionInfo.PROTECTION_NORMAL: {
8303                    // For all apps normal permissions are install time ones.
8304                    grant = GRANT_INSTALL;
8305                } break;
8306
8307                case PermissionInfo.PROTECTION_DANGEROUS: {
8308                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8309                        // For legacy apps dangerous permissions are install time ones.
8310                        grant = GRANT_INSTALL_LEGACY;
8311                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8312                        // For legacy apps that became modern, install becomes runtime.
8313                        grant = GRANT_UPGRADE;
8314                    } else {
8315                        // For modern apps keep runtime permissions unchanged.
8316                        grant = GRANT_RUNTIME;
8317                    }
8318                } break;
8319
8320                case PermissionInfo.PROTECTION_SIGNATURE: {
8321                    // For all apps signature permissions are install time ones.
8322                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8323                    if (allowedSig) {
8324                        grant = GRANT_INSTALL;
8325                    }
8326                } break;
8327            }
8328
8329            if (DEBUG_INSTALL) {
8330                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8331            }
8332
8333            if (grant != GRANT_DENIED) {
8334                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8335                    // If this is an existing, non-system package, then
8336                    // we can't add any new permissions to it.
8337                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8338                        // Except...  if this is a permission that was added
8339                        // to the platform (note: need to only do this when
8340                        // updating the platform).
8341                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8342                            grant = GRANT_DENIED;
8343                        }
8344                    }
8345                }
8346
8347                switch (grant) {
8348                    case GRANT_INSTALL: {
8349                        // Revoke this as runtime permission to handle the case of
8350                        // a runtime permission being downgraded to an install one.
8351                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8352                            if (origPermissions.getRuntimePermissionState(
8353                                    bp.name, userId) != null) {
8354                                // Revoke the runtime permission and clear the flags.
8355                                origPermissions.revokeRuntimePermission(bp, userId);
8356                                origPermissions.updatePermissionFlags(bp, userId,
8357                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8358                                // If we revoked a permission permission, we have to write.
8359                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8360                                        changedRuntimePermissionUserIds, userId);
8361                            }
8362                        }
8363                        // Grant an install permission.
8364                        if (permissionsState.grantInstallPermission(bp) !=
8365                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8366                            changedInstallPermission = true;
8367                        }
8368                    } break;
8369
8370                    case GRANT_INSTALL_LEGACY: {
8371                        // Grant an install permission.
8372                        if (permissionsState.grantInstallPermission(bp) !=
8373                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8374                            changedInstallPermission = true;
8375                        }
8376                    } break;
8377
8378                    case GRANT_RUNTIME: {
8379                        // Grant previously granted runtime permissions.
8380                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8381                            PermissionState permissionState = origPermissions
8382                                    .getRuntimePermissionState(bp.name, userId);
8383                            final int flags = permissionState != null
8384                                    ? permissionState.getFlags() : 0;
8385                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8386                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8387                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8388                                    // If we cannot put the permission as it was, we have to write.
8389                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8390                                            changedRuntimePermissionUserIds, userId);
8391                                }
8392                            }
8393                            // Propagate the permission flags.
8394                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8395                        }
8396                    } break;
8397
8398                    case GRANT_UPGRADE: {
8399                        // Grant runtime permissions for a previously held install permission.
8400                        PermissionState permissionState = origPermissions
8401                                .getInstallPermissionState(bp.name);
8402                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8403
8404                        if (origPermissions.revokeInstallPermission(bp)
8405                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8406                            // We will be transferring the permission flags, so clear them.
8407                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8408                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8409                            changedInstallPermission = true;
8410                        }
8411
8412                        // If the permission is not to be promoted to runtime we ignore it and
8413                        // also its other flags as they are not applicable to install permissions.
8414                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8415                            for (int userId : currentUserIds) {
8416                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8417                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8418                                    // Transfer the permission flags.
8419                                    permissionsState.updatePermissionFlags(bp, userId,
8420                                            flags, flags);
8421                                    // If we granted the permission, we have to write.
8422                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8423                                            changedRuntimePermissionUserIds, userId);
8424                                }
8425                            }
8426                        }
8427                    } break;
8428
8429                    default: {
8430                        if (packageOfInterest == null
8431                                || packageOfInterest.equals(pkg.packageName)) {
8432                            Slog.w(TAG, "Not granting permission " + perm
8433                                    + " to package " + pkg.packageName
8434                                    + " because it was previously installed without");
8435                        }
8436                    } break;
8437                }
8438            } else {
8439                if (permissionsState.revokeInstallPermission(bp) !=
8440                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8441                    // Also drop the permission flags.
8442                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8443                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8444                    changedInstallPermission = true;
8445                    Slog.i(TAG, "Un-granting permission " + perm
8446                            + " from package " + pkg.packageName
8447                            + " (protectionLevel=" + bp.protectionLevel
8448                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8449                            + ")");
8450                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8451                    // Don't print warning for app op permissions, since it is fine for them
8452                    // not to be granted, there is a UI for the user to decide.
8453                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8454                        Slog.w(TAG, "Not granting permission " + perm
8455                                + " to package " + pkg.packageName
8456                                + " (protectionLevel=" + bp.protectionLevel
8457                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8458                                + ")");
8459                    }
8460                }
8461            }
8462        }
8463
8464        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8465                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8466            // This is the first that we have heard about this package, so the
8467            // permissions we have now selected are fixed until explicitly
8468            // changed.
8469            ps.installPermissionsFixed = true;
8470        }
8471
8472        // Persist the runtime permissions state for users with changes.
8473        for (int userId : changedRuntimePermissionUserIds) {
8474            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8475        }
8476    }
8477
8478    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8479        boolean allowed = false;
8480        final int NP = PackageParser.NEW_PERMISSIONS.length;
8481        for (int ip=0; ip<NP; ip++) {
8482            final PackageParser.NewPermissionInfo npi
8483                    = PackageParser.NEW_PERMISSIONS[ip];
8484            if (npi.name.equals(perm)
8485                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8486                allowed = true;
8487                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8488                        + pkg.packageName);
8489                break;
8490            }
8491        }
8492        return allowed;
8493    }
8494
8495    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8496            BasePermission bp, PermissionsState origPermissions) {
8497        boolean allowed;
8498        allowed = (compareSignatures(
8499                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8500                        == PackageManager.SIGNATURE_MATCH)
8501                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8502                        == PackageManager.SIGNATURE_MATCH);
8503        if (!allowed && (bp.protectionLevel
8504                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8505            if (isSystemApp(pkg)) {
8506                // For updated system applications, a system permission
8507                // is granted only if it had been defined by the original application.
8508                if (pkg.isUpdatedSystemApp()) {
8509                    final PackageSetting sysPs = mSettings
8510                            .getDisabledSystemPkgLPr(pkg.packageName);
8511                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8512                        // If the original was granted this permission, we take
8513                        // that grant decision as read and propagate it to the
8514                        // update.
8515                        if (sysPs.isPrivileged()) {
8516                            allowed = true;
8517                        }
8518                    } else {
8519                        // The system apk may have been updated with an older
8520                        // version of the one on the data partition, but which
8521                        // granted a new system permission that it didn't have
8522                        // before.  In this case we do want to allow the app to
8523                        // now get the new permission if the ancestral apk is
8524                        // privileged to get it.
8525                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8526                            for (int j=0;
8527                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8528                                if (perm.equals(
8529                                        sysPs.pkg.requestedPermissions.get(j))) {
8530                                    allowed = true;
8531                                    break;
8532                                }
8533                            }
8534                        }
8535                    }
8536                } else {
8537                    allowed = isPrivilegedApp(pkg);
8538                }
8539            }
8540        }
8541        if (!allowed) {
8542            if (!allowed && (bp.protectionLevel
8543                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8544                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8545                // If this was a previously normal/dangerous permission that got moved
8546                // to a system permission as part of the runtime permission redesign, then
8547                // we still want to blindly grant it to old apps.
8548                allowed = true;
8549            }
8550            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8551                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8552                // If this permission is to be granted to the system installer and
8553                // this app is an installer, then it gets the permission.
8554                allowed = true;
8555            }
8556            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8557                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8558                // If this permission is to be granted to the system verifier and
8559                // this app is a verifier, then it gets the permission.
8560                allowed = true;
8561            }
8562            if (!allowed && (bp.protectionLevel
8563                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8564                    && isSystemApp(pkg)) {
8565                // Any pre-installed system app is allowed to get this permission.
8566                allowed = true;
8567            }
8568            if (!allowed && (bp.protectionLevel
8569                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8570                // For development permissions, a development permission
8571                // is granted only if it was already granted.
8572                allowed = origPermissions.hasInstallPermission(perm);
8573            }
8574        }
8575        return allowed;
8576    }
8577
8578    final class ActivityIntentResolver
8579            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8580        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8581                boolean defaultOnly, int userId) {
8582            if (!sUserManager.exists(userId)) return null;
8583            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8584            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8585        }
8586
8587        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8588                int userId) {
8589            if (!sUserManager.exists(userId)) return null;
8590            mFlags = flags;
8591            return super.queryIntent(intent, resolvedType,
8592                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8593        }
8594
8595        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8596                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8597            if (!sUserManager.exists(userId)) return null;
8598            if (packageActivities == null) {
8599                return null;
8600            }
8601            mFlags = flags;
8602            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8603            final int N = packageActivities.size();
8604            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8605                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8606
8607            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8608            for (int i = 0; i < N; ++i) {
8609                intentFilters = packageActivities.get(i).intents;
8610                if (intentFilters != null && intentFilters.size() > 0) {
8611                    PackageParser.ActivityIntentInfo[] array =
8612                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8613                    intentFilters.toArray(array);
8614                    listCut.add(array);
8615                }
8616            }
8617            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8618        }
8619
8620        public final void addActivity(PackageParser.Activity a, String type) {
8621            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8622            mActivities.put(a.getComponentName(), a);
8623            if (DEBUG_SHOW_INFO)
8624                Log.v(
8625                TAG, "  " + type + " " +
8626                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8627            if (DEBUG_SHOW_INFO)
8628                Log.v(TAG, "    Class=" + a.info.name);
8629            final int NI = a.intents.size();
8630            for (int j=0; j<NI; j++) {
8631                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8632                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8633                    intent.setPriority(0);
8634                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8635                            + a.className + " with priority > 0, forcing to 0");
8636                }
8637                if (DEBUG_SHOW_INFO) {
8638                    Log.v(TAG, "    IntentFilter:");
8639                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8640                }
8641                if (!intent.debugCheck()) {
8642                    Log.w(TAG, "==> For Activity " + a.info.name);
8643                }
8644                addFilter(intent);
8645            }
8646        }
8647
8648        public final void removeActivity(PackageParser.Activity a, String type) {
8649            mActivities.remove(a.getComponentName());
8650            if (DEBUG_SHOW_INFO) {
8651                Log.v(TAG, "  " + type + " "
8652                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8653                                : a.info.name) + ":");
8654                Log.v(TAG, "    Class=" + a.info.name);
8655            }
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 (DEBUG_SHOW_INFO) {
8660                    Log.v(TAG, "    IntentFilter:");
8661                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8662                }
8663                removeFilter(intent);
8664            }
8665        }
8666
8667        @Override
8668        protected boolean allowFilterResult(
8669                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8670            ActivityInfo filterAi = filter.activity.info;
8671            for (int i=dest.size()-1; i>=0; i--) {
8672                ActivityInfo destAi = dest.get(i).activityInfo;
8673                if (destAi.name == filterAi.name
8674                        && destAi.packageName == filterAi.packageName) {
8675                    return false;
8676                }
8677            }
8678            return true;
8679        }
8680
8681        @Override
8682        protected ActivityIntentInfo[] newArray(int size) {
8683            return new ActivityIntentInfo[size];
8684        }
8685
8686        @Override
8687        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8688            if (!sUserManager.exists(userId)) return true;
8689            PackageParser.Package p = filter.activity.owner;
8690            if (p != null) {
8691                PackageSetting ps = (PackageSetting)p.mExtras;
8692                if (ps != null) {
8693                    // System apps are never considered stopped for purposes of
8694                    // filtering, because there may be no way for the user to
8695                    // actually re-launch them.
8696                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8697                            && ps.getStopped(userId);
8698                }
8699            }
8700            return false;
8701        }
8702
8703        @Override
8704        protected boolean isPackageForFilter(String packageName,
8705                PackageParser.ActivityIntentInfo info) {
8706            return packageName.equals(info.activity.owner.packageName);
8707        }
8708
8709        @Override
8710        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8711                int match, int userId) {
8712            if (!sUserManager.exists(userId)) return null;
8713            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8714                return null;
8715            }
8716            final PackageParser.Activity activity = info.activity;
8717            if (mSafeMode && (activity.info.applicationInfo.flags
8718                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8719                return null;
8720            }
8721            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8722            if (ps == null) {
8723                return null;
8724            }
8725            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8726                    ps.readUserState(userId), userId);
8727            if (ai == null) {
8728                return null;
8729            }
8730            final ResolveInfo res = new ResolveInfo();
8731            res.activityInfo = ai;
8732            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8733                res.filter = info;
8734            }
8735            if (info != null) {
8736                res.handleAllWebDataURI = info.handleAllWebDataURI();
8737            }
8738            res.priority = info.getPriority();
8739            res.preferredOrder = activity.owner.mPreferredOrder;
8740            //System.out.println("Result: " + res.activityInfo.className +
8741            //                   " = " + res.priority);
8742            res.match = match;
8743            res.isDefault = info.hasDefault;
8744            res.labelRes = info.labelRes;
8745            res.nonLocalizedLabel = info.nonLocalizedLabel;
8746            if (userNeedsBadging(userId)) {
8747                res.noResourceId = true;
8748            } else {
8749                res.icon = info.icon;
8750            }
8751            res.iconResourceId = info.icon;
8752            res.system = res.activityInfo.applicationInfo.isSystemApp();
8753            return res;
8754        }
8755
8756        @Override
8757        protected void sortResults(List<ResolveInfo> results) {
8758            Collections.sort(results, mResolvePrioritySorter);
8759        }
8760
8761        @Override
8762        protected void dumpFilter(PrintWriter out, String prefix,
8763                PackageParser.ActivityIntentInfo filter) {
8764            out.print(prefix); out.print(
8765                    Integer.toHexString(System.identityHashCode(filter.activity)));
8766                    out.print(' ');
8767                    filter.activity.printComponentShortName(out);
8768                    out.print(" filter ");
8769                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8770        }
8771
8772        @Override
8773        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8774            return filter.activity;
8775        }
8776
8777        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8778            PackageParser.Activity activity = (PackageParser.Activity)label;
8779            out.print(prefix); out.print(
8780                    Integer.toHexString(System.identityHashCode(activity)));
8781                    out.print(' ');
8782                    activity.printComponentShortName(out);
8783            if (count > 1) {
8784                out.print(" ("); out.print(count); out.print(" filters)");
8785            }
8786            out.println();
8787        }
8788
8789//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8790//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8791//            final List<ResolveInfo> retList = Lists.newArrayList();
8792//            while (i.hasNext()) {
8793//                final ResolveInfo resolveInfo = i.next();
8794//                if (isEnabledLP(resolveInfo.activityInfo)) {
8795//                    retList.add(resolveInfo);
8796//                }
8797//            }
8798//            return retList;
8799//        }
8800
8801        // Keys are String (activity class name), values are Activity.
8802        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8803                = new ArrayMap<ComponentName, PackageParser.Activity>();
8804        private int mFlags;
8805    }
8806
8807    private final class ServiceIntentResolver
8808            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8809        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8810                boolean defaultOnly, int userId) {
8811            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8812            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8813        }
8814
8815        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8816                int userId) {
8817            if (!sUserManager.exists(userId)) return null;
8818            mFlags = flags;
8819            return super.queryIntent(intent, resolvedType,
8820                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8821        }
8822
8823        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8824                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8825            if (!sUserManager.exists(userId)) return null;
8826            if (packageServices == null) {
8827                return null;
8828            }
8829            mFlags = flags;
8830            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8831            final int N = packageServices.size();
8832            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8833                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8834
8835            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8836            for (int i = 0; i < N; ++i) {
8837                intentFilters = packageServices.get(i).intents;
8838                if (intentFilters != null && intentFilters.size() > 0) {
8839                    PackageParser.ServiceIntentInfo[] array =
8840                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8841                    intentFilters.toArray(array);
8842                    listCut.add(array);
8843                }
8844            }
8845            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8846        }
8847
8848        public final void addService(PackageParser.Service s) {
8849            mServices.put(s.getComponentName(), s);
8850            if (DEBUG_SHOW_INFO) {
8851                Log.v(TAG, "  "
8852                        + (s.info.nonLocalizedLabel != null
8853                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8854                Log.v(TAG, "    Class=" + s.info.name);
8855            }
8856            final int NI = s.intents.size();
8857            int j;
8858            for (j=0; j<NI; j++) {
8859                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8860                if (DEBUG_SHOW_INFO) {
8861                    Log.v(TAG, "    IntentFilter:");
8862                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8863                }
8864                if (!intent.debugCheck()) {
8865                    Log.w(TAG, "==> For Service " + s.info.name);
8866                }
8867                addFilter(intent);
8868            }
8869        }
8870
8871        public final void removeService(PackageParser.Service s) {
8872            mServices.remove(s.getComponentName());
8873            if (DEBUG_SHOW_INFO) {
8874                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8875                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8876                Log.v(TAG, "    Class=" + s.info.name);
8877            }
8878            final int NI = s.intents.size();
8879            int j;
8880            for (j=0; j<NI; j++) {
8881                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8882                if (DEBUG_SHOW_INFO) {
8883                    Log.v(TAG, "    IntentFilter:");
8884                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8885                }
8886                removeFilter(intent);
8887            }
8888        }
8889
8890        @Override
8891        protected boolean allowFilterResult(
8892                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8893            ServiceInfo filterSi = filter.service.info;
8894            for (int i=dest.size()-1; i>=0; i--) {
8895                ServiceInfo destAi = dest.get(i).serviceInfo;
8896                if (destAi.name == filterSi.name
8897                        && destAi.packageName == filterSi.packageName) {
8898                    return false;
8899                }
8900            }
8901            return true;
8902        }
8903
8904        @Override
8905        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8906            return new PackageParser.ServiceIntentInfo[size];
8907        }
8908
8909        @Override
8910        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8911            if (!sUserManager.exists(userId)) return true;
8912            PackageParser.Package p = filter.service.owner;
8913            if (p != null) {
8914                PackageSetting ps = (PackageSetting)p.mExtras;
8915                if (ps != null) {
8916                    // System apps are never considered stopped for purposes of
8917                    // filtering, because there may be no way for the user to
8918                    // actually re-launch them.
8919                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8920                            && ps.getStopped(userId);
8921                }
8922            }
8923            return false;
8924        }
8925
8926        @Override
8927        protected boolean isPackageForFilter(String packageName,
8928                PackageParser.ServiceIntentInfo info) {
8929            return packageName.equals(info.service.owner.packageName);
8930        }
8931
8932        @Override
8933        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8934                int match, int userId) {
8935            if (!sUserManager.exists(userId)) return null;
8936            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8937            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8938                return null;
8939            }
8940            final PackageParser.Service service = info.service;
8941            if (mSafeMode && (service.info.applicationInfo.flags
8942                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8943                return null;
8944            }
8945            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8946            if (ps == null) {
8947                return null;
8948            }
8949            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8950                    ps.readUserState(userId), userId);
8951            if (si == null) {
8952                return null;
8953            }
8954            final ResolveInfo res = new ResolveInfo();
8955            res.serviceInfo = si;
8956            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8957                res.filter = filter;
8958            }
8959            res.priority = info.getPriority();
8960            res.preferredOrder = service.owner.mPreferredOrder;
8961            res.match = match;
8962            res.isDefault = info.hasDefault;
8963            res.labelRes = info.labelRes;
8964            res.nonLocalizedLabel = info.nonLocalizedLabel;
8965            res.icon = info.icon;
8966            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8967            return res;
8968        }
8969
8970        @Override
8971        protected void sortResults(List<ResolveInfo> results) {
8972            Collections.sort(results, mResolvePrioritySorter);
8973        }
8974
8975        @Override
8976        protected void dumpFilter(PrintWriter out, String prefix,
8977                PackageParser.ServiceIntentInfo filter) {
8978            out.print(prefix); out.print(
8979                    Integer.toHexString(System.identityHashCode(filter.service)));
8980                    out.print(' ');
8981                    filter.service.printComponentShortName(out);
8982                    out.print(" filter ");
8983                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8984        }
8985
8986        @Override
8987        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8988            return filter.service;
8989        }
8990
8991        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8992            PackageParser.Service service = (PackageParser.Service)label;
8993            out.print(prefix); out.print(
8994                    Integer.toHexString(System.identityHashCode(service)));
8995                    out.print(' ');
8996                    service.printComponentShortName(out);
8997            if (count > 1) {
8998                out.print(" ("); out.print(count); out.print(" filters)");
8999            }
9000            out.println();
9001        }
9002
9003//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9004//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9005//            final List<ResolveInfo> retList = Lists.newArrayList();
9006//            while (i.hasNext()) {
9007//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9008//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9009//                    retList.add(resolveInfo);
9010//                }
9011//            }
9012//            return retList;
9013//        }
9014
9015        // Keys are String (activity class name), values are Activity.
9016        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9017                = new ArrayMap<ComponentName, PackageParser.Service>();
9018        private int mFlags;
9019    };
9020
9021    private final class ProviderIntentResolver
9022            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9023        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9024                boolean defaultOnly, int userId) {
9025            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9026            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9027        }
9028
9029        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9030                int userId) {
9031            if (!sUserManager.exists(userId))
9032                return null;
9033            mFlags = flags;
9034            return super.queryIntent(intent, resolvedType,
9035                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9036        }
9037
9038        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9039                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9040            if (!sUserManager.exists(userId))
9041                return null;
9042            if (packageProviders == null) {
9043                return null;
9044            }
9045            mFlags = flags;
9046            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9047            final int N = packageProviders.size();
9048            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9049                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9050
9051            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9052            for (int i = 0; i < N; ++i) {
9053                intentFilters = packageProviders.get(i).intents;
9054                if (intentFilters != null && intentFilters.size() > 0) {
9055                    PackageParser.ProviderIntentInfo[] array =
9056                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9057                    intentFilters.toArray(array);
9058                    listCut.add(array);
9059                }
9060            }
9061            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9062        }
9063
9064        public final void addProvider(PackageParser.Provider p) {
9065            if (mProviders.containsKey(p.getComponentName())) {
9066                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9067                return;
9068            }
9069
9070            mProviders.put(p.getComponentName(), p);
9071            if (DEBUG_SHOW_INFO) {
9072                Log.v(TAG, "  "
9073                        + (p.info.nonLocalizedLabel != null
9074                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9075                Log.v(TAG, "    Class=" + p.info.name);
9076            }
9077            final int NI = p.intents.size();
9078            int j;
9079            for (j = 0; j < NI; j++) {
9080                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9081                if (DEBUG_SHOW_INFO) {
9082                    Log.v(TAG, "    IntentFilter:");
9083                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9084                }
9085                if (!intent.debugCheck()) {
9086                    Log.w(TAG, "==> For Provider " + p.info.name);
9087                }
9088                addFilter(intent);
9089            }
9090        }
9091
9092        public final void removeProvider(PackageParser.Provider p) {
9093            mProviders.remove(p.getComponentName());
9094            if (DEBUG_SHOW_INFO) {
9095                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9096                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9097                Log.v(TAG, "    Class=" + p.info.name);
9098            }
9099            final int NI = p.intents.size();
9100            int j;
9101            for (j = 0; j < NI; j++) {
9102                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9103                if (DEBUG_SHOW_INFO) {
9104                    Log.v(TAG, "    IntentFilter:");
9105                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9106                }
9107                removeFilter(intent);
9108            }
9109        }
9110
9111        @Override
9112        protected boolean allowFilterResult(
9113                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9114            ProviderInfo filterPi = filter.provider.info;
9115            for (int i = dest.size() - 1; i >= 0; i--) {
9116                ProviderInfo destPi = dest.get(i).providerInfo;
9117                if (destPi.name == filterPi.name
9118                        && destPi.packageName == filterPi.packageName) {
9119                    return false;
9120                }
9121            }
9122            return true;
9123        }
9124
9125        @Override
9126        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9127            return new PackageParser.ProviderIntentInfo[size];
9128        }
9129
9130        @Override
9131        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9132            if (!sUserManager.exists(userId))
9133                return true;
9134            PackageParser.Package p = filter.provider.owner;
9135            if (p != null) {
9136                PackageSetting ps = (PackageSetting) p.mExtras;
9137                if (ps != null) {
9138                    // System apps are never considered stopped for purposes of
9139                    // filtering, because there may be no way for the user to
9140                    // actually re-launch them.
9141                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9142                            && ps.getStopped(userId);
9143                }
9144            }
9145            return false;
9146        }
9147
9148        @Override
9149        protected boolean isPackageForFilter(String packageName,
9150                PackageParser.ProviderIntentInfo info) {
9151            return packageName.equals(info.provider.owner.packageName);
9152        }
9153
9154        @Override
9155        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9156                int match, int userId) {
9157            if (!sUserManager.exists(userId))
9158                return null;
9159            final PackageParser.ProviderIntentInfo info = filter;
9160            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9161                return null;
9162            }
9163            final PackageParser.Provider provider = info.provider;
9164            if (mSafeMode && (provider.info.applicationInfo.flags
9165                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9166                return null;
9167            }
9168            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9169            if (ps == null) {
9170                return null;
9171            }
9172            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9173                    ps.readUserState(userId), userId);
9174            if (pi == null) {
9175                return null;
9176            }
9177            final ResolveInfo res = new ResolveInfo();
9178            res.providerInfo = pi;
9179            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9180                res.filter = filter;
9181            }
9182            res.priority = info.getPriority();
9183            res.preferredOrder = provider.owner.mPreferredOrder;
9184            res.match = match;
9185            res.isDefault = info.hasDefault;
9186            res.labelRes = info.labelRes;
9187            res.nonLocalizedLabel = info.nonLocalizedLabel;
9188            res.icon = info.icon;
9189            res.system = res.providerInfo.applicationInfo.isSystemApp();
9190            return res;
9191        }
9192
9193        @Override
9194        protected void sortResults(List<ResolveInfo> results) {
9195            Collections.sort(results, mResolvePrioritySorter);
9196        }
9197
9198        @Override
9199        protected void dumpFilter(PrintWriter out, String prefix,
9200                PackageParser.ProviderIntentInfo filter) {
9201            out.print(prefix);
9202            out.print(
9203                    Integer.toHexString(System.identityHashCode(filter.provider)));
9204            out.print(' ');
9205            filter.provider.printComponentShortName(out);
9206            out.print(" filter ");
9207            out.println(Integer.toHexString(System.identityHashCode(filter)));
9208        }
9209
9210        @Override
9211        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9212            return filter.provider;
9213        }
9214
9215        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9216            PackageParser.Provider provider = (PackageParser.Provider)label;
9217            out.print(prefix); out.print(
9218                    Integer.toHexString(System.identityHashCode(provider)));
9219                    out.print(' ');
9220                    provider.printComponentShortName(out);
9221            if (count > 1) {
9222                out.print(" ("); out.print(count); out.print(" filters)");
9223            }
9224            out.println();
9225        }
9226
9227        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9228                = new ArrayMap<ComponentName, PackageParser.Provider>();
9229        private int mFlags;
9230    };
9231
9232    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9233            new Comparator<ResolveInfo>() {
9234        public int compare(ResolveInfo r1, ResolveInfo r2) {
9235            int v1 = r1.priority;
9236            int v2 = r2.priority;
9237            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9238            if (v1 != v2) {
9239                return (v1 > v2) ? -1 : 1;
9240            }
9241            v1 = r1.preferredOrder;
9242            v2 = r2.preferredOrder;
9243            if (v1 != v2) {
9244                return (v1 > v2) ? -1 : 1;
9245            }
9246            if (r1.isDefault != r2.isDefault) {
9247                return r1.isDefault ? -1 : 1;
9248            }
9249            v1 = r1.match;
9250            v2 = r2.match;
9251            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9252            if (v1 != v2) {
9253                return (v1 > v2) ? -1 : 1;
9254            }
9255            if (r1.system != r2.system) {
9256                return r1.system ? -1 : 1;
9257            }
9258            return 0;
9259        }
9260    };
9261
9262    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9263            new Comparator<ProviderInfo>() {
9264        public int compare(ProviderInfo p1, ProviderInfo p2) {
9265            final int v1 = p1.initOrder;
9266            final int v2 = p2.initOrder;
9267            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9268        }
9269    };
9270
9271    final void sendPackageBroadcast(final String action, final String pkg,
9272            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9273            final int[] userIds) {
9274        mHandler.post(new Runnable() {
9275            @Override
9276            public void run() {
9277                try {
9278                    final IActivityManager am = ActivityManagerNative.getDefault();
9279                    if (am == null) return;
9280                    final int[] resolvedUserIds;
9281                    if (userIds == null) {
9282                        resolvedUserIds = am.getRunningUserIds();
9283                    } else {
9284                        resolvedUserIds = userIds;
9285                    }
9286                    for (int id : resolvedUserIds) {
9287                        final Intent intent = new Intent(action,
9288                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9289                        if (extras != null) {
9290                            intent.putExtras(extras);
9291                        }
9292                        if (targetPkg != null) {
9293                            intent.setPackage(targetPkg);
9294                        }
9295                        // Modify the UID when posting to other users
9296                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9297                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9298                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9299                            intent.putExtra(Intent.EXTRA_UID, uid);
9300                        }
9301                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9302                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9303                        if (DEBUG_BROADCASTS) {
9304                            RuntimeException here = new RuntimeException("here");
9305                            here.fillInStackTrace();
9306                            Slog.d(TAG, "Sending to user " + id + ": "
9307                                    + intent.toShortString(false, true, false, false)
9308                                    + " " + intent.getExtras(), here);
9309                        }
9310                        am.broadcastIntent(null, intent, null, finishedReceiver,
9311                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9312                                null, finishedReceiver != null, false, id);
9313                    }
9314                } catch (RemoteException ex) {
9315                }
9316            }
9317        });
9318    }
9319
9320    /**
9321     * Check if the external storage media is available. This is true if there
9322     * is a mounted external storage medium or if the external storage is
9323     * emulated.
9324     */
9325    private boolean isExternalMediaAvailable() {
9326        return mMediaMounted || Environment.isExternalStorageEmulated();
9327    }
9328
9329    @Override
9330    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9331        // writer
9332        synchronized (mPackages) {
9333            if (!isExternalMediaAvailable()) {
9334                // If the external storage is no longer mounted at this point,
9335                // the caller may not have been able to delete all of this
9336                // packages files and can not delete any more.  Bail.
9337                return null;
9338            }
9339            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9340            if (lastPackage != null) {
9341                pkgs.remove(lastPackage);
9342            }
9343            if (pkgs.size() > 0) {
9344                return pkgs.get(0);
9345            }
9346        }
9347        return null;
9348    }
9349
9350    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9351        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9352                userId, andCode ? 1 : 0, packageName);
9353        if (mSystemReady) {
9354            msg.sendToTarget();
9355        } else {
9356            if (mPostSystemReadyMessages == null) {
9357                mPostSystemReadyMessages = new ArrayList<>();
9358            }
9359            mPostSystemReadyMessages.add(msg);
9360        }
9361    }
9362
9363    void startCleaningPackages() {
9364        // reader
9365        synchronized (mPackages) {
9366            if (!isExternalMediaAvailable()) {
9367                return;
9368            }
9369            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9370                return;
9371            }
9372        }
9373        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9374        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9375        IActivityManager am = ActivityManagerNative.getDefault();
9376        if (am != null) {
9377            try {
9378                am.startService(null, intent, null, mContext.getOpPackageName(),
9379                        UserHandle.USER_OWNER);
9380            } catch (RemoteException e) {
9381            }
9382        }
9383    }
9384
9385    @Override
9386    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9387            int installFlags, String installerPackageName, VerificationParams verificationParams,
9388            String packageAbiOverride) {
9389        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9390                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9391    }
9392
9393    @Override
9394    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9395            int installFlags, String installerPackageName, VerificationParams verificationParams,
9396            String packageAbiOverride, int userId) {
9397        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9398
9399        final int callingUid = Binder.getCallingUid();
9400        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9401
9402        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9403            try {
9404                if (observer != null) {
9405                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9406                }
9407            } catch (RemoteException re) {
9408            }
9409            return;
9410        }
9411
9412        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9413            installFlags |= PackageManager.INSTALL_FROM_ADB;
9414
9415        } else {
9416            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9417            // about installerPackageName.
9418
9419            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9420            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9421        }
9422
9423        UserHandle user;
9424        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9425            user = UserHandle.ALL;
9426        } else {
9427            user = new UserHandle(userId);
9428        }
9429
9430        // Only system components can circumvent runtime permissions when installing.
9431        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9432                && mContext.checkCallingOrSelfPermission(Manifest.permission
9433                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9434            throw new SecurityException("You need the "
9435                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9436                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9437        }
9438
9439        verificationParams.setInstallerUid(callingUid);
9440
9441        final File originFile = new File(originPath);
9442        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9443
9444        final Message msg = mHandler.obtainMessage(INIT_COPY);
9445        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9446                null, verificationParams, user, packageAbiOverride);
9447        mHandler.sendMessage(msg);
9448    }
9449
9450    void installStage(String packageName, File stagedDir, String stagedCid,
9451            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9452            String installerPackageName, int installerUid, UserHandle user) {
9453        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9454                params.referrerUri, installerUid, null);
9455        verifParams.setInstallerUid(installerUid);
9456
9457        final OriginInfo origin;
9458        if (stagedDir != null) {
9459            origin = OriginInfo.fromStagedFile(stagedDir);
9460        } else {
9461            origin = OriginInfo.fromStagedContainer(stagedCid);
9462        }
9463
9464        final Message msg = mHandler.obtainMessage(INIT_COPY);
9465        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9466                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9467        mHandler.sendMessage(msg);
9468    }
9469
9470    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9471        Bundle extras = new Bundle(1);
9472        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9473
9474        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9475                packageName, extras, null, null, new int[] {userId});
9476        try {
9477            IActivityManager am = ActivityManagerNative.getDefault();
9478            final boolean isSystem =
9479                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9480            if (isSystem && am.isUserRunning(userId, false)) {
9481                // The just-installed/enabled app is bundled on the system, so presumed
9482                // to be able to run automatically without needing an explicit launch.
9483                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9484                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9485                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9486                        .setPackage(packageName);
9487                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9488                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9489            }
9490        } catch (RemoteException e) {
9491            // shouldn't happen
9492            Slog.w(TAG, "Unable to bootstrap installed package", e);
9493        }
9494    }
9495
9496    @Override
9497    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9498            int userId) {
9499        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9500        PackageSetting pkgSetting;
9501        final int uid = Binder.getCallingUid();
9502        enforceCrossUserPermission(uid, userId, true, true,
9503                "setApplicationHiddenSetting for user " + userId);
9504
9505        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9506            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9507            return false;
9508        }
9509
9510        long callingId = Binder.clearCallingIdentity();
9511        try {
9512            boolean sendAdded = false;
9513            boolean sendRemoved = false;
9514            // writer
9515            synchronized (mPackages) {
9516                pkgSetting = mSettings.mPackages.get(packageName);
9517                if (pkgSetting == null) {
9518                    return false;
9519                }
9520                if (pkgSetting.getHidden(userId) != hidden) {
9521                    pkgSetting.setHidden(hidden, userId);
9522                    mSettings.writePackageRestrictionsLPr(userId);
9523                    if (hidden) {
9524                        sendRemoved = true;
9525                    } else {
9526                        sendAdded = true;
9527                    }
9528                }
9529            }
9530            if (sendAdded) {
9531                sendPackageAddedForUser(packageName, pkgSetting, userId);
9532                return true;
9533            }
9534            if (sendRemoved) {
9535                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9536                        "hiding pkg");
9537                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9538            }
9539        } finally {
9540            Binder.restoreCallingIdentity(callingId);
9541        }
9542        return false;
9543    }
9544
9545    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9546            int userId) {
9547        final PackageRemovedInfo info = new PackageRemovedInfo();
9548        info.removedPackage = packageName;
9549        info.removedUsers = new int[] {userId};
9550        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9551        info.sendBroadcast(false, false, false);
9552    }
9553
9554    /**
9555     * Returns true if application is not found or there was an error. Otherwise it returns
9556     * the hidden state of the package for the given user.
9557     */
9558    @Override
9559    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9560        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9561        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9562                false, "getApplicationHidden for user " + userId);
9563        PackageSetting pkgSetting;
9564        long callingId = Binder.clearCallingIdentity();
9565        try {
9566            // writer
9567            synchronized (mPackages) {
9568                pkgSetting = mSettings.mPackages.get(packageName);
9569                if (pkgSetting == null) {
9570                    return true;
9571                }
9572                return pkgSetting.getHidden(userId);
9573            }
9574        } finally {
9575            Binder.restoreCallingIdentity(callingId);
9576        }
9577    }
9578
9579    /**
9580     * @hide
9581     */
9582    @Override
9583    public int installExistingPackageAsUser(String packageName, int userId) {
9584        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9585                null);
9586        PackageSetting pkgSetting;
9587        final int uid = Binder.getCallingUid();
9588        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9589                + userId);
9590        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9591            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9592        }
9593
9594        long callingId = Binder.clearCallingIdentity();
9595        try {
9596            boolean sendAdded = false;
9597
9598            // writer
9599            synchronized (mPackages) {
9600                pkgSetting = mSettings.mPackages.get(packageName);
9601                if (pkgSetting == null) {
9602                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9603                }
9604                if (!pkgSetting.getInstalled(userId)) {
9605                    pkgSetting.setInstalled(true, userId);
9606                    pkgSetting.setHidden(false, userId);
9607                    mSettings.writePackageRestrictionsLPr(userId);
9608                    sendAdded = true;
9609                }
9610            }
9611
9612            if (sendAdded) {
9613                sendPackageAddedForUser(packageName, pkgSetting, userId);
9614            }
9615        } finally {
9616            Binder.restoreCallingIdentity(callingId);
9617        }
9618
9619        return PackageManager.INSTALL_SUCCEEDED;
9620    }
9621
9622    boolean isUserRestricted(int userId, String restrictionKey) {
9623        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9624        if (restrictions.getBoolean(restrictionKey, false)) {
9625            Log.w(TAG, "User is restricted: " + restrictionKey);
9626            return true;
9627        }
9628        return false;
9629    }
9630
9631    @Override
9632    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9633        mContext.enforceCallingOrSelfPermission(
9634                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9635                "Only package verification agents can verify applications");
9636
9637        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9638        final PackageVerificationResponse response = new PackageVerificationResponse(
9639                verificationCode, Binder.getCallingUid());
9640        msg.arg1 = id;
9641        msg.obj = response;
9642        mHandler.sendMessage(msg);
9643    }
9644
9645    @Override
9646    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9647            long millisecondsToDelay) {
9648        mContext.enforceCallingOrSelfPermission(
9649                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9650                "Only package verification agents can extend verification timeouts");
9651
9652        final PackageVerificationState state = mPendingVerification.get(id);
9653        final PackageVerificationResponse response = new PackageVerificationResponse(
9654                verificationCodeAtTimeout, Binder.getCallingUid());
9655
9656        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9657            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9658        }
9659        if (millisecondsToDelay < 0) {
9660            millisecondsToDelay = 0;
9661        }
9662        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9663                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9664            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9665        }
9666
9667        if ((state != null) && !state.timeoutExtended()) {
9668            state.extendTimeout();
9669
9670            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9671            msg.arg1 = id;
9672            msg.obj = response;
9673            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9674        }
9675    }
9676
9677    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9678            int verificationCode, UserHandle user) {
9679        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9680        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9681        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9682        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9683        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9684
9685        mContext.sendBroadcastAsUser(intent, user,
9686                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9687    }
9688
9689    private ComponentName matchComponentForVerifier(String packageName,
9690            List<ResolveInfo> receivers) {
9691        ActivityInfo targetReceiver = null;
9692
9693        final int NR = receivers.size();
9694        for (int i = 0; i < NR; i++) {
9695            final ResolveInfo info = receivers.get(i);
9696            if (info.activityInfo == null) {
9697                continue;
9698            }
9699
9700            if (packageName.equals(info.activityInfo.packageName)) {
9701                targetReceiver = info.activityInfo;
9702                break;
9703            }
9704        }
9705
9706        if (targetReceiver == null) {
9707            return null;
9708        }
9709
9710        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9711    }
9712
9713    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9714            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9715        if (pkgInfo.verifiers.length == 0) {
9716            return null;
9717        }
9718
9719        final int N = pkgInfo.verifiers.length;
9720        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9721        for (int i = 0; i < N; i++) {
9722            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9723
9724            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9725                    receivers);
9726            if (comp == null) {
9727                continue;
9728            }
9729
9730            final int verifierUid = getUidForVerifier(verifierInfo);
9731            if (verifierUid == -1) {
9732                continue;
9733            }
9734
9735            if (DEBUG_VERIFY) {
9736                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9737                        + " with the correct signature");
9738            }
9739            sufficientVerifiers.add(comp);
9740            verificationState.addSufficientVerifier(verifierUid);
9741        }
9742
9743        return sufficientVerifiers;
9744    }
9745
9746    private int getUidForVerifier(VerifierInfo verifierInfo) {
9747        synchronized (mPackages) {
9748            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9749            if (pkg == null) {
9750                return -1;
9751            } else if (pkg.mSignatures.length != 1) {
9752                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9753                        + " has more than one signature; ignoring");
9754                return -1;
9755            }
9756
9757            /*
9758             * If the public key of the package's signature does not match
9759             * our expected public key, then this is a different package and
9760             * we should skip.
9761             */
9762
9763            final byte[] expectedPublicKey;
9764            try {
9765                final Signature verifierSig = pkg.mSignatures[0];
9766                final PublicKey publicKey = verifierSig.getPublicKey();
9767                expectedPublicKey = publicKey.getEncoded();
9768            } catch (CertificateException e) {
9769                return -1;
9770            }
9771
9772            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9773
9774            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9775                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9776                        + " does not have the expected public key; ignoring");
9777                return -1;
9778            }
9779
9780            return pkg.applicationInfo.uid;
9781        }
9782    }
9783
9784    @Override
9785    public void finishPackageInstall(int token) {
9786        enforceSystemOrRoot("Only the system is allowed to finish installs");
9787
9788        if (DEBUG_INSTALL) {
9789            Slog.v(TAG, "BM finishing package install for " + token);
9790        }
9791
9792        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9793        mHandler.sendMessage(msg);
9794    }
9795
9796    /**
9797     * Get the verification agent timeout.
9798     *
9799     * @return verification timeout in milliseconds
9800     */
9801    private long getVerificationTimeout() {
9802        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9803                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9804                DEFAULT_VERIFICATION_TIMEOUT);
9805    }
9806
9807    /**
9808     * Get the default verification agent response code.
9809     *
9810     * @return default verification response code
9811     */
9812    private int getDefaultVerificationResponse() {
9813        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9814                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9815                DEFAULT_VERIFICATION_RESPONSE);
9816    }
9817
9818    /**
9819     * Check whether or not package verification has been enabled.
9820     *
9821     * @return true if verification should be performed
9822     */
9823    private boolean isVerificationEnabled(int userId, int installFlags) {
9824        if (!DEFAULT_VERIFY_ENABLE) {
9825            return false;
9826        }
9827
9828        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9829
9830        // Check if installing from ADB
9831        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9832            // Do not run verification in a test harness environment
9833            if (ActivityManager.isRunningInTestHarness()) {
9834                return false;
9835            }
9836            if (ensureVerifyAppsEnabled) {
9837                return true;
9838            }
9839            // Check if the developer does not want package verification for ADB installs
9840            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9841                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9842                return false;
9843            }
9844        }
9845
9846        if (ensureVerifyAppsEnabled) {
9847            return true;
9848        }
9849
9850        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9851                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9852    }
9853
9854    @Override
9855    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9856            throws RemoteException {
9857        mContext.enforceCallingOrSelfPermission(
9858                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9859                "Only intentfilter verification agents can verify applications");
9860
9861        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9862        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9863                Binder.getCallingUid(), verificationCode, failedDomains);
9864        msg.arg1 = id;
9865        msg.obj = response;
9866        mHandler.sendMessage(msg);
9867    }
9868
9869    @Override
9870    public int getIntentVerificationStatus(String packageName, int userId) {
9871        synchronized (mPackages) {
9872            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9873        }
9874    }
9875
9876    @Override
9877    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9878        mContext.enforceCallingOrSelfPermission(
9879                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9880
9881        boolean result = false;
9882        synchronized (mPackages) {
9883            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9884        }
9885        if (result) {
9886            scheduleWritePackageRestrictionsLocked(userId);
9887        }
9888        return result;
9889    }
9890
9891    @Override
9892    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9893        synchronized (mPackages) {
9894            return mSettings.getIntentFilterVerificationsLPr(packageName);
9895        }
9896    }
9897
9898    @Override
9899    public List<IntentFilter> getAllIntentFilters(String packageName) {
9900        if (TextUtils.isEmpty(packageName)) {
9901            return Collections.<IntentFilter>emptyList();
9902        }
9903        synchronized (mPackages) {
9904            PackageParser.Package pkg = mPackages.get(packageName);
9905            if (pkg == null || pkg.activities == null) {
9906                return Collections.<IntentFilter>emptyList();
9907            }
9908            final int count = pkg.activities.size();
9909            ArrayList<IntentFilter> result = new ArrayList<>();
9910            for (int n=0; n<count; n++) {
9911                PackageParser.Activity activity = pkg.activities.get(n);
9912                if (activity.intents != null || activity.intents.size() > 0) {
9913                    result.addAll(activity.intents);
9914                }
9915            }
9916            return result;
9917        }
9918    }
9919
9920    @Override
9921    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9922        mContext.enforceCallingOrSelfPermission(
9923                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9924
9925        synchronized (mPackages) {
9926            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9927            if (packageName != null) {
9928                result |= updateIntentVerificationStatus(packageName,
9929                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9930                        UserHandle.myUserId());
9931                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9932                        packageName, userId);
9933            }
9934            return result;
9935        }
9936    }
9937
9938    @Override
9939    public String getDefaultBrowserPackageName(int userId) {
9940        synchronized (mPackages) {
9941            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9942        }
9943    }
9944
9945    /**
9946     * Get the "allow unknown sources" setting.
9947     *
9948     * @return the current "allow unknown sources" setting
9949     */
9950    private int getUnknownSourcesSettings() {
9951        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9952                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9953                -1);
9954    }
9955
9956    @Override
9957    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9958        final int uid = Binder.getCallingUid();
9959        // writer
9960        synchronized (mPackages) {
9961            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9962            if (targetPackageSetting == null) {
9963                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9964            }
9965
9966            PackageSetting installerPackageSetting;
9967            if (installerPackageName != null) {
9968                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9969                if (installerPackageSetting == null) {
9970                    throw new IllegalArgumentException("Unknown installer package: "
9971                            + installerPackageName);
9972                }
9973            } else {
9974                installerPackageSetting = null;
9975            }
9976
9977            Signature[] callerSignature;
9978            Object obj = mSettings.getUserIdLPr(uid);
9979            if (obj != null) {
9980                if (obj instanceof SharedUserSetting) {
9981                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9982                } else if (obj instanceof PackageSetting) {
9983                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9984                } else {
9985                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9986                }
9987            } else {
9988                throw new SecurityException("Unknown calling uid " + uid);
9989            }
9990
9991            // Verify: can't set installerPackageName to a package that is
9992            // not signed with the same cert as the caller.
9993            if (installerPackageSetting != null) {
9994                if (compareSignatures(callerSignature,
9995                        installerPackageSetting.signatures.mSignatures)
9996                        != PackageManager.SIGNATURE_MATCH) {
9997                    throw new SecurityException(
9998                            "Caller does not have same cert as new installer package "
9999                            + installerPackageName);
10000                }
10001            }
10002
10003            // Verify: if target already has an installer package, it must
10004            // be signed with the same cert as the caller.
10005            if (targetPackageSetting.installerPackageName != null) {
10006                PackageSetting setting = mSettings.mPackages.get(
10007                        targetPackageSetting.installerPackageName);
10008                // If the currently set package isn't valid, then it's always
10009                // okay to change it.
10010                if (setting != null) {
10011                    if (compareSignatures(callerSignature,
10012                            setting.signatures.mSignatures)
10013                            != PackageManager.SIGNATURE_MATCH) {
10014                        throw new SecurityException(
10015                                "Caller does not have same cert as old installer package "
10016                                + targetPackageSetting.installerPackageName);
10017                    }
10018                }
10019            }
10020
10021            // Okay!
10022            targetPackageSetting.installerPackageName = installerPackageName;
10023            scheduleWriteSettingsLocked();
10024        }
10025    }
10026
10027    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10028        // Queue up an async operation since the package installation may take a little while.
10029        mHandler.post(new Runnable() {
10030            public void run() {
10031                mHandler.removeCallbacks(this);
10032                 // Result object to be returned
10033                PackageInstalledInfo res = new PackageInstalledInfo();
10034                res.returnCode = currentStatus;
10035                res.uid = -1;
10036                res.pkg = null;
10037                res.removedInfo = new PackageRemovedInfo();
10038                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10039                    args.doPreInstall(res.returnCode);
10040                    synchronized (mInstallLock) {
10041                        installPackageLI(args, res);
10042                    }
10043                    args.doPostInstall(res.returnCode, res.uid);
10044                }
10045
10046                // A restore should be performed at this point if (a) the install
10047                // succeeded, (b) the operation is not an update, and (c) the new
10048                // package has not opted out of backup participation.
10049                final boolean update = res.removedInfo.removedPackage != null;
10050                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10051                boolean doRestore = !update
10052                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10053
10054                // Set up the post-install work request bookkeeping.  This will be used
10055                // and cleaned up by the post-install event handling regardless of whether
10056                // there's a restore pass performed.  Token values are >= 1.
10057                int token;
10058                if (mNextInstallToken < 0) mNextInstallToken = 1;
10059                token = mNextInstallToken++;
10060
10061                PostInstallData data = new PostInstallData(args, res);
10062                mRunningInstalls.put(token, data);
10063                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10064
10065                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10066                    // Pass responsibility to the Backup Manager.  It will perform a
10067                    // restore if appropriate, then pass responsibility back to the
10068                    // Package Manager to run the post-install observer callbacks
10069                    // and broadcasts.
10070                    IBackupManager bm = IBackupManager.Stub.asInterface(
10071                            ServiceManager.getService(Context.BACKUP_SERVICE));
10072                    if (bm != null) {
10073                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10074                                + " to BM for possible restore");
10075                        try {
10076                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10077                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10078                            } else {
10079                                doRestore = false;
10080                            }
10081                        } catch (RemoteException e) {
10082                            // can't happen; the backup manager is local
10083                        } catch (Exception e) {
10084                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10085                            doRestore = false;
10086                        }
10087                    } else {
10088                        Slog.e(TAG, "Backup Manager not found!");
10089                        doRestore = false;
10090                    }
10091                }
10092
10093                if (!doRestore) {
10094                    // No restore possible, or the Backup Manager was mysteriously not
10095                    // available -- just fire the post-install work request directly.
10096                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10097                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10098                    mHandler.sendMessage(msg);
10099                }
10100            }
10101        });
10102    }
10103
10104    private abstract class HandlerParams {
10105        private static final int MAX_RETRIES = 4;
10106
10107        /**
10108         * Number of times startCopy() has been attempted and had a non-fatal
10109         * error.
10110         */
10111        private int mRetries = 0;
10112
10113        /** User handle for the user requesting the information or installation. */
10114        private final UserHandle mUser;
10115
10116        HandlerParams(UserHandle user) {
10117            mUser = user;
10118        }
10119
10120        UserHandle getUser() {
10121            return mUser;
10122        }
10123
10124        final boolean startCopy() {
10125            boolean res;
10126            try {
10127                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10128
10129                if (++mRetries > MAX_RETRIES) {
10130                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10131                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10132                    handleServiceError();
10133                    return false;
10134                } else {
10135                    handleStartCopy();
10136                    res = true;
10137                }
10138            } catch (RemoteException e) {
10139                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10140                mHandler.sendEmptyMessage(MCS_RECONNECT);
10141                res = false;
10142            }
10143            handleReturnCode();
10144            return res;
10145        }
10146
10147        final void serviceError() {
10148            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10149            handleServiceError();
10150            handleReturnCode();
10151        }
10152
10153        abstract void handleStartCopy() throws RemoteException;
10154        abstract void handleServiceError();
10155        abstract void handleReturnCode();
10156    }
10157
10158    class MeasureParams extends HandlerParams {
10159        private final PackageStats mStats;
10160        private boolean mSuccess;
10161
10162        private final IPackageStatsObserver mObserver;
10163
10164        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10165            super(new UserHandle(stats.userHandle));
10166            mObserver = observer;
10167            mStats = stats;
10168        }
10169
10170        @Override
10171        public String toString() {
10172            return "MeasureParams{"
10173                + Integer.toHexString(System.identityHashCode(this))
10174                + " " + mStats.packageName + "}";
10175        }
10176
10177        @Override
10178        void handleStartCopy() throws RemoteException {
10179            synchronized (mInstallLock) {
10180                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10181            }
10182
10183            if (mSuccess) {
10184                final boolean mounted;
10185                if (Environment.isExternalStorageEmulated()) {
10186                    mounted = true;
10187                } else {
10188                    final String status = Environment.getExternalStorageState();
10189                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10190                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10191                }
10192
10193                if (mounted) {
10194                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10195
10196                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10197                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10198
10199                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10200                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10201
10202                    // Always subtract cache size, since it's a subdirectory
10203                    mStats.externalDataSize -= mStats.externalCacheSize;
10204
10205                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10206                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10207
10208                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10209                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10210                }
10211            }
10212        }
10213
10214        @Override
10215        void handleReturnCode() {
10216            if (mObserver != null) {
10217                try {
10218                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10219                } catch (RemoteException e) {
10220                    Slog.i(TAG, "Observer no longer exists.");
10221                }
10222            }
10223        }
10224
10225        @Override
10226        void handleServiceError() {
10227            Slog.e(TAG, "Could not measure application " + mStats.packageName
10228                            + " external storage");
10229        }
10230    }
10231
10232    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10233            throws RemoteException {
10234        long result = 0;
10235        for (File path : paths) {
10236            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10237        }
10238        return result;
10239    }
10240
10241    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10242        for (File path : paths) {
10243            try {
10244                mcs.clearDirectory(path.getAbsolutePath());
10245            } catch (RemoteException e) {
10246            }
10247        }
10248    }
10249
10250    static class OriginInfo {
10251        /**
10252         * Location where install is coming from, before it has been
10253         * copied/renamed into place. This could be a single monolithic APK
10254         * file, or a cluster directory. This location may be untrusted.
10255         */
10256        final File file;
10257        final String cid;
10258
10259        /**
10260         * Flag indicating that {@link #file} or {@link #cid} has already been
10261         * staged, meaning downstream users don't need to defensively copy the
10262         * contents.
10263         */
10264        final boolean staged;
10265
10266        /**
10267         * Flag indicating that {@link #file} or {@link #cid} is an already
10268         * installed app that is being moved.
10269         */
10270        final boolean existing;
10271
10272        final String resolvedPath;
10273        final File resolvedFile;
10274
10275        static OriginInfo fromNothing() {
10276            return new OriginInfo(null, null, false, false);
10277        }
10278
10279        static OriginInfo fromUntrustedFile(File file) {
10280            return new OriginInfo(file, null, false, false);
10281        }
10282
10283        static OriginInfo fromExistingFile(File file) {
10284            return new OriginInfo(file, null, false, true);
10285        }
10286
10287        static OriginInfo fromStagedFile(File file) {
10288            return new OriginInfo(file, null, true, false);
10289        }
10290
10291        static OriginInfo fromStagedContainer(String cid) {
10292            return new OriginInfo(null, cid, true, false);
10293        }
10294
10295        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10296            this.file = file;
10297            this.cid = cid;
10298            this.staged = staged;
10299            this.existing = existing;
10300
10301            if (cid != null) {
10302                resolvedPath = PackageHelper.getSdDir(cid);
10303                resolvedFile = new File(resolvedPath);
10304            } else if (file != null) {
10305                resolvedPath = file.getAbsolutePath();
10306                resolvedFile = file;
10307            } else {
10308                resolvedPath = null;
10309                resolvedFile = null;
10310            }
10311        }
10312    }
10313
10314    class MoveInfo {
10315        final int moveId;
10316        final String fromUuid;
10317        final String toUuid;
10318        final String packageName;
10319        final String dataAppName;
10320        final int appId;
10321        final String seinfo;
10322
10323        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10324                String dataAppName, int appId, String seinfo) {
10325            this.moveId = moveId;
10326            this.fromUuid = fromUuid;
10327            this.toUuid = toUuid;
10328            this.packageName = packageName;
10329            this.dataAppName = dataAppName;
10330            this.appId = appId;
10331            this.seinfo = seinfo;
10332        }
10333    }
10334
10335    class InstallParams extends HandlerParams {
10336        final OriginInfo origin;
10337        final MoveInfo move;
10338        final IPackageInstallObserver2 observer;
10339        int installFlags;
10340        final String installerPackageName;
10341        final String volumeUuid;
10342        final VerificationParams verificationParams;
10343        private InstallArgs mArgs;
10344        private int mRet;
10345        final String packageAbiOverride;
10346
10347        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10348                int installFlags, String installerPackageName, String volumeUuid,
10349                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10350            super(user);
10351            this.origin = origin;
10352            this.move = move;
10353            this.observer = observer;
10354            this.installFlags = installFlags;
10355            this.installerPackageName = installerPackageName;
10356            this.volumeUuid = volumeUuid;
10357            this.verificationParams = verificationParams;
10358            this.packageAbiOverride = packageAbiOverride;
10359        }
10360
10361        @Override
10362        public String toString() {
10363            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10364                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10365        }
10366
10367        public ManifestDigest getManifestDigest() {
10368            if (verificationParams == null) {
10369                return null;
10370            }
10371            return verificationParams.getManifestDigest();
10372        }
10373
10374        private int installLocationPolicy(PackageInfoLite pkgLite) {
10375            String packageName = pkgLite.packageName;
10376            int installLocation = pkgLite.installLocation;
10377            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10378            // reader
10379            synchronized (mPackages) {
10380                PackageParser.Package pkg = mPackages.get(packageName);
10381                if (pkg != null) {
10382                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10383                        // Check for downgrading.
10384                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10385                            try {
10386                                checkDowngrade(pkg, pkgLite);
10387                            } catch (PackageManagerException e) {
10388                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10389                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10390                            }
10391                        }
10392                        // Check for updated system application.
10393                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10394                            if (onSd) {
10395                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10396                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10397                            }
10398                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10399                        } else {
10400                            if (onSd) {
10401                                // Install flag overrides everything.
10402                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10403                            }
10404                            // If current upgrade specifies particular preference
10405                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10406                                // Application explicitly specified internal.
10407                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10408                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10409                                // App explictly prefers external. Let policy decide
10410                            } else {
10411                                // Prefer previous location
10412                                if (isExternal(pkg)) {
10413                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10414                                }
10415                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10416                            }
10417                        }
10418                    } else {
10419                        // Invalid install. Return error code
10420                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10421                    }
10422                }
10423            }
10424            // All the special cases have been taken care of.
10425            // Return result based on recommended install location.
10426            if (onSd) {
10427                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10428            }
10429            return pkgLite.recommendedInstallLocation;
10430        }
10431
10432        /*
10433         * Invoke remote method to get package information and install
10434         * location values. Override install location based on default
10435         * policy if needed and then create install arguments based
10436         * on the install location.
10437         */
10438        public void handleStartCopy() throws RemoteException {
10439            int ret = PackageManager.INSTALL_SUCCEEDED;
10440
10441            // If we're already staged, we've firmly committed to an install location
10442            if (origin.staged) {
10443                if (origin.file != null) {
10444                    installFlags |= PackageManager.INSTALL_INTERNAL;
10445                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10446                } else if (origin.cid != null) {
10447                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10448                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10449                } else {
10450                    throw new IllegalStateException("Invalid stage location");
10451                }
10452            }
10453
10454            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10455            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10456
10457            PackageInfoLite pkgLite = null;
10458
10459            if (onInt && onSd) {
10460                // Check if both bits are set.
10461                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10462                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10463            } else {
10464                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10465                        packageAbiOverride);
10466
10467                /*
10468                 * If we have too little free space, try to free cache
10469                 * before giving up.
10470                 */
10471                if (!origin.staged && pkgLite.recommendedInstallLocation
10472                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10473                    // TODO: focus freeing disk space on the target device
10474                    final StorageManager storage = StorageManager.from(mContext);
10475                    final long lowThreshold = storage.getStorageLowBytes(
10476                            Environment.getDataDirectory());
10477
10478                    final long sizeBytes = mContainerService.calculateInstalledSize(
10479                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10480
10481                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10482                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10483                                installFlags, packageAbiOverride);
10484                    }
10485
10486                    /*
10487                     * The cache free must have deleted the file we
10488                     * downloaded to install.
10489                     *
10490                     * TODO: fix the "freeCache" call to not delete
10491                     *       the file we care about.
10492                     */
10493                    if (pkgLite.recommendedInstallLocation
10494                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10495                        pkgLite.recommendedInstallLocation
10496                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10497                    }
10498                }
10499            }
10500
10501            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10502                int loc = pkgLite.recommendedInstallLocation;
10503                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10504                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10505                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10506                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10507                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10508                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10509                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10510                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10511                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10512                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10513                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10514                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10515                } else {
10516                    // Override with defaults if needed.
10517                    loc = installLocationPolicy(pkgLite);
10518                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10519                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10520                    } else if (!onSd && !onInt) {
10521                        // Override install location with flags
10522                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10523                            // Set the flag to install on external media.
10524                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10525                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10526                        } else {
10527                            // Make sure the flag for installing on external
10528                            // media is unset
10529                            installFlags |= PackageManager.INSTALL_INTERNAL;
10530                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10531                        }
10532                    }
10533                }
10534            }
10535
10536            final InstallArgs args = createInstallArgs(this);
10537            mArgs = args;
10538
10539            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10540                 /*
10541                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10542                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10543                 */
10544                int userIdentifier = getUser().getIdentifier();
10545                if (userIdentifier == UserHandle.USER_ALL
10546                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10547                    userIdentifier = UserHandle.USER_OWNER;
10548                }
10549
10550                /*
10551                 * Determine if we have any installed package verifiers. If we
10552                 * do, then we'll defer to them to verify the packages.
10553                 */
10554                final int requiredUid = mRequiredVerifierPackage == null ? -1
10555                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10556                if (!origin.existing && requiredUid != -1
10557                        && isVerificationEnabled(userIdentifier, installFlags)) {
10558                    final Intent verification = new Intent(
10559                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10560                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10561                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10562                            PACKAGE_MIME_TYPE);
10563                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10564
10565                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10566                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10567                            0 /* TODO: Which userId? */);
10568
10569                    if (DEBUG_VERIFY) {
10570                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10571                                + verification.toString() + " with " + pkgLite.verifiers.length
10572                                + " optional verifiers");
10573                    }
10574
10575                    final int verificationId = mPendingVerificationToken++;
10576
10577                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10578
10579                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10580                            installerPackageName);
10581
10582                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10583                            installFlags);
10584
10585                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10586                            pkgLite.packageName);
10587
10588                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10589                            pkgLite.versionCode);
10590
10591                    if (verificationParams != null) {
10592                        if (verificationParams.getVerificationURI() != null) {
10593                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10594                                 verificationParams.getVerificationURI());
10595                        }
10596                        if (verificationParams.getOriginatingURI() != null) {
10597                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10598                                  verificationParams.getOriginatingURI());
10599                        }
10600                        if (verificationParams.getReferrer() != null) {
10601                            verification.putExtra(Intent.EXTRA_REFERRER,
10602                                  verificationParams.getReferrer());
10603                        }
10604                        if (verificationParams.getOriginatingUid() >= 0) {
10605                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10606                                  verificationParams.getOriginatingUid());
10607                        }
10608                        if (verificationParams.getInstallerUid() >= 0) {
10609                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10610                                  verificationParams.getInstallerUid());
10611                        }
10612                    }
10613
10614                    final PackageVerificationState verificationState = new PackageVerificationState(
10615                            requiredUid, args);
10616
10617                    mPendingVerification.append(verificationId, verificationState);
10618
10619                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10620                            receivers, verificationState);
10621
10622                    /*
10623                     * If any sufficient verifiers were listed in the package
10624                     * manifest, attempt to ask them.
10625                     */
10626                    if (sufficientVerifiers != null) {
10627                        final int N = sufficientVerifiers.size();
10628                        if (N == 0) {
10629                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10630                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10631                        } else {
10632                            for (int i = 0; i < N; i++) {
10633                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10634
10635                                final Intent sufficientIntent = new Intent(verification);
10636                                sufficientIntent.setComponent(verifierComponent);
10637
10638                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10639                            }
10640                        }
10641                    }
10642
10643                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10644                            mRequiredVerifierPackage, receivers);
10645                    if (ret == PackageManager.INSTALL_SUCCEEDED
10646                            && mRequiredVerifierPackage != null) {
10647                        /*
10648                         * Send the intent to the required verification agent,
10649                         * but only start the verification timeout after the
10650                         * target BroadcastReceivers have run.
10651                         */
10652                        verification.setComponent(requiredVerifierComponent);
10653                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10654                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10655                                new BroadcastReceiver() {
10656                                    @Override
10657                                    public void onReceive(Context context, Intent intent) {
10658                                        final Message msg = mHandler
10659                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10660                                        msg.arg1 = verificationId;
10661                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10662                                    }
10663                                }, null, 0, null, null);
10664
10665                        /*
10666                         * We don't want the copy to proceed until verification
10667                         * succeeds, so null out this field.
10668                         */
10669                        mArgs = null;
10670                    }
10671                } else {
10672                    /*
10673                     * No package verification is enabled, so immediately start
10674                     * the remote call to initiate copy using temporary file.
10675                     */
10676                    ret = args.copyApk(mContainerService, true);
10677                }
10678            }
10679
10680            mRet = ret;
10681        }
10682
10683        @Override
10684        void handleReturnCode() {
10685            // If mArgs is null, then MCS couldn't be reached. When it
10686            // reconnects, it will try again to install. At that point, this
10687            // will succeed.
10688            if (mArgs != null) {
10689                processPendingInstall(mArgs, mRet);
10690            }
10691        }
10692
10693        @Override
10694        void handleServiceError() {
10695            mArgs = createInstallArgs(this);
10696            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10697        }
10698
10699        public boolean isForwardLocked() {
10700            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10701        }
10702    }
10703
10704    /**
10705     * Used during creation of InstallArgs
10706     *
10707     * @param installFlags package installation flags
10708     * @return true if should be installed on external storage
10709     */
10710    private static boolean installOnExternalAsec(int installFlags) {
10711        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10712            return false;
10713        }
10714        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10715            return true;
10716        }
10717        return false;
10718    }
10719
10720    /**
10721     * Used during creation of InstallArgs
10722     *
10723     * @param installFlags package installation flags
10724     * @return true if should be installed as forward locked
10725     */
10726    private static boolean installForwardLocked(int installFlags) {
10727        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10728    }
10729
10730    private InstallArgs createInstallArgs(InstallParams params) {
10731        if (params.move != null) {
10732            return new MoveInstallArgs(params);
10733        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10734            return new AsecInstallArgs(params);
10735        } else {
10736            return new FileInstallArgs(params);
10737        }
10738    }
10739
10740    /**
10741     * Create args that describe an existing installed package. Typically used
10742     * when cleaning up old installs, or used as a move source.
10743     */
10744    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10745            String resourcePath, String[] instructionSets) {
10746        final boolean isInAsec;
10747        if (installOnExternalAsec(installFlags)) {
10748            /* Apps on SD card are always in ASEC containers. */
10749            isInAsec = true;
10750        } else if (installForwardLocked(installFlags)
10751                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10752            /*
10753             * Forward-locked apps are only in ASEC containers if they're the
10754             * new style
10755             */
10756            isInAsec = true;
10757        } else {
10758            isInAsec = false;
10759        }
10760
10761        if (isInAsec) {
10762            return new AsecInstallArgs(codePath, instructionSets,
10763                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10764        } else {
10765            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10766        }
10767    }
10768
10769    static abstract class InstallArgs {
10770        /** @see InstallParams#origin */
10771        final OriginInfo origin;
10772        /** @see InstallParams#move */
10773        final MoveInfo move;
10774
10775        final IPackageInstallObserver2 observer;
10776        // Always refers to PackageManager flags only
10777        final int installFlags;
10778        final String installerPackageName;
10779        final String volumeUuid;
10780        final ManifestDigest manifestDigest;
10781        final UserHandle user;
10782        final String abiOverride;
10783
10784        // The list of instruction sets supported by this app. This is currently
10785        // only used during the rmdex() phase to clean up resources. We can get rid of this
10786        // if we move dex files under the common app path.
10787        /* nullable */ String[] instructionSets;
10788
10789        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10790                int installFlags, String installerPackageName, String volumeUuid,
10791                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10792                String abiOverride) {
10793            this.origin = origin;
10794            this.move = move;
10795            this.installFlags = installFlags;
10796            this.observer = observer;
10797            this.installerPackageName = installerPackageName;
10798            this.volumeUuid = volumeUuid;
10799            this.manifestDigest = manifestDigest;
10800            this.user = user;
10801            this.instructionSets = instructionSets;
10802            this.abiOverride = abiOverride;
10803        }
10804
10805        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10806        abstract int doPreInstall(int status);
10807
10808        /**
10809         * Rename package into final resting place. All paths on the given
10810         * scanned package should be updated to reflect the rename.
10811         */
10812        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10813        abstract int doPostInstall(int status, int uid);
10814
10815        /** @see PackageSettingBase#codePathString */
10816        abstract String getCodePath();
10817        /** @see PackageSettingBase#resourcePathString */
10818        abstract String getResourcePath();
10819
10820        // Need installer lock especially for dex file removal.
10821        abstract void cleanUpResourcesLI();
10822        abstract boolean doPostDeleteLI(boolean delete);
10823
10824        /**
10825         * Called before the source arguments are copied. This is used mostly
10826         * for MoveParams when it needs to read the source file to put it in the
10827         * destination.
10828         */
10829        int doPreCopy() {
10830            return PackageManager.INSTALL_SUCCEEDED;
10831        }
10832
10833        /**
10834         * Called after the source arguments are copied. This is used mostly for
10835         * MoveParams when it needs to read the source file to put it in the
10836         * destination.
10837         *
10838         * @return
10839         */
10840        int doPostCopy(int uid) {
10841            return PackageManager.INSTALL_SUCCEEDED;
10842        }
10843
10844        protected boolean isFwdLocked() {
10845            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10846        }
10847
10848        protected boolean isExternalAsec() {
10849            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10850        }
10851
10852        UserHandle getUser() {
10853            return user;
10854        }
10855    }
10856
10857    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10858        if (!allCodePaths.isEmpty()) {
10859            if (instructionSets == null) {
10860                throw new IllegalStateException("instructionSet == null");
10861            }
10862            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10863            for (String codePath : allCodePaths) {
10864                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10865                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10866                    if (retCode < 0) {
10867                        Slog.w(TAG, "Couldn't remove dex file for package: "
10868                                + " at location " + codePath + ", retcode=" + retCode);
10869                        // we don't consider this to be a failure of the core package deletion
10870                    }
10871                }
10872            }
10873        }
10874    }
10875
10876    /**
10877     * Logic to handle installation of non-ASEC applications, including copying
10878     * and renaming logic.
10879     */
10880    class FileInstallArgs extends InstallArgs {
10881        private File codeFile;
10882        private File resourceFile;
10883
10884        // Example topology:
10885        // /data/app/com.example/base.apk
10886        // /data/app/com.example/split_foo.apk
10887        // /data/app/com.example/lib/arm/libfoo.so
10888        // /data/app/com.example/lib/arm64/libfoo.so
10889        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10890
10891        /** New install */
10892        FileInstallArgs(InstallParams params) {
10893            super(params.origin, params.move, params.observer, params.installFlags,
10894                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10895                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10896            if (isFwdLocked()) {
10897                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10898            }
10899        }
10900
10901        /** Existing install */
10902        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10903            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10904                    null);
10905            this.codeFile = (codePath != null) ? new File(codePath) : null;
10906            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10907        }
10908
10909        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10910            if (origin.staged) {
10911                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10912                codeFile = origin.file;
10913                resourceFile = origin.file;
10914                return PackageManager.INSTALL_SUCCEEDED;
10915            }
10916
10917            try {
10918                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10919                codeFile = tempDir;
10920                resourceFile = tempDir;
10921            } catch (IOException e) {
10922                Slog.w(TAG, "Failed to create copy file: " + e);
10923                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10924            }
10925
10926            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10927                @Override
10928                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10929                    if (!FileUtils.isValidExtFilename(name)) {
10930                        throw new IllegalArgumentException("Invalid filename: " + name);
10931                    }
10932                    try {
10933                        final File file = new File(codeFile, name);
10934                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10935                                O_RDWR | O_CREAT, 0644);
10936                        Os.chmod(file.getAbsolutePath(), 0644);
10937                        return new ParcelFileDescriptor(fd);
10938                    } catch (ErrnoException e) {
10939                        throw new RemoteException("Failed to open: " + e.getMessage());
10940                    }
10941                }
10942            };
10943
10944            int ret = PackageManager.INSTALL_SUCCEEDED;
10945            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10946            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10947                Slog.e(TAG, "Failed to copy package");
10948                return ret;
10949            }
10950
10951            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10952            NativeLibraryHelper.Handle handle = null;
10953            try {
10954                handle = NativeLibraryHelper.Handle.create(codeFile);
10955                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10956                        abiOverride);
10957            } catch (IOException e) {
10958                Slog.e(TAG, "Copying native libraries failed", e);
10959                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10960            } finally {
10961                IoUtils.closeQuietly(handle);
10962            }
10963
10964            return ret;
10965        }
10966
10967        int doPreInstall(int status) {
10968            if (status != PackageManager.INSTALL_SUCCEEDED) {
10969                cleanUp();
10970            }
10971            return status;
10972        }
10973
10974        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10975            if (status != PackageManager.INSTALL_SUCCEEDED) {
10976                cleanUp();
10977                return false;
10978            }
10979
10980            final File targetDir = codeFile.getParentFile();
10981            final File beforeCodeFile = codeFile;
10982            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10983
10984            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10985            try {
10986                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10987            } catch (ErrnoException e) {
10988                Slog.w(TAG, "Failed to rename", e);
10989                return false;
10990            }
10991
10992            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10993                Slog.w(TAG, "Failed to restorecon");
10994                return false;
10995            }
10996
10997            // Reflect the rename internally
10998            codeFile = afterCodeFile;
10999            resourceFile = afterCodeFile;
11000
11001            // Reflect the rename in scanned details
11002            pkg.codePath = afterCodeFile.getAbsolutePath();
11003            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11004                    pkg.baseCodePath);
11005            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11006                    pkg.splitCodePaths);
11007
11008            // Reflect the rename in app info
11009            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11010            pkg.applicationInfo.setCodePath(pkg.codePath);
11011            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11012            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11013            pkg.applicationInfo.setResourcePath(pkg.codePath);
11014            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11015            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11016
11017            return true;
11018        }
11019
11020        int doPostInstall(int status, int uid) {
11021            if (status != PackageManager.INSTALL_SUCCEEDED) {
11022                cleanUp();
11023            }
11024            return status;
11025        }
11026
11027        @Override
11028        String getCodePath() {
11029            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11030        }
11031
11032        @Override
11033        String getResourcePath() {
11034            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11035        }
11036
11037        private boolean cleanUp() {
11038            if (codeFile == null || !codeFile.exists()) {
11039                return false;
11040            }
11041
11042            if (codeFile.isDirectory()) {
11043                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11044            } else {
11045                codeFile.delete();
11046            }
11047
11048            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11049                resourceFile.delete();
11050            }
11051
11052            return true;
11053        }
11054
11055        void cleanUpResourcesLI() {
11056            // Try enumerating all code paths before deleting
11057            List<String> allCodePaths = Collections.EMPTY_LIST;
11058            if (codeFile != null && codeFile.exists()) {
11059                try {
11060                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11061                    allCodePaths = pkg.getAllCodePaths();
11062                } catch (PackageParserException e) {
11063                    // Ignored; we tried our best
11064                }
11065            }
11066
11067            cleanUp();
11068            removeDexFiles(allCodePaths, instructionSets);
11069        }
11070
11071        boolean doPostDeleteLI(boolean delete) {
11072            // XXX err, shouldn't we respect the delete flag?
11073            cleanUpResourcesLI();
11074            return true;
11075        }
11076    }
11077
11078    private boolean isAsecExternal(String cid) {
11079        final String asecPath = PackageHelper.getSdFilesystem(cid);
11080        return !asecPath.startsWith(mAsecInternalPath);
11081    }
11082
11083    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11084            PackageManagerException {
11085        if (copyRet < 0) {
11086            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11087                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11088                throw new PackageManagerException(copyRet, message);
11089            }
11090        }
11091    }
11092
11093    /**
11094     * Extract the MountService "container ID" from the full code path of an
11095     * .apk.
11096     */
11097    static String cidFromCodePath(String fullCodePath) {
11098        int eidx = fullCodePath.lastIndexOf("/");
11099        String subStr1 = fullCodePath.substring(0, eidx);
11100        int sidx = subStr1.lastIndexOf("/");
11101        return subStr1.substring(sidx+1, eidx);
11102    }
11103
11104    /**
11105     * Logic to handle installation of ASEC applications, including copying and
11106     * renaming logic.
11107     */
11108    class AsecInstallArgs extends InstallArgs {
11109        static final String RES_FILE_NAME = "pkg.apk";
11110        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11111
11112        String cid;
11113        String packagePath;
11114        String resourcePath;
11115
11116        /** New install */
11117        AsecInstallArgs(InstallParams params) {
11118            super(params.origin, params.move, params.observer, params.installFlags,
11119                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11120                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11121        }
11122
11123        /** Existing install */
11124        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11125                        boolean isExternal, boolean isForwardLocked) {
11126            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11127                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11128                    instructionSets, null);
11129            // Hackily pretend we're still looking at a full code path
11130            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11131                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11132            }
11133
11134            // Extract cid from fullCodePath
11135            int eidx = fullCodePath.lastIndexOf("/");
11136            String subStr1 = fullCodePath.substring(0, eidx);
11137            int sidx = subStr1.lastIndexOf("/");
11138            cid = subStr1.substring(sidx+1, eidx);
11139            setMountPath(subStr1);
11140        }
11141
11142        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11143            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11144                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11145                    instructionSets, null);
11146            this.cid = cid;
11147            setMountPath(PackageHelper.getSdDir(cid));
11148        }
11149
11150        void createCopyFile() {
11151            cid = mInstallerService.allocateExternalStageCidLegacy();
11152        }
11153
11154        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11155            if (origin.staged) {
11156                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11157                cid = origin.cid;
11158                setMountPath(PackageHelper.getSdDir(cid));
11159                return PackageManager.INSTALL_SUCCEEDED;
11160            }
11161
11162            if (temp) {
11163                createCopyFile();
11164            } else {
11165                /*
11166                 * Pre-emptively destroy the container since it's destroyed if
11167                 * copying fails due to it existing anyway.
11168                 */
11169                PackageHelper.destroySdDir(cid);
11170            }
11171
11172            final String newMountPath = imcs.copyPackageToContainer(
11173                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11174                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11175
11176            if (newMountPath != null) {
11177                setMountPath(newMountPath);
11178                return PackageManager.INSTALL_SUCCEEDED;
11179            } else {
11180                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11181            }
11182        }
11183
11184        @Override
11185        String getCodePath() {
11186            return packagePath;
11187        }
11188
11189        @Override
11190        String getResourcePath() {
11191            return resourcePath;
11192        }
11193
11194        int doPreInstall(int status) {
11195            if (status != PackageManager.INSTALL_SUCCEEDED) {
11196                // Destroy container
11197                PackageHelper.destroySdDir(cid);
11198            } else {
11199                boolean mounted = PackageHelper.isContainerMounted(cid);
11200                if (!mounted) {
11201                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11202                            Process.SYSTEM_UID);
11203                    if (newMountPath != null) {
11204                        setMountPath(newMountPath);
11205                    } else {
11206                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11207                    }
11208                }
11209            }
11210            return status;
11211        }
11212
11213        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11214            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11215            String newMountPath = null;
11216            if (PackageHelper.isContainerMounted(cid)) {
11217                // Unmount the container
11218                if (!PackageHelper.unMountSdDir(cid)) {
11219                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11220                    return false;
11221                }
11222            }
11223            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11224                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11225                        " which might be stale. Will try to clean up.");
11226                // Clean up the stale container and proceed to recreate.
11227                if (!PackageHelper.destroySdDir(newCacheId)) {
11228                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11229                    return false;
11230                }
11231                // Successfully cleaned up stale container. Try to rename again.
11232                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11233                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11234                            + " inspite of cleaning it up.");
11235                    return false;
11236                }
11237            }
11238            if (!PackageHelper.isContainerMounted(newCacheId)) {
11239                Slog.w(TAG, "Mounting container " + newCacheId);
11240                newMountPath = PackageHelper.mountSdDir(newCacheId,
11241                        getEncryptKey(), Process.SYSTEM_UID);
11242            } else {
11243                newMountPath = PackageHelper.getSdDir(newCacheId);
11244            }
11245            if (newMountPath == null) {
11246                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11247                return false;
11248            }
11249            Log.i(TAG, "Succesfully renamed " + cid +
11250                    " to " + newCacheId +
11251                    " at new path: " + newMountPath);
11252            cid = newCacheId;
11253
11254            final File beforeCodeFile = new File(packagePath);
11255            setMountPath(newMountPath);
11256            final File afterCodeFile = new File(packagePath);
11257
11258            // Reflect the rename in scanned details
11259            pkg.codePath = afterCodeFile.getAbsolutePath();
11260            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11261                    pkg.baseCodePath);
11262            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11263                    pkg.splitCodePaths);
11264
11265            // Reflect the rename in app info
11266            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11267            pkg.applicationInfo.setCodePath(pkg.codePath);
11268            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11269            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11270            pkg.applicationInfo.setResourcePath(pkg.codePath);
11271            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11272            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11273
11274            return true;
11275        }
11276
11277        private void setMountPath(String mountPath) {
11278            final File mountFile = new File(mountPath);
11279
11280            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11281            if (monolithicFile.exists()) {
11282                packagePath = monolithicFile.getAbsolutePath();
11283                if (isFwdLocked()) {
11284                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11285                } else {
11286                    resourcePath = packagePath;
11287                }
11288            } else {
11289                packagePath = mountFile.getAbsolutePath();
11290                resourcePath = packagePath;
11291            }
11292        }
11293
11294        int doPostInstall(int status, int uid) {
11295            if (status != PackageManager.INSTALL_SUCCEEDED) {
11296                cleanUp();
11297            } else {
11298                final int groupOwner;
11299                final String protectedFile;
11300                if (isFwdLocked()) {
11301                    groupOwner = UserHandle.getSharedAppGid(uid);
11302                    protectedFile = RES_FILE_NAME;
11303                } else {
11304                    groupOwner = -1;
11305                    protectedFile = null;
11306                }
11307
11308                if (uid < Process.FIRST_APPLICATION_UID
11309                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11310                    Slog.e(TAG, "Failed to finalize " + cid);
11311                    PackageHelper.destroySdDir(cid);
11312                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11313                }
11314
11315                boolean mounted = PackageHelper.isContainerMounted(cid);
11316                if (!mounted) {
11317                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11318                }
11319            }
11320            return status;
11321        }
11322
11323        private void cleanUp() {
11324            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11325
11326            // Destroy secure container
11327            PackageHelper.destroySdDir(cid);
11328        }
11329
11330        private List<String> getAllCodePaths() {
11331            final File codeFile = new File(getCodePath());
11332            if (codeFile != null && codeFile.exists()) {
11333                try {
11334                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11335                    return pkg.getAllCodePaths();
11336                } catch (PackageParserException e) {
11337                    // Ignored; we tried our best
11338                }
11339            }
11340            return Collections.EMPTY_LIST;
11341        }
11342
11343        void cleanUpResourcesLI() {
11344            // Enumerate all code paths before deleting
11345            cleanUpResourcesLI(getAllCodePaths());
11346        }
11347
11348        private void cleanUpResourcesLI(List<String> allCodePaths) {
11349            cleanUp();
11350            removeDexFiles(allCodePaths, instructionSets);
11351        }
11352
11353        String getPackageName() {
11354            return getAsecPackageName(cid);
11355        }
11356
11357        boolean doPostDeleteLI(boolean delete) {
11358            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11359            final List<String> allCodePaths = getAllCodePaths();
11360            boolean mounted = PackageHelper.isContainerMounted(cid);
11361            if (mounted) {
11362                // Unmount first
11363                if (PackageHelper.unMountSdDir(cid)) {
11364                    mounted = false;
11365                }
11366            }
11367            if (!mounted && delete) {
11368                cleanUpResourcesLI(allCodePaths);
11369            }
11370            return !mounted;
11371        }
11372
11373        @Override
11374        int doPreCopy() {
11375            if (isFwdLocked()) {
11376                if (!PackageHelper.fixSdPermissions(cid,
11377                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11378                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11379                }
11380            }
11381
11382            return PackageManager.INSTALL_SUCCEEDED;
11383        }
11384
11385        @Override
11386        int doPostCopy(int uid) {
11387            if (isFwdLocked()) {
11388                if (uid < Process.FIRST_APPLICATION_UID
11389                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11390                                RES_FILE_NAME)) {
11391                    Slog.e(TAG, "Failed to finalize " + cid);
11392                    PackageHelper.destroySdDir(cid);
11393                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11394                }
11395            }
11396
11397            return PackageManager.INSTALL_SUCCEEDED;
11398        }
11399    }
11400
11401    /**
11402     * Logic to handle movement of existing installed applications.
11403     */
11404    class MoveInstallArgs extends InstallArgs {
11405        private File codeFile;
11406        private File resourceFile;
11407
11408        /** New install */
11409        MoveInstallArgs(InstallParams params) {
11410            super(params.origin, params.move, params.observer, params.installFlags,
11411                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11412                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11413        }
11414
11415        int copyApk(IMediaContainerService imcs, boolean temp) {
11416            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11417                    + move.fromUuid + " to " + move.toUuid);
11418            synchronized (mInstaller) {
11419                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11420                        move.dataAppName, move.appId, move.seinfo) != 0) {
11421                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11422                }
11423            }
11424
11425            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11426            resourceFile = codeFile;
11427            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11428
11429            return PackageManager.INSTALL_SUCCEEDED;
11430        }
11431
11432        int doPreInstall(int status) {
11433            if (status != PackageManager.INSTALL_SUCCEEDED) {
11434                cleanUp(move.toUuid);
11435            }
11436            return status;
11437        }
11438
11439        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11440            if (status != PackageManager.INSTALL_SUCCEEDED) {
11441                cleanUp(move.toUuid);
11442                return false;
11443            }
11444
11445            // Reflect the move in app info
11446            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11447            pkg.applicationInfo.setCodePath(pkg.codePath);
11448            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11449            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11450            pkg.applicationInfo.setResourcePath(pkg.codePath);
11451            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11452            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11453
11454            return true;
11455        }
11456
11457        int doPostInstall(int status, int uid) {
11458            if (status == PackageManager.INSTALL_SUCCEEDED) {
11459                cleanUp(move.fromUuid);
11460            } else {
11461                cleanUp(move.toUuid);
11462            }
11463            return status;
11464        }
11465
11466        @Override
11467        String getCodePath() {
11468            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11469        }
11470
11471        @Override
11472        String getResourcePath() {
11473            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11474        }
11475
11476        private boolean cleanUp(String volumeUuid) {
11477            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11478                    move.dataAppName);
11479            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11480            synchronized (mInstallLock) {
11481                // Clean up both app data and code
11482                removeDataDirsLI(volumeUuid, move.packageName);
11483                if (codeFile.isDirectory()) {
11484                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11485                } else {
11486                    codeFile.delete();
11487                }
11488            }
11489            return true;
11490        }
11491
11492        void cleanUpResourcesLI() {
11493            throw new UnsupportedOperationException();
11494        }
11495
11496        boolean doPostDeleteLI(boolean delete) {
11497            throw new UnsupportedOperationException();
11498        }
11499    }
11500
11501    static String getAsecPackageName(String packageCid) {
11502        int idx = packageCid.lastIndexOf("-");
11503        if (idx == -1) {
11504            return packageCid;
11505        }
11506        return packageCid.substring(0, idx);
11507    }
11508
11509    // Utility method used to create code paths based on package name and available index.
11510    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11511        String idxStr = "";
11512        int idx = 1;
11513        // Fall back to default value of idx=1 if prefix is not
11514        // part of oldCodePath
11515        if (oldCodePath != null) {
11516            String subStr = oldCodePath;
11517            // Drop the suffix right away
11518            if (suffix != null && subStr.endsWith(suffix)) {
11519                subStr = subStr.substring(0, subStr.length() - suffix.length());
11520            }
11521            // If oldCodePath already contains prefix find out the
11522            // ending index to either increment or decrement.
11523            int sidx = subStr.lastIndexOf(prefix);
11524            if (sidx != -1) {
11525                subStr = subStr.substring(sidx + prefix.length());
11526                if (subStr != null) {
11527                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11528                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11529                    }
11530                    try {
11531                        idx = Integer.parseInt(subStr);
11532                        if (idx <= 1) {
11533                            idx++;
11534                        } else {
11535                            idx--;
11536                        }
11537                    } catch(NumberFormatException e) {
11538                    }
11539                }
11540            }
11541        }
11542        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11543        return prefix + idxStr;
11544    }
11545
11546    private File getNextCodePath(File targetDir, String packageName) {
11547        int suffix = 1;
11548        File result;
11549        do {
11550            result = new File(targetDir, packageName + "-" + suffix);
11551            suffix++;
11552        } while (result.exists());
11553        return result;
11554    }
11555
11556    // Utility method that returns the relative package path with respect
11557    // to the installation directory. Like say for /data/data/com.test-1.apk
11558    // string com.test-1 is returned.
11559    static String deriveCodePathName(String codePath) {
11560        if (codePath == null) {
11561            return null;
11562        }
11563        final File codeFile = new File(codePath);
11564        final String name = codeFile.getName();
11565        if (codeFile.isDirectory()) {
11566            return name;
11567        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11568            final int lastDot = name.lastIndexOf('.');
11569            return name.substring(0, lastDot);
11570        } else {
11571            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11572            return null;
11573        }
11574    }
11575
11576    class PackageInstalledInfo {
11577        String name;
11578        int uid;
11579        // The set of users that originally had this package installed.
11580        int[] origUsers;
11581        // The set of users that now have this package installed.
11582        int[] newUsers;
11583        PackageParser.Package pkg;
11584        int returnCode;
11585        String returnMsg;
11586        PackageRemovedInfo removedInfo;
11587
11588        public void setError(int code, String msg) {
11589            returnCode = code;
11590            returnMsg = msg;
11591            Slog.w(TAG, msg);
11592        }
11593
11594        public void setError(String msg, PackageParserException e) {
11595            returnCode = e.error;
11596            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11597            Slog.w(TAG, msg, e);
11598        }
11599
11600        public void setError(String msg, PackageManagerException e) {
11601            returnCode = e.error;
11602            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11603            Slog.w(TAG, msg, e);
11604        }
11605
11606        // In some error cases we want to convey more info back to the observer
11607        String origPackage;
11608        String origPermission;
11609    }
11610
11611    /*
11612     * Install a non-existing package.
11613     */
11614    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11615            UserHandle user, String installerPackageName, String volumeUuid,
11616            PackageInstalledInfo res) {
11617        // Remember this for later, in case we need to rollback this install
11618        String pkgName = pkg.packageName;
11619
11620        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11621        final boolean dataDirExists = Environment
11622                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11623        synchronized(mPackages) {
11624            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11625                // A package with the same name is already installed, though
11626                // it has been renamed to an older name.  The package we
11627                // are trying to install should be installed as an update to
11628                // the existing one, but that has not been requested, so bail.
11629                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11630                        + " without first uninstalling package running as "
11631                        + mSettings.mRenamedPackages.get(pkgName));
11632                return;
11633            }
11634            if (mPackages.containsKey(pkgName)) {
11635                // Don't allow installation over an existing package with the same name.
11636                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11637                        + " without first uninstalling.");
11638                return;
11639            }
11640        }
11641
11642        try {
11643            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11644                    System.currentTimeMillis(), user);
11645
11646            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11647            // delete the partially installed application. the data directory will have to be
11648            // restored if it was already existing
11649            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11650                // remove package from internal structures.  Note that we want deletePackageX to
11651                // delete the package data and cache directories that it created in
11652                // scanPackageLocked, unless those directories existed before we even tried to
11653                // install.
11654                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11655                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11656                                res.removedInfo, true);
11657            }
11658
11659        } catch (PackageManagerException e) {
11660            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11661        }
11662    }
11663
11664    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11665        // Can't rotate keys during boot or if sharedUser.
11666        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11667                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11668            return false;
11669        }
11670        // app is using upgradeKeySets; make sure all are valid
11671        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11672        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11673        for (int i = 0; i < upgradeKeySets.length; i++) {
11674            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11675                Slog.wtf(TAG, "Package "
11676                         + (oldPs.name != null ? oldPs.name : "<null>")
11677                         + " contains upgrade-key-set reference to unknown key-set: "
11678                         + upgradeKeySets[i]
11679                         + " reverting to signatures check.");
11680                return false;
11681            }
11682        }
11683        return true;
11684    }
11685
11686    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11687        // Upgrade keysets are being used.  Determine if new package has a superset of the
11688        // required keys.
11689        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11690        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11691        for (int i = 0; i < upgradeKeySets.length; i++) {
11692            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11693            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11694                return true;
11695            }
11696        }
11697        return false;
11698    }
11699
11700    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11701            UserHandle user, String installerPackageName, String volumeUuid,
11702            PackageInstalledInfo res) {
11703        final PackageParser.Package oldPackage;
11704        final String pkgName = pkg.packageName;
11705        final int[] allUsers;
11706        final boolean[] perUserInstalled;
11707        final boolean weFroze;
11708
11709        // First find the old package info and check signatures
11710        synchronized(mPackages) {
11711            oldPackage = mPackages.get(pkgName);
11712            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11713            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11714            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11715                if(!checkUpgradeKeySetLP(ps, pkg)) {
11716                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11717                            "New package not signed by keys specified by upgrade-keysets: "
11718                            + pkgName);
11719                    return;
11720                }
11721            } else {
11722                // default to original signature matching
11723                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11724                    != PackageManager.SIGNATURE_MATCH) {
11725                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11726                            "New package has a different signature: " + pkgName);
11727                    return;
11728                }
11729            }
11730
11731            // In case of rollback, remember per-user/profile install state
11732            allUsers = sUserManager.getUserIds();
11733            perUserInstalled = new boolean[allUsers.length];
11734            for (int i = 0; i < allUsers.length; i++) {
11735                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11736            }
11737
11738            // Mark the app as frozen to prevent launching during the upgrade
11739            // process, and then kill all running instances
11740            if (!ps.frozen) {
11741                ps.frozen = true;
11742                weFroze = true;
11743            } else {
11744                weFroze = false;
11745            }
11746        }
11747
11748        // Now that we're guarded by frozen state, kill app during upgrade
11749        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11750
11751        try {
11752            boolean sysPkg = (isSystemApp(oldPackage));
11753            if (sysPkg) {
11754                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11755                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11756            } else {
11757                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11758                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11759            }
11760        } finally {
11761            // Regardless of success or failure of upgrade steps above, always
11762            // unfreeze the package if we froze it
11763            if (weFroze) {
11764                unfreezePackage(pkgName);
11765            }
11766        }
11767    }
11768
11769    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11770            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11771            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11772            String volumeUuid, PackageInstalledInfo res) {
11773        String pkgName = deletedPackage.packageName;
11774        boolean deletedPkg = true;
11775        boolean updatedSettings = false;
11776
11777        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11778                + deletedPackage);
11779        long origUpdateTime;
11780        if (pkg.mExtras != null) {
11781            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11782        } else {
11783            origUpdateTime = 0;
11784        }
11785
11786        // First delete the existing package while retaining the data directory
11787        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11788                res.removedInfo, true)) {
11789            // If the existing package wasn't successfully deleted
11790            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11791            deletedPkg = false;
11792        } else {
11793            // Successfully deleted the old package; proceed with replace.
11794
11795            // If deleted package lived in a container, give users a chance to
11796            // relinquish resources before killing.
11797            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11798                if (DEBUG_INSTALL) {
11799                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11800                }
11801                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11802                final ArrayList<String> pkgList = new ArrayList<String>(1);
11803                pkgList.add(deletedPackage.applicationInfo.packageName);
11804                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11805            }
11806
11807            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11808            try {
11809                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11810                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11811                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11812                        perUserInstalled, res, user);
11813                updatedSettings = true;
11814            } catch (PackageManagerException e) {
11815                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11816            }
11817        }
11818
11819        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11820            // remove package from internal structures.  Note that we want deletePackageX to
11821            // delete the package data and cache directories that it created in
11822            // scanPackageLocked, unless those directories existed before we even tried to
11823            // install.
11824            if(updatedSettings) {
11825                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11826                deletePackageLI(
11827                        pkgName, null, true, allUsers, perUserInstalled,
11828                        PackageManager.DELETE_KEEP_DATA,
11829                                res.removedInfo, true);
11830            }
11831            // Since we failed to install the new package we need to restore the old
11832            // package that we deleted.
11833            if (deletedPkg) {
11834                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11835                File restoreFile = new File(deletedPackage.codePath);
11836                // Parse old package
11837                boolean oldExternal = isExternal(deletedPackage);
11838                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11839                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11840                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11841                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11842                try {
11843                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11844                } catch (PackageManagerException e) {
11845                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11846                            + e.getMessage());
11847                    return;
11848                }
11849                // Restore of old package succeeded. Update permissions.
11850                // writer
11851                synchronized (mPackages) {
11852                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11853                            UPDATE_PERMISSIONS_ALL);
11854                    // can downgrade to reader
11855                    mSettings.writeLPr();
11856                }
11857                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11858            }
11859        }
11860    }
11861
11862    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11863            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11864            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11865            String volumeUuid, PackageInstalledInfo res) {
11866        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11867                + ", old=" + deletedPackage);
11868        boolean disabledSystem = false;
11869        boolean updatedSettings = false;
11870        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11871        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11872                != 0) {
11873            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11874        }
11875        String packageName = deletedPackage.packageName;
11876        if (packageName == null) {
11877            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11878                    "Attempt to delete null packageName.");
11879            return;
11880        }
11881        PackageParser.Package oldPkg;
11882        PackageSetting oldPkgSetting;
11883        // reader
11884        synchronized (mPackages) {
11885            oldPkg = mPackages.get(packageName);
11886            oldPkgSetting = mSettings.mPackages.get(packageName);
11887            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11888                    (oldPkgSetting == null)) {
11889                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11890                        "Couldn't find package:" + packageName + " information");
11891                return;
11892            }
11893        }
11894
11895        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11896        res.removedInfo.removedPackage = packageName;
11897        // Remove existing system package
11898        removePackageLI(oldPkgSetting, true);
11899        // writer
11900        synchronized (mPackages) {
11901            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11902            if (!disabledSystem && deletedPackage != null) {
11903                // We didn't need to disable the .apk as a current system package,
11904                // which means we are replacing another update that is already
11905                // installed.  We need to make sure to delete the older one's .apk.
11906                res.removedInfo.args = createInstallArgsForExisting(0,
11907                        deletedPackage.applicationInfo.getCodePath(),
11908                        deletedPackage.applicationInfo.getResourcePath(),
11909                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11910            } else {
11911                res.removedInfo.args = null;
11912            }
11913        }
11914
11915        // Successfully disabled the old package. Now proceed with re-installation
11916        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11917
11918        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11919        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11920
11921        PackageParser.Package newPackage = null;
11922        try {
11923            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11924            if (newPackage.mExtras != null) {
11925                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11926                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11927                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11928
11929                // is the update attempting to change shared user? that isn't going to work...
11930                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11931                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11932                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11933                            + " to " + newPkgSetting.sharedUser);
11934                    updatedSettings = true;
11935                }
11936            }
11937
11938            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11939                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11940                        perUserInstalled, res, user);
11941                updatedSettings = true;
11942            }
11943
11944        } catch (PackageManagerException e) {
11945            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11946        }
11947
11948        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11949            // Re installation failed. Restore old information
11950            // Remove new pkg information
11951            if (newPackage != null) {
11952                removeInstalledPackageLI(newPackage, true);
11953            }
11954            // Add back the old system package
11955            try {
11956                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11957            } catch (PackageManagerException e) {
11958                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11959            }
11960            // Restore the old system information in Settings
11961            synchronized (mPackages) {
11962                if (disabledSystem) {
11963                    mSettings.enableSystemPackageLPw(packageName);
11964                }
11965                if (updatedSettings) {
11966                    mSettings.setInstallerPackageName(packageName,
11967                            oldPkgSetting.installerPackageName);
11968                }
11969                mSettings.writeLPr();
11970            }
11971        }
11972    }
11973
11974    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11975            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11976            UserHandle user) {
11977        String pkgName = newPackage.packageName;
11978        synchronized (mPackages) {
11979            //write settings. the installStatus will be incomplete at this stage.
11980            //note that the new package setting would have already been
11981            //added to mPackages. It hasn't been persisted yet.
11982            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11983            mSettings.writeLPr();
11984        }
11985
11986        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11987
11988        synchronized (mPackages) {
11989            updatePermissionsLPw(newPackage.packageName, newPackage,
11990                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11991                            ? UPDATE_PERMISSIONS_ALL : 0));
11992            // For system-bundled packages, we assume that installing an upgraded version
11993            // of the package implies that the user actually wants to run that new code,
11994            // so we enable the package.
11995            PackageSetting ps = mSettings.mPackages.get(pkgName);
11996            if (ps != null) {
11997                if (isSystemApp(newPackage)) {
11998                    // NB: implicit assumption that system package upgrades apply to all users
11999                    if (DEBUG_INSTALL) {
12000                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12001                    }
12002                    if (res.origUsers != null) {
12003                        for (int userHandle : res.origUsers) {
12004                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12005                                    userHandle, installerPackageName);
12006                        }
12007                    }
12008                    // Also convey the prior install/uninstall state
12009                    if (allUsers != null && perUserInstalled != null) {
12010                        for (int i = 0; i < allUsers.length; i++) {
12011                            if (DEBUG_INSTALL) {
12012                                Slog.d(TAG, "    user " + allUsers[i]
12013                                        + " => " + perUserInstalled[i]);
12014                            }
12015                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12016                        }
12017                        // these install state changes will be persisted in the
12018                        // upcoming call to mSettings.writeLPr().
12019                    }
12020                }
12021                // It's implied that when a user requests installation, they want the app to be
12022                // installed and enabled.
12023                int userId = user.getIdentifier();
12024                if (userId != UserHandle.USER_ALL) {
12025                    ps.setInstalled(true, userId);
12026                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12027                }
12028            }
12029            res.name = pkgName;
12030            res.uid = newPackage.applicationInfo.uid;
12031            res.pkg = newPackage;
12032            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12033            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12034            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12035            //to update install status
12036            mSettings.writeLPr();
12037        }
12038    }
12039
12040    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12041        final int installFlags = args.installFlags;
12042        final String installerPackageName = args.installerPackageName;
12043        final String volumeUuid = args.volumeUuid;
12044        final File tmpPackageFile = new File(args.getCodePath());
12045        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12046        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12047                || (args.volumeUuid != null));
12048        boolean replace = false;
12049        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12050        if (args.move != null) {
12051            // moving a complete application; perfom an initial scan on the new install location
12052            scanFlags |= SCAN_INITIAL;
12053        }
12054        // Result object to be returned
12055        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12056
12057        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12058        // Retrieve PackageSettings and parse package
12059        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12060                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12061                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12062        PackageParser pp = new PackageParser();
12063        pp.setSeparateProcesses(mSeparateProcesses);
12064        pp.setDisplayMetrics(mMetrics);
12065
12066        final PackageParser.Package pkg;
12067        try {
12068            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12069        } catch (PackageParserException e) {
12070            res.setError("Failed parse during installPackageLI", e);
12071            return;
12072        }
12073
12074        // Mark that we have an install time CPU ABI override.
12075        pkg.cpuAbiOverride = args.abiOverride;
12076
12077        String pkgName = res.name = pkg.packageName;
12078        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12079            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12080                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12081                return;
12082            }
12083        }
12084
12085        try {
12086            pp.collectCertificates(pkg, parseFlags);
12087            pp.collectManifestDigest(pkg);
12088        } catch (PackageParserException e) {
12089            res.setError("Failed collect during installPackageLI", e);
12090            return;
12091        }
12092
12093        /* If the installer passed in a manifest digest, compare it now. */
12094        if (args.manifestDigest != null) {
12095            if (DEBUG_INSTALL) {
12096                final String parsedManifest = pkg.manifestDigest == null ? "null"
12097                        : pkg.manifestDigest.toString();
12098                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12099                        + parsedManifest);
12100            }
12101
12102            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12103                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12104                return;
12105            }
12106        } else if (DEBUG_INSTALL) {
12107            final String parsedManifest = pkg.manifestDigest == null
12108                    ? "null" : pkg.manifestDigest.toString();
12109            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12110        }
12111
12112        // Get rid of all references to package scan path via parser.
12113        pp = null;
12114        String oldCodePath = null;
12115        boolean systemApp = false;
12116        synchronized (mPackages) {
12117            // Check if installing already existing package
12118            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12119                String oldName = mSettings.mRenamedPackages.get(pkgName);
12120                if (pkg.mOriginalPackages != null
12121                        && pkg.mOriginalPackages.contains(oldName)
12122                        && mPackages.containsKey(oldName)) {
12123                    // This package is derived from an original package,
12124                    // and this device has been updating from that original
12125                    // name.  We must continue using the original name, so
12126                    // rename the new package here.
12127                    pkg.setPackageName(oldName);
12128                    pkgName = pkg.packageName;
12129                    replace = true;
12130                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12131                            + oldName + " pkgName=" + pkgName);
12132                } else if (mPackages.containsKey(pkgName)) {
12133                    // This package, under its official name, already exists
12134                    // on the device; we should replace it.
12135                    replace = true;
12136                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12137                }
12138
12139                // Prevent apps opting out from runtime permissions
12140                if (replace) {
12141                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12142                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12143                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12144                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12145                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12146                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12147                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12148                                        + " doesn't support runtime permissions but the old"
12149                                        + " target SDK " + oldTargetSdk + " does.");
12150                        return;
12151                    }
12152                }
12153            }
12154
12155            PackageSetting ps = mSettings.mPackages.get(pkgName);
12156            if (ps != null) {
12157                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12158
12159                // Quick sanity check that we're signed correctly if updating;
12160                // we'll check this again later when scanning, but we want to
12161                // bail early here before tripping over redefined permissions.
12162                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12163                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12164                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12165                                + pkg.packageName + " upgrade keys do not match the "
12166                                + "previously installed version");
12167                        return;
12168                    }
12169                } else {
12170                    try {
12171                        verifySignaturesLP(ps, pkg);
12172                    } catch (PackageManagerException e) {
12173                        res.setError(e.error, e.getMessage());
12174                        return;
12175                    }
12176                }
12177
12178                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12179                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12180                    systemApp = (ps.pkg.applicationInfo.flags &
12181                            ApplicationInfo.FLAG_SYSTEM) != 0;
12182                }
12183                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12184            }
12185
12186            // Check whether the newly-scanned package wants to define an already-defined perm
12187            int N = pkg.permissions.size();
12188            for (int i = N-1; i >= 0; i--) {
12189                PackageParser.Permission perm = pkg.permissions.get(i);
12190                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12191                if (bp != null) {
12192                    // If the defining package is signed with our cert, it's okay.  This
12193                    // also includes the "updating the same package" case, of course.
12194                    // "updating same package" could also involve key-rotation.
12195                    final boolean sigsOk;
12196                    if (bp.sourcePackage.equals(pkg.packageName)
12197                            && (bp.packageSetting instanceof PackageSetting)
12198                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12199                                    scanFlags))) {
12200                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12201                    } else {
12202                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12203                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12204                    }
12205                    if (!sigsOk) {
12206                        // If the owning package is the system itself, we log but allow
12207                        // install to proceed; we fail the install on all other permission
12208                        // redefinitions.
12209                        if (!bp.sourcePackage.equals("android")) {
12210                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12211                                    + pkg.packageName + " attempting to redeclare permission "
12212                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12213                            res.origPermission = perm.info.name;
12214                            res.origPackage = bp.sourcePackage;
12215                            return;
12216                        } else {
12217                            Slog.w(TAG, "Package " + pkg.packageName
12218                                    + " attempting to redeclare system permission "
12219                                    + perm.info.name + "; ignoring new declaration");
12220                            pkg.permissions.remove(i);
12221                        }
12222                    }
12223                }
12224            }
12225
12226        }
12227
12228        if (systemApp && onExternal) {
12229            // Disable updates to system apps on sdcard
12230            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12231                    "Cannot install updates to system apps on sdcard");
12232            return;
12233        }
12234
12235        if (args.move != null) {
12236            // We did an in-place move, so dex is ready to roll
12237            scanFlags |= SCAN_NO_DEX;
12238            scanFlags |= SCAN_MOVE;
12239        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12240            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12241            scanFlags |= SCAN_NO_DEX;
12242
12243            try {
12244                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12245                        true /* extract libs */);
12246            } catch (PackageManagerException pme) {
12247                Slog.e(TAG, "Error deriving application ABI", pme);
12248                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12249                return;
12250            }
12251
12252            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12253            int result = mPackageDexOptimizer
12254                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12255                            false /* defer */, false /* inclDependencies */);
12256            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12257                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12258                return;
12259            }
12260        }
12261
12262        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12263            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12264            return;
12265        }
12266
12267        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12268
12269        if (replace) {
12270            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12271                    installerPackageName, volumeUuid, res);
12272        } else {
12273            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12274                    args.user, installerPackageName, volumeUuid, res);
12275        }
12276        synchronized (mPackages) {
12277            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12278            if (ps != null) {
12279                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12280            }
12281        }
12282    }
12283
12284    private void startIntentFilterVerifications(int userId, boolean replacing,
12285            PackageParser.Package pkg) {
12286        if (mIntentFilterVerifierComponent == null) {
12287            Slog.w(TAG, "No IntentFilter verification will not be done as "
12288                    + "there is no IntentFilterVerifier available!");
12289            return;
12290        }
12291
12292        final int verifierUid = getPackageUid(
12293                mIntentFilterVerifierComponent.getPackageName(),
12294                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12295
12296        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12297        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12298        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12299        mHandler.sendMessage(msg);
12300    }
12301
12302    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12303            PackageParser.Package pkg) {
12304        int size = pkg.activities.size();
12305        if (size == 0) {
12306            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12307                    "No activity, so no need to verify any IntentFilter!");
12308            return;
12309        }
12310
12311        final boolean hasDomainURLs = hasDomainURLs(pkg);
12312        if (!hasDomainURLs) {
12313            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12314                    "No domain URLs, so no need to verify any IntentFilter!");
12315            return;
12316        }
12317
12318        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12319                + " if any IntentFilter from the " + size
12320                + " Activities needs verification ...");
12321
12322        int count = 0;
12323        final String packageName = pkg.packageName;
12324
12325        synchronized (mPackages) {
12326            // If this is a new install and we see that we've already run verification for this
12327            // package, we have nothing to do: it means the state was restored from backup.
12328            if (!replacing) {
12329                IntentFilterVerificationInfo ivi =
12330                        mSettings.getIntentFilterVerificationLPr(packageName);
12331                if (ivi != null) {
12332                    if (DEBUG_DOMAIN_VERIFICATION) {
12333                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12334                                + ivi.getStatusString());
12335                    }
12336                    return;
12337                }
12338            }
12339
12340            // If any filters need to be verified, then all need to be.
12341            boolean needToVerify = false;
12342            for (PackageParser.Activity a : pkg.activities) {
12343                for (ActivityIntentInfo filter : a.intents) {
12344                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12345                        if (DEBUG_DOMAIN_VERIFICATION) {
12346                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12347                        }
12348                        needToVerify = true;
12349                        break;
12350                    }
12351                }
12352            }
12353
12354            if (needToVerify) {
12355                final int verificationId = mIntentFilterVerificationToken++;
12356                for (PackageParser.Activity a : pkg.activities) {
12357                    for (ActivityIntentInfo filter : a.intents) {
12358                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12359                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12360                                    "Verification needed for IntentFilter:" + filter.toString());
12361                            mIntentFilterVerifier.addOneIntentFilterVerification(
12362                                    verifierUid, userId, verificationId, filter, packageName);
12363                            count++;
12364                        }
12365                    }
12366                }
12367            }
12368        }
12369
12370        if (count > 0) {
12371            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12372                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12373                    +  " for userId:" + userId);
12374            mIntentFilterVerifier.startVerifications(userId);
12375        } else {
12376            if (DEBUG_DOMAIN_VERIFICATION) {
12377                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12378            }
12379        }
12380    }
12381
12382    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12383        final ComponentName cn  = filter.activity.getComponentName();
12384        final String packageName = cn.getPackageName();
12385
12386        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12387                packageName);
12388        if (ivi == null) {
12389            return true;
12390        }
12391        int status = ivi.getStatus();
12392        switch (status) {
12393            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12394            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12395                return true;
12396
12397            default:
12398                // Nothing to do
12399                return false;
12400        }
12401    }
12402
12403    private static boolean isMultiArch(PackageSetting ps) {
12404        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12405    }
12406
12407    private static boolean isMultiArch(ApplicationInfo info) {
12408        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12409    }
12410
12411    private static boolean isExternal(PackageParser.Package pkg) {
12412        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12413    }
12414
12415    private static boolean isExternal(PackageSetting ps) {
12416        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12417    }
12418
12419    private static boolean isExternal(ApplicationInfo info) {
12420        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12421    }
12422
12423    private static boolean isSystemApp(PackageParser.Package pkg) {
12424        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12425    }
12426
12427    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12428        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12429    }
12430
12431    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12432        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12433    }
12434
12435    private static boolean isSystemApp(PackageSetting ps) {
12436        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12437    }
12438
12439    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12440        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12441    }
12442
12443    private int packageFlagsToInstallFlags(PackageSetting ps) {
12444        int installFlags = 0;
12445        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12446            // This existing package was an external ASEC install when we have
12447            // the external flag without a UUID
12448            installFlags |= PackageManager.INSTALL_EXTERNAL;
12449        }
12450        if (ps.isForwardLocked()) {
12451            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12452        }
12453        return installFlags;
12454    }
12455
12456    private void deleteTempPackageFiles() {
12457        final FilenameFilter filter = new FilenameFilter() {
12458            public boolean accept(File dir, String name) {
12459                return name.startsWith("vmdl") && name.endsWith(".tmp");
12460            }
12461        };
12462        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12463            file.delete();
12464        }
12465    }
12466
12467    @Override
12468    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12469            int flags) {
12470        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12471                flags);
12472    }
12473
12474    @Override
12475    public void deletePackage(final String packageName,
12476            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12477        mContext.enforceCallingOrSelfPermission(
12478                android.Manifest.permission.DELETE_PACKAGES, null);
12479        Preconditions.checkNotNull(packageName);
12480        Preconditions.checkNotNull(observer);
12481        final int uid = Binder.getCallingUid();
12482        if (UserHandle.getUserId(uid) != userId) {
12483            mContext.enforceCallingPermission(
12484                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12485                    "deletePackage for user " + userId);
12486        }
12487        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12488            try {
12489                observer.onPackageDeleted(packageName,
12490                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12491            } catch (RemoteException re) {
12492            }
12493            return;
12494        }
12495
12496        boolean uninstallBlocked = false;
12497        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12498            int[] users = sUserManager.getUserIds();
12499            for (int i = 0; i < users.length; ++i) {
12500                if (getBlockUninstallForUser(packageName, users[i])) {
12501                    uninstallBlocked = true;
12502                    break;
12503                }
12504            }
12505        } else {
12506            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12507        }
12508        if (uninstallBlocked) {
12509            try {
12510                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12511                        null);
12512            } catch (RemoteException re) {
12513            }
12514            return;
12515        }
12516
12517        if (DEBUG_REMOVE) {
12518            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12519        }
12520        // Queue up an async operation since the package deletion may take a little while.
12521        mHandler.post(new Runnable() {
12522            public void run() {
12523                mHandler.removeCallbacks(this);
12524                final int returnCode = deletePackageX(packageName, userId, flags);
12525                if (observer != null) {
12526                    try {
12527                        observer.onPackageDeleted(packageName, returnCode, null);
12528                    } catch (RemoteException e) {
12529                        Log.i(TAG, "Observer no longer exists.");
12530                    } //end catch
12531                } //end if
12532            } //end run
12533        });
12534    }
12535
12536    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12537        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12538                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12539        try {
12540            if (dpm != null) {
12541                if (dpm.isDeviceOwner(packageName)) {
12542                    return true;
12543                }
12544                int[] users;
12545                if (userId == UserHandle.USER_ALL) {
12546                    users = sUserManager.getUserIds();
12547                } else {
12548                    users = new int[]{userId};
12549                }
12550                for (int i = 0; i < users.length; ++i) {
12551                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12552                        return true;
12553                    }
12554                }
12555            }
12556        } catch (RemoteException e) {
12557        }
12558        return false;
12559    }
12560
12561    /**
12562     *  This method is an internal method that could be get invoked either
12563     *  to delete an installed package or to clean up a failed installation.
12564     *  After deleting an installed package, a broadcast is sent to notify any
12565     *  listeners that the package has been installed. For cleaning up a failed
12566     *  installation, the broadcast is not necessary since the package's
12567     *  installation wouldn't have sent the initial broadcast either
12568     *  The key steps in deleting a package are
12569     *  deleting the package information in internal structures like mPackages,
12570     *  deleting the packages base directories through installd
12571     *  updating mSettings to reflect current status
12572     *  persisting settings for later use
12573     *  sending a broadcast if necessary
12574     */
12575    private int deletePackageX(String packageName, int userId, int flags) {
12576        final PackageRemovedInfo info = new PackageRemovedInfo();
12577        final boolean res;
12578
12579        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12580                ? UserHandle.ALL : new UserHandle(userId);
12581
12582        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12583            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12584            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12585        }
12586
12587        boolean removedForAllUsers = false;
12588        boolean systemUpdate = false;
12589
12590        // for the uninstall-updates case and restricted profiles, remember the per-
12591        // userhandle installed state
12592        int[] allUsers;
12593        boolean[] perUserInstalled;
12594        synchronized (mPackages) {
12595            PackageSetting ps = mSettings.mPackages.get(packageName);
12596            allUsers = sUserManager.getUserIds();
12597            perUserInstalled = new boolean[allUsers.length];
12598            for (int i = 0; i < allUsers.length; i++) {
12599                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12600            }
12601        }
12602
12603        synchronized (mInstallLock) {
12604            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12605            res = deletePackageLI(packageName, removeForUser,
12606                    true, allUsers, perUserInstalled,
12607                    flags | REMOVE_CHATTY, info, true);
12608            systemUpdate = info.isRemovedPackageSystemUpdate;
12609            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12610                removedForAllUsers = true;
12611            }
12612            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12613                    + " removedForAllUsers=" + removedForAllUsers);
12614        }
12615
12616        if (res) {
12617            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12618
12619            // If the removed package was a system update, the old system package
12620            // was re-enabled; we need to broadcast this information
12621            if (systemUpdate) {
12622                Bundle extras = new Bundle(1);
12623                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12624                        ? info.removedAppId : info.uid);
12625                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12626
12627                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12628                        extras, null, null, null);
12629                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12630                        extras, null, null, null);
12631                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12632                        null, packageName, null, null);
12633            }
12634        }
12635        // Force a gc here.
12636        Runtime.getRuntime().gc();
12637        // Delete the resources here after sending the broadcast to let
12638        // other processes clean up before deleting resources.
12639        if (info.args != null) {
12640            synchronized (mInstallLock) {
12641                info.args.doPostDeleteLI(true);
12642            }
12643        }
12644
12645        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12646    }
12647
12648    class PackageRemovedInfo {
12649        String removedPackage;
12650        int uid = -1;
12651        int removedAppId = -1;
12652        int[] removedUsers = null;
12653        boolean isRemovedPackageSystemUpdate = false;
12654        // Clean up resources deleted packages.
12655        InstallArgs args = null;
12656
12657        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12658            Bundle extras = new Bundle(1);
12659            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12660            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12661            if (replacing) {
12662                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12663            }
12664            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12665            if (removedPackage != null) {
12666                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12667                        extras, null, null, removedUsers);
12668                if (fullRemove && !replacing) {
12669                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12670                            extras, null, null, removedUsers);
12671                }
12672            }
12673            if (removedAppId >= 0) {
12674                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12675                        removedUsers);
12676            }
12677        }
12678    }
12679
12680    /*
12681     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12682     * flag is not set, the data directory is removed as well.
12683     * make sure this flag is set for partially installed apps. If not its meaningless to
12684     * delete a partially installed application.
12685     */
12686    private void removePackageDataLI(PackageSetting ps,
12687            int[] allUserHandles, boolean[] perUserInstalled,
12688            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12689        String packageName = ps.name;
12690        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12691        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12692        // Retrieve object to delete permissions for shared user later on
12693        final PackageSetting deletedPs;
12694        // reader
12695        synchronized (mPackages) {
12696            deletedPs = mSettings.mPackages.get(packageName);
12697            if (outInfo != null) {
12698                outInfo.removedPackage = packageName;
12699                outInfo.removedUsers = deletedPs != null
12700                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12701                        : null;
12702            }
12703        }
12704        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12705            removeDataDirsLI(ps.volumeUuid, packageName);
12706            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12707        }
12708        // writer
12709        synchronized (mPackages) {
12710            if (deletedPs != null) {
12711                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12712                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12713                    clearDefaultBrowserIfNeeded(packageName);
12714                    if (outInfo != null) {
12715                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12716                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12717                    }
12718                    updatePermissionsLPw(deletedPs.name, null, 0);
12719                    if (deletedPs.sharedUser != null) {
12720                        // Remove permissions associated with package. Since runtime
12721                        // permissions are per user we have to kill the removed package
12722                        // or packages running under the shared user of the removed
12723                        // package if revoking the permissions requested only by the removed
12724                        // package is successful and this causes a change in gids.
12725                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12726                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12727                                    userId);
12728                            if (userIdToKill == UserHandle.USER_ALL
12729                                    || userIdToKill >= UserHandle.USER_OWNER) {
12730                                // If gids changed for this user, kill all affected packages.
12731                                mHandler.post(new Runnable() {
12732                                    @Override
12733                                    public void run() {
12734                                        // This has to happen with no lock held.
12735                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12736                                                KILL_APP_REASON_GIDS_CHANGED);
12737                                    }
12738                                });
12739                                break;
12740                            }
12741                        }
12742                    }
12743                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12744                }
12745                // make sure to preserve per-user disabled state if this removal was just
12746                // a downgrade of a system app to the factory package
12747                if (allUserHandles != null && perUserInstalled != null) {
12748                    if (DEBUG_REMOVE) {
12749                        Slog.d(TAG, "Propagating install state across downgrade");
12750                    }
12751                    for (int i = 0; i < allUserHandles.length; i++) {
12752                        if (DEBUG_REMOVE) {
12753                            Slog.d(TAG, "    user " + allUserHandles[i]
12754                                    + " => " + perUserInstalled[i]);
12755                        }
12756                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12757                    }
12758                }
12759            }
12760            // can downgrade to reader
12761            if (writeSettings) {
12762                // Save settings now
12763                mSettings.writeLPr();
12764            }
12765        }
12766        if (outInfo != null) {
12767            // A user ID was deleted here. Go through all users and remove it
12768            // from KeyStore.
12769            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12770        }
12771    }
12772
12773    static boolean locationIsPrivileged(File path) {
12774        try {
12775            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12776                    .getCanonicalPath();
12777            return path.getCanonicalPath().startsWith(privilegedAppDir);
12778        } catch (IOException e) {
12779            Slog.e(TAG, "Unable to access code path " + path);
12780        }
12781        return false;
12782    }
12783
12784    /*
12785     * Tries to delete system package.
12786     */
12787    private boolean deleteSystemPackageLI(PackageSetting newPs,
12788            int[] allUserHandles, boolean[] perUserInstalled,
12789            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12790        final boolean applyUserRestrictions
12791                = (allUserHandles != null) && (perUserInstalled != null);
12792        PackageSetting disabledPs = null;
12793        // Confirm if the system package has been updated
12794        // An updated system app can be deleted. This will also have to restore
12795        // the system pkg from system partition
12796        // reader
12797        synchronized (mPackages) {
12798            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12799        }
12800        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12801                + " disabledPs=" + disabledPs);
12802        if (disabledPs == null) {
12803            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12804            return false;
12805        } else if (DEBUG_REMOVE) {
12806            Slog.d(TAG, "Deleting system pkg from data partition");
12807        }
12808        if (DEBUG_REMOVE) {
12809            if (applyUserRestrictions) {
12810                Slog.d(TAG, "Remembering install states:");
12811                for (int i = 0; i < allUserHandles.length; i++) {
12812                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12813                }
12814            }
12815        }
12816        // Delete the updated package
12817        outInfo.isRemovedPackageSystemUpdate = true;
12818        if (disabledPs.versionCode < newPs.versionCode) {
12819            // Delete data for downgrades
12820            flags &= ~PackageManager.DELETE_KEEP_DATA;
12821        } else {
12822            // Preserve data by setting flag
12823            flags |= PackageManager.DELETE_KEEP_DATA;
12824        }
12825        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12826                allUserHandles, perUserInstalled, outInfo, writeSettings);
12827        if (!ret) {
12828            return false;
12829        }
12830        // writer
12831        synchronized (mPackages) {
12832            // Reinstate the old system package
12833            mSettings.enableSystemPackageLPw(newPs.name);
12834            // Remove any native libraries from the upgraded package.
12835            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12836        }
12837        // Install the system package
12838        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12839        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12840        if (locationIsPrivileged(disabledPs.codePath)) {
12841            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12842        }
12843
12844        final PackageParser.Package newPkg;
12845        try {
12846            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12847        } catch (PackageManagerException e) {
12848            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12849            return false;
12850        }
12851
12852        // writer
12853        synchronized (mPackages) {
12854            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12855
12856            // Propagate the permissions state as we do want to drop on the floor
12857            // runtime permissions. The update permissions method below will take
12858            // care of removing obsolete permissions and grant install permissions.
12859            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12860            updatePermissionsLPw(newPkg.packageName, newPkg,
12861                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12862
12863            if (applyUserRestrictions) {
12864                if (DEBUG_REMOVE) {
12865                    Slog.d(TAG, "Propagating install state across reinstall");
12866                }
12867                for (int i = 0; i < allUserHandles.length; i++) {
12868                    if (DEBUG_REMOVE) {
12869                        Slog.d(TAG, "    user " + allUserHandles[i]
12870                                + " => " + perUserInstalled[i]);
12871                    }
12872                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12873                }
12874                // Regardless of writeSettings we need to ensure that this restriction
12875                // state propagation is persisted
12876                mSettings.writeAllUsersPackageRestrictionsLPr();
12877            }
12878            // can downgrade to reader here
12879            if (writeSettings) {
12880                mSettings.writeLPr();
12881            }
12882        }
12883        return true;
12884    }
12885
12886    private boolean deleteInstalledPackageLI(PackageSetting ps,
12887            boolean deleteCodeAndResources, int flags,
12888            int[] allUserHandles, boolean[] perUserInstalled,
12889            PackageRemovedInfo outInfo, boolean writeSettings) {
12890        if (outInfo != null) {
12891            outInfo.uid = ps.appId;
12892        }
12893
12894        // Delete package data from internal structures and also remove data if flag is set
12895        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12896
12897        // Delete application code and resources
12898        if (deleteCodeAndResources && (outInfo != null)) {
12899            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12900                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12901            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12902        }
12903        return true;
12904    }
12905
12906    @Override
12907    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12908            int userId) {
12909        mContext.enforceCallingOrSelfPermission(
12910                android.Manifest.permission.DELETE_PACKAGES, null);
12911        synchronized (mPackages) {
12912            PackageSetting ps = mSettings.mPackages.get(packageName);
12913            if (ps == null) {
12914                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12915                return false;
12916            }
12917            if (!ps.getInstalled(userId)) {
12918                // Can't block uninstall for an app that is not installed or enabled.
12919                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12920                return false;
12921            }
12922            ps.setBlockUninstall(blockUninstall, userId);
12923            mSettings.writePackageRestrictionsLPr(userId);
12924        }
12925        return true;
12926    }
12927
12928    @Override
12929    public boolean getBlockUninstallForUser(String packageName, int userId) {
12930        synchronized (mPackages) {
12931            PackageSetting ps = mSettings.mPackages.get(packageName);
12932            if (ps == null) {
12933                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12934                return false;
12935            }
12936            return ps.getBlockUninstall(userId);
12937        }
12938    }
12939
12940    /*
12941     * This method handles package deletion in general
12942     */
12943    private boolean deletePackageLI(String packageName, UserHandle user,
12944            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12945            int flags, PackageRemovedInfo outInfo,
12946            boolean writeSettings) {
12947        if (packageName == null) {
12948            Slog.w(TAG, "Attempt to delete null packageName.");
12949            return false;
12950        }
12951        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12952        PackageSetting ps;
12953        boolean dataOnly = false;
12954        int removeUser = -1;
12955        int appId = -1;
12956        synchronized (mPackages) {
12957            ps = mSettings.mPackages.get(packageName);
12958            if (ps == null) {
12959                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12960                return false;
12961            }
12962            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12963                    && user.getIdentifier() != UserHandle.USER_ALL) {
12964                // The caller is asking that the package only be deleted for a single
12965                // user.  To do this, we just mark its uninstalled state and delete
12966                // its data.  If this is a system app, we only allow this to happen if
12967                // they have set the special DELETE_SYSTEM_APP which requests different
12968                // semantics than normal for uninstalling system apps.
12969                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12970                ps.setUserState(user.getIdentifier(),
12971                        COMPONENT_ENABLED_STATE_DEFAULT,
12972                        false, //installed
12973                        true,  //stopped
12974                        true,  //notLaunched
12975                        false, //hidden
12976                        null, null, null,
12977                        false, // blockUninstall
12978                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
12979                if (!isSystemApp(ps)) {
12980                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12981                        // Other user still have this package installed, so all
12982                        // we need to do is clear this user's data and save that
12983                        // it is uninstalled.
12984                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12985                        removeUser = user.getIdentifier();
12986                        appId = ps.appId;
12987                        scheduleWritePackageRestrictionsLocked(removeUser);
12988                    } else {
12989                        // We need to set it back to 'installed' so the uninstall
12990                        // broadcasts will be sent correctly.
12991                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12992                        ps.setInstalled(true, user.getIdentifier());
12993                    }
12994                } else {
12995                    // This is a system app, so we assume that the
12996                    // other users still have this package installed, so all
12997                    // we need to do is clear this user's data and save that
12998                    // it is uninstalled.
12999                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13000                    removeUser = user.getIdentifier();
13001                    appId = ps.appId;
13002                    scheduleWritePackageRestrictionsLocked(removeUser);
13003                }
13004            }
13005        }
13006
13007        if (removeUser >= 0) {
13008            // From above, we determined that we are deleting this only
13009            // for a single user.  Continue the work here.
13010            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13011            if (outInfo != null) {
13012                outInfo.removedPackage = packageName;
13013                outInfo.removedAppId = appId;
13014                outInfo.removedUsers = new int[] {removeUser};
13015            }
13016            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13017            removeKeystoreDataIfNeeded(removeUser, appId);
13018            schedulePackageCleaning(packageName, removeUser, false);
13019            synchronized (mPackages) {
13020                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13021                    scheduleWritePackageRestrictionsLocked(removeUser);
13022                }
13023                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13024            }
13025            return true;
13026        }
13027
13028        if (dataOnly) {
13029            // Delete application data first
13030            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13031            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13032            return true;
13033        }
13034
13035        boolean ret = false;
13036        if (isSystemApp(ps)) {
13037            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13038            // When an updated system application is deleted we delete the existing resources as well and
13039            // fall back to existing code in system partition
13040            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13041                    flags, outInfo, writeSettings);
13042        } else {
13043            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13044            // Kill application pre-emptively especially for apps on sd.
13045            killApplication(packageName, ps.appId, "uninstall pkg");
13046            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13047                    allUserHandles, perUserInstalled,
13048                    outInfo, writeSettings);
13049        }
13050
13051        return ret;
13052    }
13053
13054    private final class ClearStorageConnection implements ServiceConnection {
13055        IMediaContainerService mContainerService;
13056
13057        @Override
13058        public void onServiceConnected(ComponentName name, IBinder service) {
13059            synchronized (this) {
13060                mContainerService = IMediaContainerService.Stub.asInterface(service);
13061                notifyAll();
13062            }
13063        }
13064
13065        @Override
13066        public void onServiceDisconnected(ComponentName name) {
13067        }
13068    }
13069
13070    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13071        final boolean mounted;
13072        if (Environment.isExternalStorageEmulated()) {
13073            mounted = true;
13074        } else {
13075            final String status = Environment.getExternalStorageState();
13076
13077            mounted = status.equals(Environment.MEDIA_MOUNTED)
13078                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13079        }
13080
13081        if (!mounted) {
13082            return;
13083        }
13084
13085        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13086        int[] users;
13087        if (userId == UserHandle.USER_ALL) {
13088            users = sUserManager.getUserIds();
13089        } else {
13090            users = new int[] { userId };
13091        }
13092        final ClearStorageConnection conn = new ClearStorageConnection();
13093        if (mContext.bindServiceAsUser(
13094                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13095            try {
13096                for (int curUser : users) {
13097                    long timeout = SystemClock.uptimeMillis() + 5000;
13098                    synchronized (conn) {
13099                        long now = SystemClock.uptimeMillis();
13100                        while (conn.mContainerService == null && now < timeout) {
13101                            try {
13102                                conn.wait(timeout - now);
13103                            } catch (InterruptedException e) {
13104                            }
13105                        }
13106                    }
13107                    if (conn.mContainerService == null) {
13108                        return;
13109                    }
13110
13111                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13112                    clearDirectory(conn.mContainerService,
13113                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13114                    if (allData) {
13115                        clearDirectory(conn.mContainerService,
13116                                userEnv.buildExternalStorageAppDataDirs(packageName));
13117                        clearDirectory(conn.mContainerService,
13118                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13119                    }
13120                }
13121            } finally {
13122                mContext.unbindService(conn);
13123            }
13124        }
13125    }
13126
13127    @Override
13128    public void clearApplicationUserData(final String packageName,
13129            final IPackageDataObserver observer, final int userId) {
13130        mContext.enforceCallingOrSelfPermission(
13131                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13132        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13133        // Queue up an async operation since the package deletion may take a little while.
13134        mHandler.post(new Runnable() {
13135            public void run() {
13136                mHandler.removeCallbacks(this);
13137                final boolean succeeded;
13138                synchronized (mInstallLock) {
13139                    succeeded = clearApplicationUserDataLI(packageName, userId);
13140                }
13141                clearExternalStorageDataSync(packageName, userId, true);
13142                if (succeeded) {
13143                    // invoke DeviceStorageMonitor's update method to clear any notifications
13144                    DeviceStorageMonitorInternal
13145                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13146                    if (dsm != null) {
13147                        dsm.checkMemory();
13148                    }
13149                }
13150                if(observer != null) {
13151                    try {
13152                        observer.onRemoveCompleted(packageName, succeeded);
13153                    } catch (RemoteException e) {
13154                        Log.i(TAG, "Observer no longer exists.");
13155                    }
13156                } //end if observer
13157            } //end run
13158        });
13159    }
13160
13161    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13162        if (packageName == null) {
13163            Slog.w(TAG, "Attempt to delete null packageName.");
13164            return false;
13165        }
13166
13167        // Try finding details about the requested package
13168        PackageParser.Package pkg;
13169        synchronized (mPackages) {
13170            pkg = mPackages.get(packageName);
13171            if (pkg == null) {
13172                final PackageSetting ps = mSettings.mPackages.get(packageName);
13173                if (ps != null) {
13174                    pkg = ps.pkg;
13175                }
13176            }
13177
13178            if (pkg == null) {
13179                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13180                return false;
13181            }
13182
13183            PackageSetting ps = (PackageSetting) pkg.mExtras;
13184            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13185        }
13186
13187        // Always delete data directories for package, even if we found no other
13188        // record of app. This helps users recover from UID mismatches without
13189        // resorting to a full data wipe.
13190        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13191        if (retCode < 0) {
13192            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13193            return false;
13194        }
13195
13196        final int appId = pkg.applicationInfo.uid;
13197        removeKeystoreDataIfNeeded(userId, appId);
13198
13199        // Create a native library symlink only if we have native libraries
13200        // and if the native libraries are 32 bit libraries. We do not provide
13201        // this symlink for 64 bit libraries.
13202        if (pkg.applicationInfo.primaryCpuAbi != null &&
13203                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13204            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13205            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13206                    nativeLibPath, userId) < 0) {
13207                Slog.w(TAG, "Failed linking native library dir");
13208                return false;
13209            }
13210        }
13211
13212        return true;
13213    }
13214
13215    /**
13216     * Reverts user permission state changes (permissions and flags).
13217     *
13218     * @param ps The package for which to reset.
13219     * @param userId The device user for which to do a reset.
13220     */
13221    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13222            final PackageSetting ps, final int userId) {
13223        if (ps.pkg == null) {
13224            return;
13225        }
13226
13227        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13228                | FLAG_PERMISSION_USER_FIXED
13229                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13230
13231        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13232                | FLAG_PERMISSION_POLICY_FIXED;
13233
13234        boolean writeInstallPermissions = false;
13235        boolean writeRuntimePermissions = false;
13236
13237        final int permissionCount = ps.pkg.requestedPermissions.size();
13238        for (int i = 0; i < permissionCount; i++) {
13239            String permission = ps.pkg.requestedPermissions.get(i);
13240
13241            BasePermission bp = mSettings.mPermissions.get(permission);
13242            if (bp == null) {
13243                continue;
13244            }
13245
13246            // If shared user we just reset the state to which only this app contributed.
13247            if (ps.sharedUser != null) {
13248                boolean used = false;
13249                final int packageCount = ps.sharedUser.packages.size();
13250                for (int j = 0; j < packageCount; j++) {
13251                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13252                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13253                            && pkg.pkg.requestedPermissions.contains(permission)) {
13254                        used = true;
13255                        break;
13256                    }
13257                }
13258                if (used) {
13259                    continue;
13260                }
13261            }
13262
13263            PermissionsState permissionsState = ps.getPermissionsState();
13264
13265            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13266
13267            // Always clear the user settable flags.
13268            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13269                    bp.name) != null;
13270            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13271                if (hasInstallState) {
13272                    writeInstallPermissions = true;
13273                } else {
13274                    writeRuntimePermissions = true;
13275                }
13276            }
13277
13278            // Below is only runtime permission handling.
13279            if (!bp.isRuntime()) {
13280                continue;
13281            }
13282
13283            // Never clobber system or policy.
13284            if ((oldFlags & policyOrSystemFlags) != 0) {
13285                continue;
13286            }
13287
13288            // If this permission was granted by default, make sure it is.
13289            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13290                if (permissionsState.grantRuntimePermission(bp, userId)
13291                        != PERMISSION_OPERATION_FAILURE) {
13292                    writeRuntimePermissions = true;
13293                }
13294            } else {
13295                // Otherwise, reset the permission.
13296                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13297                switch (revokeResult) {
13298                    case PERMISSION_OPERATION_SUCCESS: {
13299                        writeRuntimePermissions = true;
13300                    } break;
13301
13302                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13303                        writeRuntimePermissions = true;
13304                        // If gids changed for this user, kill all affected packages.
13305                        mHandler.post(new Runnable() {
13306                            @Override
13307                            public void run() {
13308                                // This has to happen with no lock held.
13309                                killSettingPackagesForUser(ps, userId,
13310                                        KILL_APP_REASON_GIDS_CHANGED);
13311                            }
13312                        });
13313                    } break;
13314                }
13315            }
13316        }
13317
13318        // Synchronously write as we are taking permissions away.
13319        if (writeRuntimePermissions) {
13320            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13321        }
13322
13323        // Synchronously write as we are taking permissions away.
13324        if (writeInstallPermissions) {
13325            mSettings.writeLPr();
13326        }
13327    }
13328
13329    /**
13330     * Remove entries from the keystore daemon. Will only remove it if the
13331     * {@code appId} is valid.
13332     */
13333    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13334        if (appId < 0) {
13335            return;
13336        }
13337
13338        final KeyStore keyStore = KeyStore.getInstance();
13339        if (keyStore != null) {
13340            if (userId == UserHandle.USER_ALL) {
13341                for (final int individual : sUserManager.getUserIds()) {
13342                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13343                }
13344            } else {
13345                keyStore.clearUid(UserHandle.getUid(userId, appId));
13346            }
13347        } else {
13348            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13349        }
13350    }
13351
13352    @Override
13353    public void deleteApplicationCacheFiles(final String packageName,
13354            final IPackageDataObserver observer) {
13355        mContext.enforceCallingOrSelfPermission(
13356                android.Manifest.permission.DELETE_CACHE_FILES, null);
13357        // Queue up an async operation since the package deletion may take a little while.
13358        final int userId = UserHandle.getCallingUserId();
13359        mHandler.post(new Runnable() {
13360            public void run() {
13361                mHandler.removeCallbacks(this);
13362                final boolean succeded;
13363                synchronized (mInstallLock) {
13364                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13365                }
13366                clearExternalStorageDataSync(packageName, userId, false);
13367                if (observer != null) {
13368                    try {
13369                        observer.onRemoveCompleted(packageName, succeded);
13370                    } catch (RemoteException e) {
13371                        Log.i(TAG, "Observer no longer exists.");
13372                    }
13373                } //end if observer
13374            } //end run
13375        });
13376    }
13377
13378    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13379        if (packageName == null) {
13380            Slog.w(TAG, "Attempt to delete null packageName.");
13381            return false;
13382        }
13383        PackageParser.Package p;
13384        synchronized (mPackages) {
13385            p = mPackages.get(packageName);
13386        }
13387        if (p == null) {
13388            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13389            return false;
13390        }
13391        final ApplicationInfo applicationInfo = p.applicationInfo;
13392        if (applicationInfo == null) {
13393            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13394            return false;
13395        }
13396        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13397        if (retCode < 0) {
13398            Slog.w(TAG, "Couldn't remove cache files for package: "
13399                       + packageName + " u" + userId);
13400            return false;
13401        }
13402        return true;
13403    }
13404
13405    @Override
13406    public void getPackageSizeInfo(final String packageName, int userHandle,
13407            final IPackageStatsObserver observer) {
13408        mContext.enforceCallingOrSelfPermission(
13409                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13410        if (packageName == null) {
13411            throw new IllegalArgumentException("Attempt to get size of null packageName");
13412        }
13413
13414        PackageStats stats = new PackageStats(packageName, userHandle);
13415
13416        /*
13417         * Queue up an async operation since the package measurement may take a
13418         * little while.
13419         */
13420        Message msg = mHandler.obtainMessage(INIT_COPY);
13421        msg.obj = new MeasureParams(stats, observer);
13422        mHandler.sendMessage(msg);
13423    }
13424
13425    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13426            PackageStats pStats) {
13427        if (packageName == null) {
13428            Slog.w(TAG, "Attempt to get size of null packageName.");
13429            return false;
13430        }
13431        PackageParser.Package p;
13432        boolean dataOnly = false;
13433        String libDirRoot = null;
13434        String asecPath = null;
13435        PackageSetting ps = null;
13436        synchronized (mPackages) {
13437            p = mPackages.get(packageName);
13438            ps = mSettings.mPackages.get(packageName);
13439            if(p == null) {
13440                dataOnly = true;
13441                if((ps == null) || (ps.pkg == null)) {
13442                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13443                    return false;
13444                }
13445                p = ps.pkg;
13446            }
13447            if (ps != null) {
13448                libDirRoot = ps.legacyNativeLibraryPathString;
13449            }
13450            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13451                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13452                if (secureContainerId != null) {
13453                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13454                }
13455            }
13456        }
13457        String publicSrcDir = null;
13458        if(!dataOnly) {
13459            final ApplicationInfo applicationInfo = p.applicationInfo;
13460            if (applicationInfo == null) {
13461                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13462                return false;
13463            }
13464            if (p.isForwardLocked()) {
13465                publicSrcDir = applicationInfo.getBaseResourcePath();
13466            }
13467        }
13468        // TODO: extend to measure size of split APKs
13469        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13470        // not just the first level.
13471        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13472        // just the primary.
13473        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13474        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13475                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13476        if (res < 0) {
13477            return false;
13478        }
13479
13480        // Fix-up for forward-locked applications in ASEC containers.
13481        if (!isExternal(p)) {
13482            pStats.codeSize += pStats.externalCodeSize;
13483            pStats.externalCodeSize = 0L;
13484        }
13485
13486        return true;
13487    }
13488
13489
13490    @Override
13491    public void addPackageToPreferred(String packageName) {
13492        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13493    }
13494
13495    @Override
13496    public void removePackageFromPreferred(String packageName) {
13497        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13498    }
13499
13500    @Override
13501    public List<PackageInfo> getPreferredPackages(int flags) {
13502        return new ArrayList<PackageInfo>();
13503    }
13504
13505    private int getUidTargetSdkVersionLockedLPr(int uid) {
13506        Object obj = mSettings.getUserIdLPr(uid);
13507        if (obj instanceof SharedUserSetting) {
13508            final SharedUserSetting sus = (SharedUserSetting) obj;
13509            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13510            final Iterator<PackageSetting> it = sus.packages.iterator();
13511            while (it.hasNext()) {
13512                final PackageSetting ps = it.next();
13513                if (ps.pkg != null) {
13514                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13515                    if (v < vers) vers = v;
13516                }
13517            }
13518            return vers;
13519        } else if (obj instanceof PackageSetting) {
13520            final PackageSetting ps = (PackageSetting) obj;
13521            if (ps.pkg != null) {
13522                return ps.pkg.applicationInfo.targetSdkVersion;
13523            }
13524        }
13525        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13526    }
13527
13528    @Override
13529    public void addPreferredActivity(IntentFilter filter, int match,
13530            ComponentName[] set, ComponentName activity, int userId) {
13531        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13532                "Adding preferred");
13533    }
13534
13535    private void addPreferredActivityInternal(IntentFilter filter, int match,
13536            ComponentName[] set, ComponentName activity, boolean always, int userId,
13537            String opname) {
13538        // writer
13539        int callingUid = Binder.getCallingUid();
13540        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13541        if (filter.countActions() == 0) {
13542            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13543            return;
13544        }
13545        synchronized (mPackages) {
13546            if (mContext.checkCallingOrSelfPermission(
13547                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13548                    != PackageManager.PERMISSION_GRANTED) {
13549                if (getUidTargetSdkVersionLockedLPr(callingUid)
13550                        < Build.VERSION_CODES.FROYO) {
13551                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13552                            + callingUid);
13553                    return;
13554                }
13555                mContext.enforceCallingOrSelfPermission(
13556                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13557            }
13558
13559            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13560            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13561                    + userId + ":");
13562            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13563            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13564            scheduleWritePackageRestrictionsLocked(userId);
13565        }
13566    }
13567
13568    @Override
13569    public void replacePreferredActivity(IntentFilter filter, int match,
13570            ComponentName[] set, ComponentName activity, int userId) {
13571        if (filter.countActions() != 1) {
13572            throw new IllegalArgumentException(
13573                    "replacePreferredActivity expects filter to have only 1 action.");
13574        }
13575        if (filter.countDataAuthorities() != 0
13576                || filter.countDataPaths() != 0
13577                || filter.countDataSchemes() > 1
13578                || filter.countDataTypes() != 0) {
13579            throw new IllegalArgumentException(
13580                    "replacePreferredActivity expects filter to have no data authorities, " +
13581                    "paths, or types; and at most one scheme.");
13582        }
13583
13584        final int callingUid = Binder.getCallingUid();
13585        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13586        synchronized (mPackages) {
13587            if (mContext.checkCallingOrSelfPermission(
13588                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13589                    != PackageManager.PERMISSION_GRANTED) {
13590                if (getUidTargetSdkVersionLockedLPr(callingUid)
13591                        < Build.VERSION_CODES.FROYO) {
13592                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13593                            + Binder.getCallingUid());
13594                    return;
13595                }
13596                mContext.enforceCallingOrSelfPermission(
13597                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13598            }
13599
13600            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13601            if (pir != null) {
13602                // Get all of the existing entries that exactly match this filter.
13603                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13604                if (existing != null && existing.size() == 1) {
13605                    PreferredActivity cur = existing.get(0);
13606                    if (DEBUG_PREFERRED) {
13607                        Slog.i(TAG, "Checking replace of preferred:");
13608                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13609                        if (!cur.mPref.mAlways) {
13610                            Slog.i(TAG, "  -- CUR; not mAlways!");
13611                        } else {
13612                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13613                            Slog.i(TAG, "  -- CUR: mSet="
13614                                    + Arrays.toString(cur.mPref.mSetComponents));
13615                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13616                            Slog.i(TAG, "  -- NEW: mMatch="
13617                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13618                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13619                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13620                        }
13621                    }
13622                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13623                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13624                            && cur.mPref.sameSet(set)) {
13625                        // Setting the preferred activity to what it happens to be already
13626                        if (DEBUG_PREFERRED) {
13627                            Slog.i(TAG, "Replacing with same preferred activity "
13628                                    + cur.mPref.mShortComponent + " for user "
13629                                    + userId + ":");
13630                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13631                        }
13632                        return;
13633                    }
13634                }
13635
13636                if (existing != null) {
13637                    if (DEBUG_PREFERRED) {
13638                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13639                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13640                    }
13641                    for (int i = 0; i < existing.size(); i++) {
13642                        PreferredActivity pa = existing.get(i);
13643                        if (DEBUG_PREFERRED) {
13644                            Slog.i(TAG, "Removing existing preferred activity "
13645                                    + pa.mPref.mComponent + ":");
13646                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13647                        }
13648                        pir.removeFilter(pa);
13649                    }
13650                }
13651            }
13652            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13653                    "Replacing preferred");
13654        }
13655    }
13656
13657    @Override
13658    public void clearPackagePreferredActivities(String packageName) {
13659        final int uid = Binder.getCallingUid();
13660        // writer
13661        synchronized (mPackages) {
13662            PackageParser.Package pkg = mPackages.get(packageName);
13663            if (pkg == null || pkg.applicationInfo.uid != uid) {
13664                if (mContext.checkCallingOrSelfPermission(
13665                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13666                        != PackageManager.PERMISSION_GRANTED) {
13667                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13668                            < Build.VERSION_CODES.FROYO) {
13669                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13670                                + Binder.getCallingUid());
13671                        return;
13672                    }
13673                    mContext.enforceCallingOrSelfPermission(
13674                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13675                }
13676            }
13677
13678            int user = UserHandle.getCallingUserId();
13679            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13680                scheduleWritePackageRestrictionsLocked(user);
13681            }
13682        }
13683    }
13684
13685    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13686    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13687        ArrayList<PreferredActivity> removed = null;
13688        boolean changed = false;
13689        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13690            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13691            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13692            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13693                continue;
13694            }
13695            Iterator<PreferredActivity> it = pir.filterIterator();
13696            while (it.hasNext()) {
13697                PreferredActivity pa = it.next();
13698                // Mark entry for removal only if it matches the package name
13699                // and the entry is of type "always".
13700                if (packageName == null ||
13701                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13702                                && pa.mPref.mAlways)) {
13703                    if (removed == null) {
13704                        removed = new ArrayList<PreferredActivity>();
13705                    }
13706                    removed.add(pa);
13707                }
13708            }
13709            if (removed != null) {
13710                for (int j=0; j<removed.size(); j++) {
13711                    PreferredActivity pa = removed.get(j);
13712                    pir.removeFilter(pa);
13713                }
13714                changed = true;
13715            }
13716        }
13717        return changed;
13718    }
13719
13720    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13721    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13722        if (userId == UserHandle.USER_ALL) {
13723            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13724                    sUserManager.getUserIds())) {
13725                for (int oneUserId : sUserManager.getUserIds()) {
13726                    scheduleWritePackageRestrictionsLocked(oneUserId);
13727                }
13728            }
13729        } else {
13730            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13731                scheduleWritePackageRestrictionsLocked(userId);
13732            }
13733        }
13734    }
13735
13736
13737    void clearDefaultBrowserIfNeeded(String packageName) {
13738        for (int oneUserId : sUserManager.getUserIds()) {
13739            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13740            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13741            if (packageName.equals(defaultBrowserPackageName)) {
13742                setDefaultBrowserPackageName(null, oneUserId);
13743            }
13744        }
13745    }
13746
13747    @Override
13748    public void resetPreferredActivities(int userId) {
13749        mContext.enforceCallingOrSelfPermission(
13750                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13751        // writer
13752        synchronized (mPackages) {
13753            clearPackagePreferredActivitiesLPw(null, userId);
13754            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13755            applyFactoryDefaultBrowserLPw(userId);
13756            primeDomainVerificationsLPw(userId);
13757
13758            scheduleWritePackageRestrictionsLocked(userId);
13759        }
13760    }
13761
13762    @Override
13763    public int getPreferredActivities(List<IntentFilter> outFilters,
13764            List<ComponentName> outActivities, String packageName) {
13765
13766        int num = 0;
13767        final int userId = UserHandle.getCallingUserId();
13768        // reader
13769        synchronized (mPackages) {
13770            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13771            if (pir != null) {
13772                final Iterator<PreferredActivity> it = pir.filterIterator();
13773                while (it.hasNext()) {
13774                    final PreferredActivity pa = it.next();
13775                    if (packageName == null
13776                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13777                                    && pa.mPref.mAlways)) {
13778                        if (outFilters != null) {
13779                            outFilters.add(new IntentFilter(pa));
13780                        }
13781                        if (outActivities != null) {
13782                            outActivities.add(pa.mPref.mComponent);
13783                        }
13784                    }
13785                }
13786            }
13787        }
13788
13789        return num;
13790    }
13791
13792    @Override
13793    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13794            int userId) {
13795        int callingUid = Binder.getCallingUid();
13796        if (callingUid != Process.SYSTEM_UID) {
13797            throw new SecurityException(
13798                    "addPersistentPreferredActivity can only be run by the system");
13799        }
13800        if (filter.countActions() == 0) {
13801            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13802            return;
13803        }
13804        synchronized (mPackages) {
13805            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13806                    " :");
13807            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13808            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13809                    new PersistentPreferredActivity(filter, activity));
13810            scheduleWritePackageRestrictionsLocked(userId);
13811        }
13812    }
13813
13814    @Override
13815    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13816        int callingUid = Binder.getCallingUid();
13817        if (callingUid != Process.SYSTEM_UID) {
13818            throw new SecurityException(
13819                    "clearPackagePersistentPreferredActivities can only be run by the system");
13820        }
13821        ArrayList<PersistentPreferredActivity> removed = null;
13822        boolean changed = false;
13823        synchronized (mPackages) {
13824            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13825                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13826                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13827                        .valueAt(i);
13828                if (userId != thisUserId) {
13829                    continue;
13830                }
13831                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13832                while (it.hasNext()) {
13833                    PersistentPreferredActivity ppa = it.next();
13834                    // Mark entry for removal only if it matches the package name.
13835                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13836                        if (removed == null) {
13837                            removed = new ArrayList<PersistentPreferredActivity>();
13838                        }
13839                        removed.add(ppa);
13840                    }
13841                }
13842                if (removed != null) {
13843                    for (int j=0; j<removed.size(); j++) {
13844                        PersistentPreferredActivity ppa = removed.get(j);
13845                        ppir.removeFilter(ppa);
13846                    }
13847                    changed = true;
13848                }
13849            }
13850
13851            if (changed) {
13852                scheduleWritePackageRestrictionsLocked(userId);
13853            }
13854        }
13855    }
13856
13857    /**
13858     * Common machinery for picking apart a restored XML blob and passing
13859     * it to a caller-supplied functor to be applied to the running system.
13860     */
13861    private void restoreFromXml(XmlPullParser parser, int userId,
13862            String expectedStartTag, BlobXmlRestorer functor)
13863            throws IOException, XmlPullParserException {
13864        int type;
13865        while ((type = parser.next()) != XmlPullParser.START_TAG
13866                && type != XmlPullParser.END_DOCUMENT) {
13867        }
13868        if (type != XmlPullParser.START_TAG) {
13869            // oops didn't find a start tag?!
13870            if (DEBUG_BACKUP) {
13871                Slog.e(TAG, "Didn't find start tag during restore");
13872            }
13873            return;
13874        }
13875
13876        // this is supposed to be TAG_PREFERRED_BACKUP
13877        if (!expectedStartTag.equals(parser.getName())) {
13878            if (DEBUG_BACKUP) {
13879                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13880            }
13881            return;
13882        }
13883
13884        // skip interfering stuff, then we're aligned with the backing implementation
13885        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13886        functor.apply(parser, userId);
13887    }
13888
13889    private interface BlobXmlRestorer {
13890        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13891    }
13892
13893    /**
13894     * Non-Binder method, support for the backup/restore mechanism: write the
13895     * full set of preferred activities in its canonical XML format.  Returns the
13896     * XML output as a byte array, or null if there is none.
13897     */
13898    @Override
13899    public byte[] getPreferredActivityBackup(int userId) {
13900        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13901            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13902        }
13903
13904        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13905        try {
13906            final XmlSerializer serializer = new FastXmlSerializer();
13907            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13908            serializer.startDocument(null, true);
13909            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13910
13911            synchronized (mPackages) {
13912                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13913            }
13914
13915            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13916            serializer.endDocument();
13917            serializer.flush();
13918        } catch (Exception e) {
13919            if (DEBUG_BACKUP) {
13920                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13921            }
13922            return null;
13923        }
13924
13925        return dataStream.toByteArray();
13926    }
13927
13928    @Override
13929    public void restorePreferredActivities(byte[] backup, int userId) {
13930        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13931            throw new SecurityException("Only the system may call restorePreferredActivities()");
13932        }
13933
13934        try {
13935            final XmlPullParser parser = Xml.newPullParser();
13936            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13937            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13938                    new BlobXmlRestorer() {
13939                        @Override
13940                        public void apply(XmlPullParser parser, int userId)
13941                                throws XmlPullParserException, IOException {
13942                            synchronized (mPackages) {
13943                                mSettings.readPreferredActivitiesLPw(parser, userId);
13944                            }
13945                        }
13946                    } );
13947        } catch (Exception e) {
13948            if (DEBUG_BACKUP) {
13949                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13950            }
13951        }
13952    }
13953
13954    /**
13955     * Non-Binder method, support for the backup/restore mechanism: write the
13956     * default browser (etc) settings in its canonical XML format.  Returns the default
13957     * browser XML representation as a byte array, or null if there is none.
13958     */
13959    @Override
13960    public byte[] getDefaultAppsBackup(int userId) {
13961        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13962            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13963        }
13964
13965        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13966        try {
13967            final XmlSerializer serializer = new FastXmlSerializer();
13968            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13969            serializer.startDocument(null, true);
13970            serializer.startTag(null, TAG_DEFAULT_APPS);
13971
13972            synchronized (mPackages) {
13973                mSettings.writeDefaultAppsLPr(serializer, userId);
13974            }
13975
13976            serializer.endTag(null, TAG_DEFAULT_APPS);
13977            serializer.endDocument();
13978            serializer.flush();
13979        } catch (Exception e) {
13980            if (DEBUG_BACKUP) {
13981                Slog.e(TAG, "Unable to write default apps for backup", e);
13982            }
13983            return null;
13984        }
13985
13986        return dataStream.toByteArray();
13987    }
13988
13989    @Override
13990    public void restoreDefaultApps(byte[] backup, int userId) {
13991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13992            throw new SecurityException("Only the system may call restoreDefaultApps()");
13993        }
13994
13995        try {
13996            final XmlPullParser parser = Xml.newPullParser();
13997            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13998            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13999                    new BlobXmlRestorer() {
14000                        @Override
14001                        public void apply(XmlPullParser parser, int userId)
14002                                throws XmlPullParserException, IOException {
14003                            synchronized (mPackages) {
14004                                mSettings.readDefaultAppsLPw(parser, userId);
14005                            }
14006                        }
14007                    } );
14008        } catch (Exception e) {
14009            if (DEBUG_BACKUP) {
14010                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14011            }
14012        }
14013    }
14014
14015    @Override
14016    public byte[] getIntentFilterVerificationBackup(int userId) {
14017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14018            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14019        }
14020
14021        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14022        try {
14023            final XmlSerializer serializer = new FastXmlSerializer();
14024            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14025            serializer.startDocument(null, true);
14026            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14027
14028            synchronized (mPackages) {
14029                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14030            }
14031
14032            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14033            serializer.endDocument();
14034            serializer.flush();
14035        } catch (Exception e) {
14036            if (DEBUG_BACKUP) {
14037                Slog.e(TAG, "Unable to write default apps for backup", e);
14038            }
14039            return null;
14040        }
14041
14042        return dataStream.toByteArray();
14043    }
14044
14045    @Override
14046    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14047        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14048            throw new SecurityException("Only the system may call restorePreferredActivities()");
14049        }
14050
14051        try {
14052            final XmlPullParser parser = Xml.newPullParser();
14053            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14054            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14055                    new BlobXmlRestorer() {
14056                        @Override
14057                        public void apply(XmlPullParser parser, int userId)
14058                                throws XmlPullParserException, IOException {
14059                            synchronized (mPackages) {
14060                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14061                                mSettings.writeLPr();
14062                            }
14063                        }
14064                    } );
14065        } catch (Exception e) {
14066            if (DEBUG_BACKUP) {
14067                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14068            }
14069        }
14070    }
14071
14072    @Override
14073    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14074            int sourceUserId, int targetUserId, int flags) {
14075        mContext.enforceCallingOrSelfPermission(
14076                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14077        int callingUid = Binder.getCallingUid();
14078        enforceOwnerRights(ownerPackage, callingUid);
14079        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14080        if (intentFilter.countActions() == 0) {
14081            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14082            return;
14083        }
14084        synchronized (mPackages) {
14085            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14086                    ownerPackage, targetUserId, flags);
14087            CrossProfileIntentResolver resolver =
14088                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14089            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14090            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14091            if (existing != null) {
14092                int size = existing.size();
14093                for (int i = 0; i < size; i++) {
14094                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14095                        return;
14096                    }
14097                }
14098            }
14099            resolver.addFilter(newFilter);
14100            scheduleWritePackageRestrictionsLocked(sourceUserId);
14101        }
14102    }
14103
14104    @Override
14105    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14106        mContext.enforceCallingOrSelfPermission(
14107                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14108        int callingUid = Binder.getCallingUid();
14109        enforceOwnerRights(ownerPackage, callingUid);
14110        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14111        synchronized (mPackages) {
14112            CrossProfileIntentResolver resolver =
14113                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14114            ArraySet<CrossProfileIntentFilter> set =
14115                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14116            for (CrossProfileIntentFilter filter : set) {
14117                if (filter.getOwnerPackage().equals(ownerPackage)) {
14118                    resolver.removeFilter(filter);
14119                }
14120            }
14121            scheduleWritePackageRestrictionsLocked(sourceUserId);
14122        }
14123    }
14124
14125    // Enforcing that callingUid is owning pkg on userId
14126    private void enforceOwnerRights(String pkg, int callingUid) {
14127        // The system owns everything.
14128        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14129            return;
14130        }
14131        int callingUserId = UserHandle.getUserId(callingUid);
14132        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14133        if (pi == null) {
14134            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14135                    + callingUserId);
14136        }
14137        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14138            throw new SecurityException("Calling uid " + callingUid
14139                    + " does not own package " + pkg);
14140        }
14141    }
14142
14143    @Override
14144    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14145        Intent intent = new Intent(Intent.ACTION_MAIN);
14146        intent.addCategory(Intent.CATEGORY_HOME);
14147
14148        final int callingUserId = UserHandle.getCallingUserId();
14149        List<ResolveInfo> list = queryIntentActivities(intent, null,
14150                PackageManager.GET_META_DATA, callingUserId);
14151        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14152                true, false, false, callingUserId);
14153
14154        allHomeCandidates.clear();
14155        if (list != null) {
14156            for (ResolveInfo ri : list) {
14157                allHomeCandidates.add(ri);
14158            }
14159        }
14160        return (preferred == null || preferred.activityInfo == null)
14161                ? null
14162                : new ComponentName(preferred.activityInfo.packageName,
14163                        preferred.activityInfo.name);
14164    }
14165
14166    @Override
14167    public void setApplicationEnabledSetting(String appPackageName,
14168            int newState, int flags, int userId, String callingPackage) {
14169        if (!sUserManager.exists(userId)) return;
14170        if (callingPackage == null) {
14171            callingPackage = Integer.toString(Binder.getCallingUid());
14172        }
14173        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14174    }
14175
14176    @Override
14177    public void setComponentEnabledSetting(ComponentName componentName,
14178            int newState, int flags, int userId) {
14179        if (!sUserManager.exists(userId)) return;
14180        setEnabledSetting(componentName.getPackageName(),
14181                componentName.getClassName(), newState, flags, userId, null);
14182    }
14183
14184    private void setEnabledSetting(final String packageName, String className, int newState,
14185            final int flags, int userId, String callingPackage) {
14186        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14187              || newState == COMPONENT_ENABLED_STATE_ENABLED
14188              || newState == COMPONENT_ENABLED_STATE_DISABLED
14189              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14190              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14191            throw new IllegalArgumentException("Invalid new component state: "
14192                    + newState);
14193        }
14194        PackageSetting pkgSetting;
14195        final int uid = Binder.getCallingUid();
14196        final int permission = mContext.checkCallingOrSelfPermission(
14197                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14198        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14199        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14200        boolean sendNow = false;
14201        boolean isApp = (className == null);
14202        String componentName = isApp ? packageName : className;
14203        int packageUid = -1;
14204        ArrayList<String> components;
14205
14206        // writer
14207        synchronized (mPackages) {
14208            pkgSetting = mSettings.mPackages.get(packageName);
14209            if (pkgSetting == null) {
14210                if (className == null) {
14211                    throw new IllegalArgumentException(
14212                            "Unknown package: " + packageName);
14213                }
14214                throw new IllegalArgumentException(
14215                        "Unknown component: " + packageName
14216                        + "/" + className);
14217            }
14218            // Allow root and verify that userId is not being specified by a different user
14219            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14220                throw new SecurityException(
14221                        "Permission Denial: attempt to change component state from pid="
14222                        + Binder.getCallingPid()
14223                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14224            }
14225            if (className == null) {
14226                // We're dealing with an application/package level state change
14227                if (pkgSetting.getEnabled(userId) == newState) {
14228                    // Nothing to do
14229                    return;
14230                }
14231                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14232                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14233                    // Don't care about who enables an app.
14234                    callingPackage = null;
14235                }
14236                pkgSetting.setEnabled(newState, userId, callingPackage);
14237                // pkgSetting.pkg.mSetEnabled = newState;
14238            } else {
14239                // We're dealing with a component level state change
14240                // First, verify that this is a valid class name.
14241                PackageParser.Package pkg = pkgSetting.pkg;
14242                if (pkg == null || !pkg.hasComponentClassName(className)) {
14243                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14244                        throw new IllegalArgumentException("Component class " + className
14245                                + " does not exist in " + packageName);
14246                    } else {
14247                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14248                                + className + " does not exist in " + packageName);
14249                    }
14250                }
14251                switch (newState) {
14252                case COMPONENT_ENABLED_STATE_ENABLED:
14253                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14254                        return;
14255                    }
14256                    break;
14257                case COMPONENT_ENABLED_STATE_DISABLED:
14258                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14259                        return;
14260                    }
14261                    break;
14262                case COMPONENT_ENABLED_STATE_DEFAULT:
14263                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14264                        return;
14265                    }
14266                    break;
14267                default:
14268                    Slog.e(TAG, "Invalid new component state: " + newState);
14269                    return;
14270                }
14271            }
14272            scheduleWritePackageRestrictionsLocked(userId);
14273            components = mPendingBroadcasts.get(userId, packageName);
14274            final boolean newPackage = components == null;
14275            if (newPackage) {
14276                components = new ArrayList<String>();
14277            }
14278            if (!components.contains(componentName)) {
14279                components.add(componentName);
14280            }
14281            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14282                sendNow = true;
14283                // Purge entry from pending broadcast list if another one exists already
14284                // since we are sending one right away.
14285                mPendingBroadcasts.remove(userId, packageName);
14286            } else {
14287                if (newPackage) {
14288                    mPendingBroadcasts.put(userId, packageName, components);
14289                }
14290                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14291                    // Schedule a message
14292                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14293                }
14294            }
14295        }
14296
14297        long callingId = Binder.clearCallingIdentity();
14298        try {
14299            if (sendNow) {
14300                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14301                sendPackageChangedBroadcast(packageName,
14302                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14303            }
14304        } finally {
14305            Binder.restoreCallingIdentity(callingId);
14306        }
14307    }
14308
14309    private void sendPackageChangedBroadcast(String packageName,
14310            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14311        if (DEBUG_INSTALL)
14312            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14313                    + componentNames);
14314        Bundle extras = new Bundle(4);
14315        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14316        String nameList[] = new String[componentNames.size()];
14317        componentNames.toArray(nameList);
14318        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14319        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14320        extras.putInt(Intent.EXTRA_UID, packageUid);
14321        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14322                new int[] {UserHandle.getUserId(packageUid)});
14323    }
14324
14325    @Override
14326    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14327        if (!sUserManager.exists(userId)) return;
14328        final int uid = Binder.getCallingUid();
14329        final int permission = mContext.checkCallingOrSelfPermission(
14330                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14331        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14332        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14333        // writer
14334        synchronized (mPackages) {
14335            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14336                    allowedByPermission, uid, userId)) {
14337                scheduleWritePackageRestrictionsLocked(userId);
14338            }
14339        }
14340    }
14341
14342    @Override
14343    public String getInstallerPackageName(String packageName) {
14344        // reader
14345        synchronized (mPackages) {
14346            return mSettings.getInstallerPackageNameLPr(packageName);
14347        }
14348    }
14349
14350    @Override
14351    public int getApplicationEnabledSetting(String packageName, int userId) {
14352        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14353        int uid = Binder.getCallingUid();
14354        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14355        // reader
14356        synchronized (mPackages) {
14357            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14358        }
14359    }
14360
14361    @Override
14362    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14363        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14364        int uid = Binder.getCallingUid();
14365        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14366        // reader
14367        synchronized (mPackages) {
14368            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14369        }
14370    }
14371
14372    @Override
14373    public void enterSafeMode() {
14374        enforceSystemOrRoot("Only the system can request entering safe mode");
14375
14376        if (!mSystemReady) {
14377            mSafeMode = true;
14378        }
14379    }
14380
14381    @Override
14382    public void systemReady() {
14383        mSystemReady = true;
14384
14385        // Read the compatibilty setting when the system is ready.
14386        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14387                mContext.getContentResolver(),
14388                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14389        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14390        if (DEBUG_SETTINGS) {
14391            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14392        }
14393
14394        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14395
14396        synchronized (mPackages) {
14397            // Verify that all of the preferred activity components actually
14398            // exist.  It is possible for applications to be updated and at
14399            // that point remove a previously declared activity component that
14400            // had been set as a preferred activity.  We try to clean this up
14401            // the next time we encounter that preferred activity, but it is
14402            // possible for the user flow to never be able to return to that
14403            // situation so here we do a sanity check to make sure we haven't
14404            // left any junk around.
14405            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14406            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14407                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14408                removed.clear();
14409                for (PreferredActivity pa : pir.filterSet()) {
14410                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14411                        removed.add(pa);
14412                    }
14413                }
14414                if (removed.size() > 0) {
14415                    for (int r=0; r<removed.size(); r++) {
14416                        PreferredActivity pa = removed.get(r);
14417                        Slog.w(TAG, "Removing dangling preferred activity: "
14418                                + pa.mPref.mComponent);
14419                        pir.removeFilter(pa);
14420                    }
14421                    mSettings.writePackageRestrictionsLPr(
14422                            mSettings.mPreferredActivities.keyAt(i));
14423                }
14424            }
14425
14426            for (int userId : UserManagerService.getInstance().getUserIds()) {
14427                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14428                    grantPermissionsUserIds = ArrayUtils.appendInt(
14429                            grantPermissionsUserIds, userId);
14430                }
14431            }
14432        }
14433        sUserManager.systemReady();
14434
14435        // If we upgraded grant all default permissions before kicking off.
14436        for (int userId : grantPermissionsUserIds) {
14437            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14438        }
14439
14440        // Kick off any messages waiting for system ready
14441        if (mPostSystemReadyMessages != null) {
14442            for (Message msg : mPostSystemReadyMessages) {
14443                msg.sendToTarget();
14444            }
14445            mPostSystemReadyMessages = null;
14446        }
14447
14448        // Watch for external volumes that come and go over time
14449        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14450        storage.registerListener(mStorageListener);
14451
14452        mInstallerService.systemReady();
14453        mPackageDexOptimizer.systemReady();
14454
14455        MountServiceInternal mountServiceInternal = LocalServices.getService(
14456                MountServiceInternal.class);
14457        mountServiceInternal.addExternalStoragePolicy(
14458                new MountServiceInternal.ExternalStorageMountPolicy() {
14459            @Override
14460            public int getMountMode(int uid, String packageName) {
14461                if (Process.isIsolated(uid)) {
14462                    return Zygote.MOUNT_EXTERNAL_NONE;
14463                }
14464                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14465                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14466                }
14467                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14468                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14469                }
14470                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14471                    return Zygote.MOUNT_EXTERNAL_READ;
14472                }
14473                return Zygote.MOUNT_EXTERNAL_WRITE;
14474            }
14475
14476            @Override
14477            public boolean hasExternalStorage(int uid, String packageName) {
14478                return true;
14479            }
14480        });
14481    }
14482
14483    @Override
14484    public boolean isSafeMode() {
14485        return mSafeMode;
14486    }
14487
14488    @Override
14489    public boolean hasSystemUidErrors() {
14490        return mHasSystemUidErrors;
14491    }
14492
14493    static String arrayToString(int[] array) {
14494        StringBuffer buf = new StringBuffer(128);
14495        buf.append('[');
14496        if (array != null) {
14497            for (int i=0; i<array.length; i++) {
14498                if (i > 0) buf.append(", ");
14499                buf.append(array[i]);
14500            }
14501        }
14502        buf.append(']');
14503        return buf.toString();
14504    }
14505
14506    static class DumpState {
14507        public static final int DUMP_LIBS = 1 << 0;
14508        public static final int DUMP_FEATURES = 1 << 1;
14509        public static final int DUMP_RESOLVERS = 1 << 2;
14510        public static final int DUMP_PERMISSIONS = 1 << 3;
14511        public static final int DUMP_PACKAGES = 1 << 4;
14512        public static final int DUMP_SHARED_USERS = 1 << 5;
14513        public static final int DUMP_MESSAGES = 1 << 6;
14514        public static final int DUMP_PROVIDERS = 1 << 7;
14515        public static final int DUMP_VERIFIERS = 1 << 8;
14516        public static final int DUMP_PREFERRED = 1 << 9;
14517        public static final int DUMP_PREFERRED_XML = 1 << 10;
14518        public static final int DUMP_KEYSETS = 1 << 11;
14519        public static final int DUMP_VERSION = 1 << 12;
14520        public static final int DUMP_INSTALLS = 1 << 13;
14521        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14522        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14523
14524        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14525
14526        private int mTypes;
14527
14528        private int mOptions;
14529
14530        private boolean mTitlePrinted;
14531
14532        private SharedUserSetting mSharedUser;
14533
14534        public boolean isDumping(int type) {
14535            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14536                return true;
14537            }
14538
14539            return (mTypes & type) != 0;
14540        }
14541
14542        public void setDump(int type) {
14543            mTypes |= type;
14544        }
14545
14546        public boolean isOptionEnabled(int option) {
14547            return (mOptions & option) != 0;
14548        }
14549
14550        public void setOptionEnabled(int option) {
14551            mOptions |= option;
14552        }
14553
14554        public boolean onTitlePrinted() {
14555            final boolean printed = mTitlePrinted;
14556            mTitlePrinted = true;
14557            return printed;
14558        }
14559
14560        public boolean getTitlePrinted() {
14561            return mTitlePrinted;
14562        }
14563
14564        public void setTitlePrinted(boolean enabled) {
14565            mTitlePrinted = enabled;
14566        }
14567
14568        public SharedUserSetting getSharedUser() {
14569            return mSharedUser;
14570        }
14571
14572        public void setSharedUser(SharedUserSetting user) {
14573            mSharedUser = user;
14574        }
14575    }
14576
14577    @Override
14578    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14579        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14580                != PackageManager.PERMISSION_GRANTED) {
14581            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14582                    + Binder.getCallingPid()
14583                    + ", uid=" + Binder.getCallingUid()
14584                    + " without permission "
14585                    + android.Manifest.permission.DUMP);
14586            return;
14587        }
14588
14589        DumpState dumpState = new DumpState();
14590        boolean fullPreferred = false;
14591        boolean checkin = false;
14592
14593        String packageName = null;
14594        ArraySet<String> permissionNames = null;
14595
14596        int opti = 0;
14597        while (opti < args.length) {
14598            String opt = args[opti];
14599            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14600                break;
14601            }
14602            opti++;
14603
14604            if ("-a".equals(opt)) {
14605                // Right now we only know how to print all.
14606            } else if ("-h".equals(opt)) {
14607                pw.println("Package manager dump options:");
14608                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14609                pw.println("    --checkin: dump for a checkin");
14610                pw.println("    -f: print details of intent filters");
14611                pw.println("    -h: print this help");
14612                pw.println("  cmd may be one of:");
14613                pw.println("    l[ibraries]: list known shared libraries");
14614                pw.println("    f[ibraries]: list device features");
14615                pw.println("    k[eysets]: print known keysets");
14616                pw.println("    r[esolvers]: dump intent resolvers");
14617                pw.println("    perm[issions]: dump permissions");
14618                pw.println("    permission [name ...]: dump declaration and use of given permission");
14619                pw.println("    pref[erred]: print preferred package settings");
14620                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14621                pw.println("    prov[iders]: dump content providers");
14622                pw.println("    p[ackages]: dump installed packages");
14623                pw.println("    s[hared-users]: dump shared user IDs");
14624                pw.println("    m[essages]: print collected runtime messages");
14625                pw.println("    v[erifiers]: print package verifier info");
14626                pw.println("    version: print database version info");
14627                pw.println("    write: write current settings now");
14628                pw.println("    <package.name>: info about given package");
14629                pw.println("    installs: details about install sessions");
14630                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14631                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14632                return;
14633            } else if ("--checkin".equals(opt)) {
14634                checkin = true;
14635            } else if ("-f".equals(opt)) {
14636                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14637            } else {
14638                pw.println("Unknown argument: " + opt + "; use -h for help");
14639            }
14640        }
14641
14642        // Is the caller requesting to dump a particular piece of data?
14643        if (opti < args.length) {
14644            String cmd = args[opti];
14645            opti++;
14646            // Is this a package name?
14647            if ("android".equals(cmd) || cmd.contains(".")) {
14648                packageName = cmd;
14649                // When dumping a single package, we always dump all of its
14650                // filter information since the amount of data will be reasonable.
14651                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14652            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14653                dumpState.setDump(DumpState.DUMP_LIBS);
14654            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14655                dumpState.setDump(DumpState.DUMP_FEATURES);
14656            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14657                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14658            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14659                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14660            } else if ("permission".equals(cmd)) {
14661                if (opti >= args.length) {
14662                    pw.println("Error: permission requires permission name");
14663                    return;
14664                }
14665                permissionNames = new ArraySet<>();
14666                while (opti < args.length) {
14667                    permissionNames.add(args[opti]);
14668                    opti++;
14669                }
14670                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14671                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14672            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14673                dumpState.setDump(DumpState.DUMP_PREFERRED);
14674            } else if ("preferred-xml".equals(cmd)) {
14675                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14676                if (opti < args.length && "--full".equals(args[opti])) {
14677                    fullPreferred = true;
14678                    opti++;
14679                }
14680            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14681                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14682            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14683                dumpState.setDump(DumpState.DUMP_PACKAGES);
14684            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14685                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14686            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14687                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14688            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14689                dumpState.setDump(DumpState.DUMP_MESSAGES);
14690            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14691                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14692            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14693                    || "intent-filter-verifiers".equals(cmd)) {
14694                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14695            } else if ("version".equals(cmd)) {
14696                dumpState.setDump(DumpState.DUMP_VERSION);
14697            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14698                dumpState.setDump(DumpState.DUMP_KEYSETS);
14699            } else if ("installs".equals(cmd)) {
14700                dumpState.setDump(DumpState.DUMP_INSTALLS);
14701            } else if ("write".equals(cmd)) {
14702                synchronized (mPackages) {
14703                    mSettings.writeLPr();
14704                    pw.println("Settings written.");
14705                    return;
14706                }
14707            }
14708        }
14709
14710        if (checkin) {
14711            pw.println("vers,1");
14712        }
14713
14714        // reader
14715        synchronized (mPackages) {
14716            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14717                if (!checkin) {
14718                    if (dumpState.onTitlePrinted())
14719                        pw.println();
14720                    pw.println("Database versions:");
14721                    pw.print("  SDK Version:");
14722                    pw.print(" internal=");
14723                    pw.print(mSettings.mInternalSdkPlatform);
14724                    pw.print(" external=");
14725                    pw.println(mSettings.mExternalSdkPlatform);
14726                    pw.print("  DB Version:");
14727                    pw.print(" internal=");
14728                    pw.print(mSettings.mInternalDatabaseVersion);
14729                    pw.print(" external=");
14730                    pw.println(mSettings.mExternalDatabaseVersion);
14731                }
14732            }
14733
14734            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14735                if (!checkin) {
14736                    if (dumpState.onTitlePrinted())
14737                        pw.println();
14738                    pw.println("Verifiers:");
14739                    pw.print("  Required: ");
14740                    pw.print(mRequiredVerifierPackage);
14741                    pw.print(" (uid=");
14742                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14743                    pw.println(")");
14744                } else if (mRequiredVerifierPackage != null) {
14745                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14746                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14747                }
14748            }
14749
14750            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14751                    packageName == null) {
14752                if (mIntentFilterVerifierComponent != null) {
14753                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14754                    if (!checkin) {
14755                        if (dumpState.onTitlePrinted())
14756                            pw.println();
14757                        pw.println("Intent Filter Verifier:");
14758                        pw.print("  Using: ");
14759                        pw.print(verifierPackageName);
14760                        pw.print(" (uid=");
14761                        pw.print(getPackageUid(verifierPackageName, 0));
14762                        pw.println(")");
14763                    } else if (verifierPackageName != null) {
14764                        pw.print("ifv,"); pw.print(verifierPackageName);
14765                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14766                    }
14767                } else {
14768                    pw.println();
14769                    pw.println("No Intent Filter Verifier available!");
14770                }
14771            }
14772
14773            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14774                boolean printedHeader = false;
14775                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14776                while (it.hasNext()) {
14777                    String name = it.next();
14778                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14779                    if (!checkin) {
14780                        if (!printedHeader) {
14781                            if (dumpState.onTitlePrinted())
14782                                pw.println();
14783                            pw.println("Libraries:");
14784                            printedHeader = true;
14785                        }
14786                        pw.print("  ");
14787                    } else {
14788                        pw.print("lib,");
14789                    }
14790                    pw.print(name);
14791                    if (!checkin) {
14792                        pw.print(" -> ");
14793                    }
14794                    if (ent.path != null) {
14795                        if (!checkin) {
14796                            pw.print("(jar) ");
14797                            pw.print(ent.path);
14798                        } else {
14799                            pw.print(",jar,");
14800                            pw.print(ent.path);
14801                        }
14802                    } else {
14803                        if (!checkin) {
14804                            pw.print("(apk) ");
14805                            pw.print(ent.apk);
14806                        } else {
14807                            pw.print(",apk,");
14808                            pw.print(ent.apk);
14809                        }
14810                    }
14811                    pw.println();
14812                }
14813            }
14814
14815            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14816                if (dumpState.onTitlePrinted())
14817                    pw.println();
14818                if (!checkin) {
14819                    pw.println("Features:");
14820                }
14821                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14822                while (it.hasNext()) {
14823                    String name = it.next();
14824                    if (!checkin) {
14825                        pw.print("  ");
14826                    } else {
14827                        pw.print("feat,");
14828                    }
14829                    pw.println(name);
14830                }
14831            }
14832
14833            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14834                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14835                        : "Activity Resolver Table:", "  ", packageName,
14836                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14837                    dumpState.setTitlePrinted(true);
14838                }
14839                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14840                        : "Receiver Resolver Table:", "  ", packageName,
14841                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14842                    dumpState.setTitlePrinted(true);
14843                }
14844                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14845                        : "Service Resolver Table:", "  ", packageName,
14846                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14847                    dumpState.setTitlePrinted(true);
14848                }
14849                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14850                        : "Provider Resolver Table:", "  ", packageName,
14851                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14852                    dumpState.setTitlePrinted(true);
14853                }
14854            }
14855
14856            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14857                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14858                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14859                    int user = mSettings.mPreferredActivities.keyAt(i);
14860                    if (pir.dump(pw,
14861                            dumpState.getTitlePrinted()
14862                                ? "\nPreferred Activities User " + user + ":"
14863                                : "Preferred Activities User " + user + ":", "  ",
14864                            packageName, true, false)) {
14865                        dumpState.setTitlePrinted(true);
14866                    }
14867                }
14868            }
14869
14870            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14871                pw.flush();
14872                FileOutputStream fout = new FileOutputStream(fd);
14873                BufferedOutputStream str = new BufferedOutputStream(fout);
14874                XmlSerializer serializer = new FastXmlSerializer();
14875                try {
14876                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14877                    serializer.startDocument(null, true);
14878                    serializer.setFeature(
14879                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14880                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14881                    serializer.endDocument();
14882                    serializer.flush();
14883                } catch (IllegalArgumentException e) {
14884                    pw.println("Failed writing: " + e);
14885                } catch (IllegalStateException e) {
14886                    pw.println("Failed writing: " + e);
14887                } catch (IOException e) {
14888                    pw.println("Failed writing: " + e);
14889                }
14890            }
14891
14892            if (!checkin
14893                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14894                    && packageName == null) {
14895                pw.println();
14896                int count = mSettings.mPackages.size();
14897                if (count == 0) {
14898                    pw.println("No applications!");
14899                    pw.println();
14900                } else {
14901                    final String prefix = "  ";
14902                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14903                    if (allPackageSettings.size() == 0) {
14904                        pw.println("No domain preferred apps!");
14905                        pw.println();
14906                    } else {
14907                        pw.println("App verification status:");
14908                        pw.println();
14909                        count = 0;
14910                        for (PackageSetting ps : allPackageSettings) {
14911                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14912                            if (ivi == null || ivi.getPackageName() == null) continue;
14913                            pw.println(prefix + "Package: " + ivi.getPackageName());
14914                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14915                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14916                            pw.println();
14917                            count++;
14918                        }
14919                        if (count == 0) {
14920                            pw.println(prefix + "No app verification established.");
14921                            pw.println();
14922                        }
14923                        for (int userId : sUserManager.getUserIds()) {
14924                            pw.println("App linkages for user " + userId + ":");
14925                            pw.println();
14926                            count = 0;
14927                            for (PackageSetting ps : allPackageSettings) {
14928                                final long status = ps.getDomainVerificationStatusForUser(userId);
14929                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14930                                    continue;
14931                                }
14932                                pw.println(prefix + "Package: " + ps.name);
14933                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14934                                String statusStr = IntentFilterVerificationInfo.
14935                                        getStatusStringFromValue(status);
14936                                pw.println(prefix + "Status:  " + statusStr);
14937                                pw.println();
14938                                count++;
14939                            }
14940                            if (count == 0) {
14941                                pw.println(prefix + "No configured app linkages.");
14942                                pw.println();
14943                            }
14944                        }
14945                    }
14946                }
14947            }
14948
14949            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14950                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14951                if (packageName == null && permissionNames == null) {
14952                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14953                        if (iperm == 0) {
14954                            if (dumpState.onTitlePrinted())
14955                                pw.println();
14956                            pw.println("AppOp Permissions:");
14957                        }
14958                        pw.print("  AppOp Permission ");
14959                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14960                        pw.println(":");
14961                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14962                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14963                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14964                        }
14965                    }
14966                }
14967            }
14968
14969            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14970                boolean printedSomething = false;
14971                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14972                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14973                        continue;
14974                    }
14975                    if (!printedSomething) {
14976                        if (dumpState.onTitlePrinted())
14977                            pw.println();
14978                        pw.println("Registered ContentProviders:");
14979                        printedSomething = true;
14980                    }
14981                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14982                    pw.print("    "); pw.println(p.toString());
14983                }
14984                printedSomething = false;
14985                for (Map.Entry<String, PackageParser.Provider> entry :
14986                        mProvidersByAuthority.entrySet()) {
14987                    PackageParser.Provider p = entry.getValue();
14988                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14989                        continue;
14990                    }
14991                    if (!printedSomething) {
14992                        if (dumpState.onTitlePrinted())
14993                            pw.println();
14994                        pw.println("ContentProvider Authorities:");
14995                        printedSomething = true;
14996                    }
14997                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14998                    pw.print("    "); pw.println(p.toString());
14999                    if (p.info != null && p.info.applicationInfo != null) {
15000                        final String appInfo = p.info.applicationInfo.toString();
15001                        pw.print("      applicationInfo="); pw.println(appInfo);
15002                    }
15003                }
15004            }
15005
15006            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15007                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15008            }
15009
15010            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15011                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15012            }
15013
15014            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15015                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15016            }
15017
15018            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15019                // XXX should handle packageName != null by dumping only install data that
15020                // the given package is involved with.
15021                if (dumpState.onTitlePrinted()) pw.println();
15022                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15023            }
15024
15025            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15026                if (dumpState.onTitlePrinted()) pw.println();
15027                mSettings.dumpReadMessagesLPr(pw, dumpState);
15028
15029                pw.println();
15030                pw.println("Package warning messages:");
15031                BufferedReader in = null;
15032                String line = null;
15033                try {
15034                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15035                    while ((line = in.readLine()) != null) {
15036                        if (line.contains("ignored: updated version")) continue;
15037                        pw.println(line);
15038                    }
15039                } catch (IOException ignored) {
15040                } finally {
15041                    IoUtils.closeQuietly(in);
15042                }
15043            }
15044
15045            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15046                BufferedReader in = null;
15047                String line = null;
15048                try {
15049                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15050                    while ((line = in.readLine()) != null) {
15051                        if (line.contains("ignored: updated version")) continue;
15052                        pw.print("msg,");
15053                        pw.println(line);
15054                    }
15055                } catch (IOException ignored) {
15056                } finally {
15057                    IoUtils.closeQuietly(in);
15058                }
15059            }
15060        }
15061    }
15062
15063    private String dumpDomainString(String packageName) {
15064        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15065        List<IntentFilter> filters = getAllIntentFilters(packageName);
15066
15067        ArraySet<String> result = new ArraySet<>();
15068        if (iviList.size() > 0) {
15069            for (IntentFilterVerificationInfo ivi : iviList) {
15070                for (String host : ivi.getDomains()) {
15071                    result.add(host);
15072                }
15073            }
15074        }
15075        if (filters != null && filters.size() > 0) {
15076            for (IntentFilter filter : filters) {
15077                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15078                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15079                    result.addAll(filter.getHostsList());
15080                }
15081            }
15082        }
15083
15084        StringBuilder sb = new StringBuilder(result.size() * 16);
15085        for (String domain : result) {
15086            if (sb.length() > 0) sb.append(" ");
15087            sb.append(domain);
15088        }
15089        return sb.toString();
15090    }
15091
15092    // ------- apps on sdcard specific code -------
15093    static final boolean DEBUG_SD_INSTALL = false;
15094
15095    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15096
15097    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15098
15099    private boolean mMediaMounted = false;
15100
15101    static String getEncryptKey() {
15102        try {
15103            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15104                    SD_ENCRYPTION_KEYSTORE_NAME);
15105            if (sdEncKey == null) {
15106                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15107                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15108                if (sdEncKey == null) {
15109                    Slog.e(TAG, "Failed to create encryption keys");
15110                    return null;
15111                }
15112            }
15113            return sdEncKey;
15114        } catch (NoSuchAlgorithmException nsae) {
15115            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15116            return null;
15117        } catch (IOException ioe) {
15118            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15119            return null;
15120        }
15121    }
15122
15123    /*
15124     * Update media status on PackageManager.
15125     */
15126    @Override
15127    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15128        int callingUid = Binder.getCallingUid();
15129        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15130            throw new SecurityException("Media status can only be updated by the system");
15131        }
15132        // reader; this apparently protects mMediaMounted, but should probably
15133        // be a different lock in that case.
15134        synchronized (mPackages) {
15135            Log.i(TAG, "Updating external media status from "
15136                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15137                    + (mediaStatus ? "mounted" : "unmounted"));
15138            if (DEBUG_SD_INSTALL)
15139                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15140                        + ", mMediaMounted=" + mMediaMounted);
15141            if (mediaStatus == mMediaMounted) {
15142                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15143                        : 0, -1);
15144                mHandler.sendMessage(msg);
15145                return;
15146            }
15147            mMediaMounted = mediaStatus;
15148        }
15149        // Queue up an async operation since the package installation may take a
15150        // little while.
15151        mHandler.post(new Runnable() {
15152            public void run() {
15153                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15154            }
15155        });
15156    }
15157
15158    /**
15159     * Called by MountService when the initial ASECs to scan are available.
15160     * Should block until all the ASEC containers are finished being scanned.
15161     */
15162    public void scanAvailableAsecs() {
15163        updateExternalMediaStatusInner(true, false, false);
15164        if (mShouldRestoreconData) {
15165            SELinuxMMAC.setRestoreconDone();
15166            mShouldRestoreconData = false;
15167        }
15168    }
15169
15170    /*
15171     * Collect information of applications on external media, map them against
15172     * existing containers and update information based on current mount status.
15173     * Please note that we always have to report status if reportStatus has been
15174     * set to true especially when unloading packages.
15175     */
15176    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15177            boolean externalStorage) {
15178        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15179        int[] uidArr = EmptyArray.INT;
15180
15181        final String[] list = PackageHelper.getSecureContainerList();
15182        if (ArrayUtils.isEmpty(list)) {
15183            Log.i(TAG, "No secure containers found");
15184        } else {
15185            // Process list of secure containers and categorize them
15186            // as active or stale based on their package internal state.
15187
15188            // reader
15189            synchronized (mPackages) {
15190                for (String cid : list) {
15191                    // Leave stages untouched for now; installer service owns them
15192                    if (PackageInstallerService.isStageName(cid)) continue;
15193
15194                    if (DEBUG_SD_INSTALL)
15195                        Log.i(TAG, "Processing container " + cid);
15196                    String pkgName = getAsecPackageName(cid);
15197                    if (pkgName == null) {
15198                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15199                        continue;
15200                    }
15201                    if (DEBUG_SD_INSTALL)
15202                        Log.i(TAG, "Looking for pkg : " + pkgName);
15203
15204                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15205                    if (ps == null) {
15206                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15207                        continue;
15208                    }
15209
15210                    /*
15211                     * Skip packages that are not external if we're unmounting
15212                     * external storage.
15213                     */
15214                    if (externalStorage && !isMounted && !isExternal(ps)) {
15215                        continue;
15216                    }
15217
15218                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15219                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15220                    // The package status is changed only if the code path
15221                    // matches between settings and the container id.
15222                    if (ps.codePathString != null
15223                            && ps.codePathString.startsWith(args.getCodePath())) {
15224                        if (DEBUG_SD_INSTALL) {
15225                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15226                                    + " at code path: " + ps.codePathString);
15227                        }
15228
15229                        // We do have a valid package installed on sdcard
15230                        processCids.put(args, ps.codePathString);
15231                        final int uid = ps.appId;
15232                        if (uid != -1) {
15233                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15234                        }
15235                    } else {
15236                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15237                                + ps.codePathString);
15238                    }
15239                }
15240            }
15241
15242            Arrays.sort(uidArr);
15243        }
15244
15245        // Process packages with valid entries.
15246        if (isMounted) {
15247            if (DEBUG_SD_INSTALL)
15248                Log.i(TAG, "Loading packages");
15249            loadMediaPackages(processCids, uidArr);
15250            startCleaningPackages();
15251            mInstallerService.onSecureContainersAvailable();
15252        } else {
15253            if (DEBUG_SD_INSTALL)
15254                Log.i(TAG, "Unloading packages");
15255            unloadMediaPackages(processCids, uidArr, reportStatus);
15256        }
15257    }
15258
15259    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15260            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15261        final int size = infos.size();
15262        final String[] packageNames = new String[size];
15263        final int[] packageUids = new int[size];
15264        for (int i = 0; i < size; i++) {
15265            final ApplicationInfo info = infos.get(i);
15266            packageNames[i] = info.packageName;
15267            packageUids[i] = info.uid;
15268        }
15269        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15270                finishedReceiver);
15271    }
15272
15273    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15274            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15275        sendResourcesChangedBroadcast(mediaStatus, replacing,
15276                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15277    }
15278
15279    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15280            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15281        int size = pkgList.length;
15282        if (size > 0) {
15283            // Send broadcasts here
15284            Bundle extras = new Bundle();
15285            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15286            if (uidArr != null) {
15287                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15288            }
15289            if (replacing) {
15290                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15291            }
15292            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15293                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15294            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15295        }
15296    }
15297
15298   /*
15299     * Look at potentially valid container ids from processCids If package
15300     * information doesn't match the one on record or package scanning fails,
15301     * the cid is added to list of removeCids. We currently don't delete stale
15302     * containers.
15303     */
15304    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15305        ArrayList<String> pkgList = new ArrayList<String>();
15306        Set<AsecInstallArgs> keys = processCids.keySet();
15307
15308        for (AsecInstallArgs args : keys) {
15309            String codePath = processCids.get(args);
15310            if (DEBUG_SD_INSTALL)
15311                Log.i(TAG, "Loading container : " + args.cid);
15312            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15313            try {
15314                // Make sure there are no container errors first.
15315                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15316                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15317                            + " when installing from sdcard");
15318                    continue;
15319                }
15320                // Check code path here.
15321                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15322                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15323                            + " does not match one in settings " + codePath);
15324                    continue;
15325                }
15326                // Parse package
15327                int parseFlags = mDefParseFlags;
15328                if (args.isExternalAsec()) {
15329                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15330                }
15331                if (args.isFwdLocked()) {
15332                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15333                }
15334
15335                synchronized (mInstallLock) {
15336                    PackageParser.Package pkg = null;
15337                    try {
15338                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15339                    } catch (PackageManagerException e) {
15340                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15341                    }
15342                    // Scan the package
15343                    if (pkg != null) {
15344                        /*
15345                         * TODO why is the lock being held? doPostInstall is
15346                         * called in other places without the lock. This needs
15347                         * to be straightened out.
15348                         */
15349                        // writer
15350                        synchronized (mPackages) {
15351                            retCode = PackageManager.INSTALL_SUCCEEDED;
15352                            pkgList.add(pkg.packageName);
15353                            // Post process args
15354                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15355                                    pkg.applicationInfo.uid);
15356                        }
15357                    } else {
15358                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15359                    }
15360                }
15361
15362            } finally {
15363                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15364                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15365                }
15366            }
15367        }
15368        // writer
15369        synchronized (mPackages) {
15370            // If the platform SDK has changed since the last time we booted,
15371            // we need to re-grant app permission to catch any new ones that
15372            // appear. This is really a hack, and means that apps can in some
15373            // cases get permissions that the user didn't initially explicitly
15374            // allow... it would be nice to have some better way to handle
15375            // this situation.
15376            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15377            if (regrantPermissions)
15378                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15379                        + mSdkVersion + "; regranting permissions for external storage");
15380            mSettings.mExternalSdkPlatform = mSdkVersion;
15381
15382            // Make sure group IDs have been assigned, and any permission
15383            // changes in other apps are accounted for
15384            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15385                    | (regrantPermissions
15386                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15387                            : 0));
15388
15389            mSettings.updateExternalDatabaseVersion();
15390
15391            // can downgrade to reader
15392            // Persist settings
15393            mSettings.writeLPr();
15394        }
15395        // Send a broadcast to let everyone know we are done processing
15396        if (pkgList.size() > 0) {
15397            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15398        }
15399    }
15400
15401   /*
15402     * Utility method to unload a list of specified containers
15403     */
15404    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15405        // Just unmount all valid containers.
15406        for (AsecInstallArgs arg : cidArgs) {
15407            synchronized (mInstallLock) {
15408                arg.doPostDeleteLI(false);
15409           }
15410       }
15411   }
15412
15413    /*
15414     * Unload packages mounted on external media. This involves deleting package
15415     * data from internal structures, sending broadcasts about diabled packages,
15416     * gc'ing to free up references, unmounting all secure containers
15417     * corresponding to packages on external media, and posting a
15418     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15419     * that we always have to post this message if status has been requested no
15420     * matter what.
15421     */
15422    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15423            final boolean reportStatus) {
15424        if (DEBUG_SD_INSTALL)
15425            Log.i(TAG, "unloading media packages");
15426        ArrayList<String> pkgList = new ArrayList<String>();
15427        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15428        final Set<AsecInstallArgs> keys = processCids.keySet();
15429        for (AsecInstallArgs args : keys) {
15430            String pkgName = args.getPackageName();
15431            if (DEBUG_SD_INSTALL)
15432                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15433            // Delete package internally
15434            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15435            synchronized (mInstallLock) {
15436                boolean res = deletePackageLI(pkgName, null, false, null, null,
15437                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15438                if (res) {
15439                    pkgList.add(pkgName);
15440                } else {
15441                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15442                    failedList.add(args);
15443                }
15444            }
15445        }
15446
15447        // reader
15448        synchronized (mPackages) {
15449            // We didn't update the settings after removing each package;
15450            // write them now for all packages.
15451            mSettings.writeLPr();
15452        }
15453
15454        // We have to absolutely send UPDATED_MEDIA_STATUS only
15455        // after confirming that all the receivers processed the ordered
15456        // broadcast when packages get disabled, force a gc to clean things up.
15457        // and unload all the containers.
15458        if (pkgList.size() > 0) {
15459            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15460                    new IIntentReceiver.Stub() {
15461                public void performReceive(Intent intent, int resultCode, String data,
15462                        Bundle extras, boolean ordered, boolean sticky,
15463                        int sendingUser) throws RemoteException {
15464                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15465                            reportStatus ? 1 : 0, 1, keys);
15466                    mHandler.sendMessage(msg);
15467                }
15468            });
15469        } else {
15470            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15471                    keys);
15472            mHandler.sendMessage(msg);
15473        }
15474    }
15475
15476    private void loadPrivatePackages(VolumeInfo vol) {
15477        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15478        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15479        synchronized (mInstallLock) {
15480        synchronized (mPackages) {
15481            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15482            for (PackageSetting ps : packages) {
15483                final PackageParser.Package pkg;
15484                try {
15485                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15486                    loaded.add(pkg.applicationInfo);
15487                } catch (PackageManagerException e) {
15488                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15489                }
15490            }
15491
15492            // TODO: regrant any permissions that changed based since original install
15493
15494            mSettings.writeLPr();
15495        }
15496        }
15497
15498        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15499        sendResourcesChangedBroadcast(true, false, loaded, null);
15500    }
15501
15502    private void unloadPrivatePackages(VolumeInfo vol) {
15503        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15504        synchronized (mInstallLock) {
15505        synchronized (mPackages) {
15506            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15507            for (PackageSetting ps : packages) {
15508                if (ps.pkg == null) continue;
15509
15510                final ApplicationInfo info = ps.pkg.applicationInfo;
15511                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15512                if (deletePackageLI(ps.name, null, false, null, null,
15513                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15514                    unloaded.add(info);
15515                } else {
15516                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15517                }
15518            }
15519
15520            mSettings.writeLPr();
15521        }
15522        }
15523
15524        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15525        sendResourcesChangedBroadcast(false, false, unloaded, null);
15526    }
15527
15528    /**
15529     * Examine all users present on given mounted volume, and destroy data
15530     * belonging to users that are no longer valid, or whose user ID has been
15531     * recycled.
15532     */
15533    private void reconcileUsers(String volumeUuid) {
15534        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15535        if (ArrayUtils.isEmpty(files)) {
15536            Slog.d(TAG, "No users found on " + volumeUuid);
15537            return;
15538        }
15539
15540        for (File file : files) {
15541            if (!file.isDirectory()) continue;
15542
15543            final int userId;
15544            final UserInfo info;
15545            try {
15546                userId = Integer.parseInt(file.getName());
15547                info = sUserManager.getUserInfo(userId);
15548            } catch (NumberFormatException e) {
15549                Slog.w(TAG, "Invalid user directory " + file);
15550                continue;
15551            }
15552
15553            boolean destroyUser = false;
15554            if (info == null) {
15555                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15556                        + " because no matching user was found");
15557                destroyUser = true;
15558            } else {
15559                try {
15560                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15561                } catch (IOException e) {
15562                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15563                            + " because we failed to enforce serial number: " + e);
15564                    destroyUser = true;
15565                }
15566            }
15567
15568            if (destroyUser) {
15569                synchronized (mInstallLock) {
15570                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15571                }
15572            }
15573        }
15574
15575        final UserManager um = mContext.getSystemService(UserManager.class);
15576        for (UserInfo user : um.getUsers()) {
15577            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15578            if (userDir.exists()) continue;
15579
15580            try {
15581                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15582                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15583            } catch (IOException e) {
15584                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15585            }
15586        }
15587    }
15588
15589    /**
15590     * Examine all apps present on given mounted volume, and destroy apps that
15591     * aren't expected, either due to uninstallation or reinstallation on
15592     * another volume.
15593     */
15594    private void reconcileApps(String volumeUuid) {
15595        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15596        if (ArrayUtils.isEmpty(files)) {
15597            Slog.d(TAG, "No apps found on " + volumeUuid);
15598            return;
15599        }
15600
15601        for (File file : files) {
15602            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15603                    && !PackageInstallerService.isStageName(file.getName());
15604            if (!isPackage) {
15605                // Ignore entries which are not packages
15606                continue;
15607            }
15608
15609            boolean destroyApp = false;
15610            String packageName = null;
15611            try {
15612                final PackageLite pkg = PackageParser.parsePackageLite(file,
15613                        PackageParser.PARSE_MUST_BE_APK);
15614                packageName = pkg.packageName;
15615
15616                synchronized (mPackages) {
15617                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15618                    if (ps == null) {
15619                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15620                                + volumeUuid + " because we found no install record");
15621                        destroyApp = true;
15622                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15623                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15624                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15625                        destroyApp = true;
15626                    }
15627                }
15628
15629            } catch (PackageParserException e) {
15630                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15631                destroyApp = true;
15632            }
15633
15634            if (destroyApp) {
15635                synchronized (mInstallLock) {
15636                    if (packageName != null) {
15637                        removeDataDirsLI(volumeUuid, packageName);
15638                    }
15639                    if (file.isDirectory()) {
15640                        mInstaller.rmPackageDir(file.getAbsolutePath());
15641                    } else {
15642                        file.delete();
15643                    }
15644                }
15645            }
15646        }
15647    }
15648
15649    private void unfreezePackage(String packageName) {
15650        synchronized (mPackages) {
15651            final PackageSetting ps = mSettings.mPackages.get(packageName);
15652            if (ps != null) {
15653                ps.frozen = false;
15654            }
15655        }
15656    }
15657
15658    @Override
15659    public int movePackage(final String packageName, final String volumeUuid) {
15660        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15661
15662        final int moveId = mNextMoveId.getAndIncrement();
15663        try {
15664            movePackageInternal(packageName, volumeUuid, moveId);
15665        } catch (PackageManagerException e) {
15666            Slog.w(TAG, "Failed to move " + packageName, e);
15667            mMoveCallbacks.notifyStatusChanged(moveId,
15668                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15669        }
15670        return moveId;
15671    }
15672
15673    private void movePackageInternal(final String packageName, final String volumeUuid,
15674            final int moveId) throws PackageManagerException {
15675        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15676        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15677        final PackageManager pm = mContext.getPackageManager();
15678
15679        final boolean currentAsec;
15680        final String currentVolumeUuid;
15681        final File codeFile;
15682        final String installerPackageName;
15683        final String packageAbiOverride;
15684        final int appId;
15685        final String seinfo;
15686        final String label;
15687
15688        // reader
15689        synchronized (mPackages) {
15690            final PackageParser.Package pkg = mPackages.get(packageName);
15691            final PackageSetting ps = mSettings.mPackages.get(packageName);
15692            if (pkg == null || ps == null) {
15693                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15694            }
15695
15696            if (pkg.applicationInfo.isSystemApp()) {
15697                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15698                        "Cannot move system application");
15699            }
15700
15701            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15702                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15703                        "Package already moved to " + volumeUuid);
15704            }
15705
15706            final File probe = new File(pkg.codePath);
15707            final File probeOat = new File(probe, "oat");
15708            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15709                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15710                        "Move only supported for modern cluster style installs");
15711            }
15712
15713            if (ps.frozen) {
15714                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15715                        "Failed to move already frozen package");
15716            }
15717            ps.frozen = true;
15718
15719            currentAsec = pkg.applicationInfo.isForwardLocked()
15720                    || pkg.applicationInfo.isExternalAsec();
15721            currentVolumeUuid = ps.volumeUuid;
15722            codeFile = new File(pkg.codePath);
15723            installerPackageName = ps.installerPackageName;
15724            packageAbiOverride = ps.cpuAbiOverrideString;
15725            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15726            seinfo = pkg.applicationInfo.seinfo;
15727            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15728        }
15729
15730        // Now that we're guarded by frozen state, kill app during move
15731        killApplication(packageName, appId, "move pkg");
15732
15733        final Bundle extras = new Bundle();
15734        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15735        extras.putString(Intent.EXTRA_TITLE, label);
15736        mMoveCallbacks.notifyCreated(moveId, extras);
15737
15738        int installFlags;
15739        final boolean moveCompleteApp;
15740        final File measurePath;
15741
15742        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15743            installFlags = INSTALL_INTERNAL;
15744            moveCompleteApp = !currentAsec;
15745            measurePath = Environment.getDataAppDirectory(volumeUuid);
15746        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15747            installFlags = INSTALL_EXTERNAL;
15748            moveCompleteApp = false;
15749            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15750        } else {
15751            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15752            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15753                    || !volume.isMountedWritable()) {
15754                unfreezePackage(packageName);
15755                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15756                        "Move location not mounted private volume");
15757            }
15758
15759            Preconditions.checkState(!currentAsec);
15760
15761            installFlags = INSTALL_INTERNAL;
15762            moveCompleteApp = true;
15763            measurePath = Environment.getDataAppDirectory(volumeUuid);
15764        }
15765
15766        final PackageStats stats = new PackageStats(null, -1);
15767        synchronized (mInstaller) {
15768            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15769                unfreezePackage(packageName);
15770                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15771                        "Failed to measure package size");
15772            }
15773        }
15774
15775        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15776                + stats.dataSize);
15777
15778        final long startFreeBytes = measurePath.getFreeSpace();
15779        final long sizeBytes;
15780        if (moveCompleteApp) {
15781            sizeBytes = stats.codeSize + stats.dataSize;
15782        } else {
15783            sizeBytes = stats.codeSize;
15784        }
15785
15786        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15787            unfreezePackage(packageName);
15788            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15789                    "Not enough free space to move");
15790        }
15791
15792        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15793
15794        final CountDownLatch installedLatch = new CountDownLatch(1);
15795        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15796            @Override
15797            public void onUserActionRequired(Intent intent) throws RemoteException {
15798                throw new IllegalStateException();
15799            }
15800
15801            @Override
15802            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15803                    Bundle extras) throws RemoteException {
15804                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15805                        + PackageManager.installStatusToString(returnCode, msg));
15806
15807                installedLatch.countDown();
15808
15809                // Regardless of success or failure of the move operation,
15810                // always unfreeze the package
15811                unfreezePackage(packageName);
15812
15813                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15814                switch (status) {
15815                    case PackageInstaller.STATUS_SUCCESS:
15816                        mMoveCallbacks.notifyStatusChanged(moveId,
15817                                PackageManager.MOVE_SUCCEEDED);
15818                        break;
15819                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15820                        mMoveCallbacks.notifyStatusChanged(moveId,
15821                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15822                        break;
15823                    default:
15824                        mMoveCallbacks.notifyStatusChanged(moveId,
15825                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15826                        break;
15827                }
15828            }
15829        };
15830
15831        final MoveInfo move;
15832        if (moveCompleteApp) {
15833            // Kick off a thread to report progress estimates
15834            new Thread() {
15835                @Override
15836                public void run() {
15837                    while (true) {
15838                        try {
15839                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15840                                break;
15841                            }
15842                        } catch (InterruptedException ignored) {
15843                        }
15844
15845                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15846                        final int progress = 10 + (int) MathUtils.constrain(
15847                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15848                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15849                    }
15850                }
15851            }.start();
15852
15853            final String dataAppName = codeFile.getName();
15854            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15855                    dataAppName, appId, seinfo);
15856        } else {
15857            move = null;
15858        }
15859
15860        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15861
15862        final Message msg = mHandler.obtainMessage(INIT_COPY);
15863        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15864        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15865                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15866        mHandler.sendMessage(msg);
15867    }
15868
15869    @Override
15870    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15871        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15872
15873        final int realMoveId = mNextMoveId.getAndIncrement();
15874        final Bundle extras = new Bundle();
15875        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15876        mMoveCallbacks.notifyCreated(realMoveId, extras);
15877
15878        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15879            @Override
15880            public void onCreated(int moveId, Bundle extras) {
15881                // Ignored
15882            }
15883
15884            @Override
15885            public void onStatusChanged(int moveId, int status, long estMillis) {
15886                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15887            }
15888        };
15889
15890        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15891        storage.setPrimaryStorageUuid(volumeUuid, callback);
15892        return realMoveId;
15893    }
15894
15895    @Override
15896    public int getMoveStatus(int moveId) {
15897        mContext.enforceCallingOrSelfPermission(
15898                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15899        return mMoveCallbacks.mLastStatus.get(moveId);
15900    }
15901
15902    @Override
15903    public void registerMoveCallback(IPackageMoveObserver callback) {
15904        mContext.enforceCallingOrSelfPermission(
15905                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15906        mMoveCallbacks.register(callback);
15907    }
15908
15909    @Override
15910    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15911        mContext.enforceCallingOrSelfPermission(
15912                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15913        mMoveCallbacks.unregister(callback);
15914    }
15915
15916    @Override
15917    public boolean setInstallLocation(int loc) {
15918        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15919                null);
15920        if (getInstallLocation() == loc) {
15921            return true;
15922        }
15923        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15924                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15925            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15926                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15927            return true;
15928        }
15929        return false;
15930   }
15931
15932    @Override
15933    public int getInstallLocation() {
15934        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15935                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15936                PackageHelper.APP_INSTALL_AUTO);
15937    }
15938
15939    /** Called by UserManagerService */
15940    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15941        mDirtyUsers.remove(userHandle);
15942        mSettings.removeUserLPw(userHandle);
15943        mPendingBroadcasts.remove(userHandle);
15944        if (mInstaller != null) {
15945            // Technically, we shouldn't be doing this with the package lock
15946            // held.  However, this is very rare, and there is already so much
15947            // other disk I/O going on, that we'll let it slide for now.
15948            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15949            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15950                final String volumeUuid = vol.getFsUuid();
15951                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15952                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15953            }
15954        }
15955        mUserNeedsBadging.delete(userHandle);
15956        removeUnusedPackagesLILPw(userManager, userHandle);
15957    }
15958
15959    /**
15960     * We're removing userHandle and would like to remove any downloaded packages
15961     * that are no longer in use by any other user.
15962     * @param userHandle the user being removed
15963     */
15964    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15965        final boolean DEBUG_CLEAN_APKS = false;
15966        int [] users = userManager.getUserIdsLPr();
15967        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15968        while (psit.hasNext()) {
15969            PackageSetting ps = psit.next();
15970            if (ps.pkg == null) {
15971                continue;
15972            }
15973            final String packageName = ps.pkg.packageName;
15974            // Skip over if system app
15975            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15976                continue;
15977            }
15978            if (DEBUG_CLEAN_APKS) {
15979                Slog.i(TAG, "Checking package " + packageName);
15980            }
15981            boolean keep = false;
15982            for (int i = 0; i < users.length; i++) {
15983                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15984                    keep = true;
15985                    if (DEBUG_CLEAN_APKS) {
15986                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15987                                + users[i]);
15988                    }
15989                    break;
15990                }
15991            }
15992            if (!keep) {
15993                if (DEBUG_CLEAN_APKS) {
15994                    Slog.i(TAG, "  Removing package " + packageName);
15995                }
15996                mHandler.post(new Runnable() {
15997                    public void run() {
15998                        deletePackageX(packageName, userHandle, 0);
15999                    } //end run
16000                });
16001            }
16002        }
16003    }
16004
16005    /** Called by UserManagerService */
16006    void createNewUserLILPw(int userHandle) {
16007        if (mInstaller != null) {
16008            mInstaller.createUserConfig(userHandle);
16009            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16010            applyFactoryDefaultBrowserLPw(userHandle);
16011            primeDomainVerificationsLPw(userHandle);
16012        }
16013    }
16014
16015    void newUserCreated(final int userHandle) {
16016        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16017    }
16018
16019    @Override
16020    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16021        mContext.enforceCallingOrSelfPermission(
16022                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16023                "Only package verification agents can read the verifier device identity");
16024
16025        synchronized (mPackages) {
16026            return mSettings.getVerifierDeviceIdentityLPw();
16027        }
16028    }
16029
16030    @Override
16031    public void setPermissionEnforced(String permission, boolean enforced) {
16032        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
16033        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16034            synchronized (mPackages) {
16035                if (mSettings.mReadExternalStorageEnforced == null
16036                        || mSettings.mReadExternalStorageEnforced != enforced) {
16037                    mSettings.mReadExternalStorageEnforced = enforced;
16038                    mSettings.writeLPr();
16039                }
16040            }
16041            // kill any non-foreground processes so we restart them and
16042            // grant/revoke the GID.
16043            final IActivityManager am = ActivityManagerNative.getDefault();
16044            if (am != null) {
16045                final long token = Binder.clearCallingIdentity();
16046                try {
16047                    am.killProcessesBelowForeground("setPermissionEnforcement");
16048                } catch (RemoteException e) {
16049                } finally {
16050                    Binder.restoreCallingIdentity(token);
16051                }
16052            }
16053        } else {
16054            throw new IllegalArgumentException("No selective enforcement for " + permission);
16055        }
16056    }
16057
16058    @Override
16059    @Deprecated
16060    public boolean isPermissionEnforced(String permission) {
16061        return true;
16062    }
16063
16064    @Override
16065    public boolean isStorageLow() {
16066        final long token = Binder.clearCallingIdentity();
16067        try {
16068            final DeviceStorageMonitorInternal
16069                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16070            if (dsm != null) {
16071                return dsm.isMemoryLow();
16072            } else {
16073                return false;
16074            }
16075        } finally {
16076            Binder.restoreCallingIdentity(token);
16077        }
16078    }
16079
16080    @Override
16081    public IPackageInstaller getPackageInstaller() {
16082        return mInstallerService;
16083    }
16084
16085    private boolean userNeedsBadging(int userId) {
16086        int index = mUserNeedsBadging.indexOfKey(userId);
16087        if (index < 0) {
16088            final UserInfo userInfo;
16089            final long token = Binder.clearCallingIdentity();
16090            try {
16091                userInfo = sUserManager.getUserInfo(userId);
16092            } finally {
16093                Binder.restoreCallingIdentity(token);
16094            }
16095            final boolean b;
16096            if (userInfo != null && userInfo.isManagedProfile()) {
16097                b = true;
16098            } else {
16099                b = false;
16100            }
16101            mUserNeedsBadging.put(userId, b);
16102            return b;
16103        }
16104        return mUserNeedsBadging.valueAt(index);
16105    }
16106
16107    @Override
16108    public KeySet getKeySetByAlias(String packageName, String alias) {
16109        if (packageName == null || alias == null) {
16110            return null;
16111        }
16112        synchronized(mPackages) {
16113            final PackageParser.Package pkg = mPackages.get(packageName);
16114            if (pkg == null) {
16115                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16116                throw new IllegalArgumentException("Unknown package: " + packageName);
16117            }
16118            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16119            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16120        }
16121    }
16122
16123    @Override
16124    public KeySet getSigningKeySet(String packageName) {
16125        if (packageName == null) {
16126            return null;
16127        }
16128        synchronized(mPackages) {
16129            final PackageParser.Package pkg = mPackages.get(packageName);
16130            if (pkg == null) {
16131                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16132                throw new IllegalArgumentException("Unknown package: " + packageName);
16133            }
16134            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16135                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16136                throw new SecurityException("May not access signing KeySet of other apps.");
16137            }
16138            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16139            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16140        }
16141    }
16142
16143    @Override
16144    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16145        if (packageName == null || ks == null) {
16146            return false;
16147        }
16148        synchronized(mPackages) {
16149            final PackageParser.Package pkg = mPackages.get(packageName);
16150            if (pkg == null) {
16151                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16152                throw new IllegalArgumentException("Unknown package: " + packageName);
16153            }
16154            IBinder ksh = ks.getToken();
16155            if (ksh instanceof KeySetHandle) {
16156                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16157                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16158            }
16159            return false;
16160        }
16161    }
16162
16163    @Override
16164    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16165        if (packageName == null || ks == null) {
16166            return false;
16167        }
16168        synchronized(mPackages) {
16169            final PackageParser.Package pkg = mPackages.get(packageName);
16170            if (pkg == null) {
16171                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16172                throw new IllegalArgumentException("Unknown package: " + packageName);
16173            }
16174            IBinder ksh = ks.getToken();
16175            if (ksh instanceof KeySetHandle) {
16176                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16177                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16178            }
16179            return false;
16180        }
16181    }
16182
16183    public void getUsageStatsIfNoPackageUsageInfo() {
16184        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16185            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16186            if (usm == null) {
16187                throw new IllegalStateException("UsageStatsManager must be initialized");
16188            }
16189            long now = System.currentTimeMillis();
16190            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16191            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16192                String packageName = entry.getKey();
16193                PackageParser.Package pkg = mPackages.get(packageName);
16194                if (pkg == null) {
16195                    continue;
16196                }
16197                UsageStats usage = entry.getValue();
16198                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16199                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16200            }
16201        }
16202    }
16203
16204    /**
16205     * Check and throw if the given before/after packages would be considered a
16206     * downgrade.
16207     */
16208    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16209            throws PackageManagerException {
16210        if (after.versionCode < before.mVersionCode) {
16211            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16212                    "Update version code " + after.versionCode + " is older than current "
16213                    + before.mVersionCode);
16214        } else if (after.versionCode == before.mVersionCode) {
16215            if (after.baseRevisionCode < before.baseRevisionCode) {
16216                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16217                        "Update base revision code " + after.baseRevisionCode
16218                        + " is older than current " + before.baseRevisionCode);
16219            }
16220
16221            if (!ArrayUtils.isEmpty(after.splitNames)) {
16222                for (int i = 0; i < after.splitNames.length; i++) {
16223                    final String splitName = after.splitNames[i];
16224                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16225                    if (j != -1) {
16226                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16227                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16228                                    "Update split " + splitName + " revision code "
16229                                    + after.splitRevisionCodes[i] + " is older than current "
16230                                    + before.splitRevisionCodes[j]);
16231                        }
16232                    }
16233                }
16234            }
16235        }
16236    }
16237
16238    private static class MoveCallbacks extends Handler {
16239        private static final int MSG_CREATED = 1;
16240        private static final int MSG_STATUS_CHANGED = 2;
16241
16242        private final RemoteCallbackList<IPackageMoveObserver>
16243                mCallbacks = new RemoteCallbackList<>();
16244
16245        private final SparseIntArray mLastStatus = new SparseIntArray();
16246
16247        public MoveCallbacks(Looper looper) {
16248            super(looper);
16249        }
16250
16251        public void register(IPackageMoveObserver callback) {
16252            mCallbacks.register(callback);
16253        }
16254
16255        public void unregister(IPackageMoveObserver callback) {
16256            mCallbacks.unregister(callback);
16257        }
16258
16259        @Override
16260        public void handleMessage(Message msg) {
16261            final SomeArgs args = (SomeArgs) msg.obj;
16262            final int n = mCallbacks.beginBroadcast();
16263            for (int i = 0; i < n; i++) {
16264                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16265                try {
16266                    invokeCallback(callback, msg.what, args);
16267                } catch (RemoteException ignored) {
16268                }
16269            }
16270            mCallbacks.finishBroadcast();
16271            args.recycle();
16272        }
16273
16274        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16275                throws RemoteException {
16276            switch (what) {
16277                case MSG_CREATED: {
16278                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16279                    break;
16280                }
16281                case MSG_STATUS_CHANGED: {
16282                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16283                    break;
16284                }
16285            }
16286        }
16287
16288        private void notifyCreated(int moveId, Bundle extras) {
16289            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16290
16291            final SomeArgs args = SomeArgs.obtain();
16292            args.argi1 = moveId;
16293            args.arg2 = extras;
16294            obtainMessage(MSG_CREATED, args).sendToTarget();
16295        }
16296
16297        private void notifyStatusChanged(int moveId, int status) {
16298            notifyStatusChanged(moveId, status, -1);
16299        }
16300
16301        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16302            Slog.v(TAG, "Move " + moveId + " status " + status);
16303
16304            final SomeArgs args = SomeArgs.obtain();
16305            args.argi1 = moveId;
16306            args.argi2 = status;
16307            args.arg3 = estMillis;
16308            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16309
16310            synchronized (mLastStatus) {
16311                mLastStatus.put(moveId, status);
16312            }
16313        }
16314    }
16315
16316    private final class OnPermissionChangeListeners extends Handler {
16317        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16318
16319        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16320                new RemoteCallbackList<>();
16321
16322        public OnPermissionChangeListeners(Looper looper) {
16323            super(looper);
16324        }
16325
16326        @Override
16327        public void handleMessage(Message msg) {
16328            switch (msg.what) {
16329                case MSG_ON_PERMISSIONS_CHANGED: {
16330                    final int uid = msg.arg1;
16331                    handleOnPermissionsChanged(uid);
16332                } break;
16333            }
16334        }
16335
16336        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16337            mPermissionListeners.register(listener);
16338
16339        }
16340
16341        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16342            mPermissionListeners.unregister(listener);
16343        }
16344
16345        public void onPermissionsChanged(int uid) {
16346            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16347                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16348            }
16349        }
16350
16351        private void handleOnPermissionsChanged(int uid) {
16352            final int count = mPermissionListeners.beginBroadcast();
16353            try {
16354                for (int i = 0; i < count; i++) {
16355                    IOnPermissionsChangeListener callback = mPermissionListeners
16356                            .getBroadcastItem(i);
16357                    try {
16358                        callback.onPermissionsChanged(uid);
16359                    } catch (RemoteException e) {
16360                        Log.e(TAG, "Permission listener is dead", e);
16361                    }
16362                }
16363            } finally {
16364                mPermissionListeners.finishBroadcast();
16365            }
16366        }
16367    }
16368
16369    private class PackageManagerInternalImpl extends PackageManagerInternal {
16370        @Override
16371        public void setLocationPackagesProvider(PackagesProvider provider) {
16372            synchronized (mPackages) {
16373                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16374            }
16375        }
16376
16377        @Override
16378        public void setImePackagesProvider(PackagesProvider provider) {
16379            synchronized (mPackages) {
16380                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16381            }
16382        }
16383
16384        @Override
16385        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16386            synchronized (mPackages) {
16387                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16388            }
16389        }
16390
16391        @Override
16392        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16393            synchronized (mPackages) {
16394                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16395            }
16396        }
16397
16398        @Override
16399        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16400            synchronized (mPackages) {
16401                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16402            }
16403        }
16404
16405        @Override
16406        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16407            synchronized (mPackages) {
16408                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16409            }
16410        }
16411
16412        @Override
16413        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16414            synchronized (mPackages) {
16415                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16416                        packageName, userId);
16417            }
16418        }
16419
16420        @Override
16421        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16422            synchronized (mPackages) {
16423                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16424                        packageName, userId);
16425            }
16426        }
16427    }
16428
16429    @Override
16430    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16431        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16432        synchronized (mPackages) {
16433            final long identity = Binder.clearCallingIdentity();
16434            try {
16435                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16436                        packageNames, userId);
16437            } finally {
16438                Binder.restoreCallingIdentity(identity);
16439            }
16440        }
16441    }
16442
16443    private static void enforceSystemOrPhoneCaller(String tag) {
16444        int callingUid = Binder.getCallingUid();
16445        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16446            throw new SecurityException(
16447                    "Cannot call " + tag + " from UID " + callingUid);
16448        }
16449    }
16450}
16451