PackageManagerService.java revision 5a624aad5faa0a71ce6495671caac1ccd90544ba
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.MATCH_ALL;
60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
64import static android.content.pm.PackageManager.PERMISSION_DENIED;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Debug;
147import android.os.Binder;
148import android.os.Build;
149import android.os.Bundle;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.MountServiceInternal;
170import android.os.storage.StorageEventListener;
171import android.os.storage.StorageManager;
172import android.os.storage.VolumeInfo;
173import android.os.storage.VolumeRecord;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArrayMap;
182import android.util.ArraySet;
183import android.util.AtomicFile;
184import android.util.DisplayMetrics;
185import android.util.EventLog;
186import android.util.ExceptionUtils;
187import android.util.Log;
188import android.util.LogPrinter;
189import android.util.MathUtils;
190import android.util.PrintStreamPrinter;
191import android.util.Slog;
192import android.util.SparseArray;
193import android.util.SparseBooleanArray;
194import android.util.SparseIntArray;
195import android.util.Xml;
196import android.view.Display;
197
198import dalvik.system.DexFile;
199import dalvik.system.VMRuntime;
200
201import libcore.io.IoUtils;
202import libcore.util.EmptyArray;
203
204import com.android.internal.R;
205import com.android.internal.annotations.GuardedBy;
206import com.android.internal.app.IMediaContainerService;
207import com.android.internal.app.ResolverActivity;
208import com.android.internal.content.NativeLibraryHelper;
209import com.android.internal.content.PackageHelper;
210import com.android.internal.os.IParcelFileDescriptorFactory;
211import com.android.internal.os.SomeArgs;
212import com.android.internal.os.Zygote;
213import com.android.internal.util.ArrayUtils;
214import com.android.internal.util.FastPrintWriter;
215import com.android.internal.util.FastXmlSerializer;
216import com.android.internal.util.IndentingPrintWriter;
217import com.android.internal.util.Preconditions;
218import com.android.server.EventLogTags;
219import com.android.server.FgThread;
220import com.android.server.IntentResolver;
221import com.android.server.LocalServices;
222import com.android.server.ServiceThread;
223import com.android.server.SystemConfig;
224import com.android.server.Watchdog;
225import com.android.server.pm.PermissionsState.PermissionState;
226import com.android.server.pm.Settings.DatabaseVersion;
227import com.android.server.pm.Settings.VersionInfo;
228import com.android.server.storage.DeviceStorageMonitorInternal;
229
230import org.xmlpull.v1.XmlPullParser;
231import org.xmlpull.v1.XmlPullParserException;
232import org.xmlpull.v1.XmlSerializer;
233
234import java.io.BufferedInputStream;
235import java.io.BufferedOutputStream;
236import java.io.BufferedReader;
237import java.io.ByteArrayInputStream;
238import java.io.ByteArrayOutputStream;
239import java.io.File;
240import java.io.FileDescriptor;
241import java.io.FileNotFoundException;
242import java.io.FileOutputStream;
243import java.io.FileReader;
244import java.io.FilenameFilter;
245import java.io.IOException;
246import java.io.InputStream;
247import java.io.PrintWriter;
248import java.nio.charset.StandardCharsets;
249import java.security.NoSuchAlgorithmException;
250import java.security.PublicKey;
251import java.security.cert.CertificateEncodingException;
252import java.security.cert.CertificateException;
253import java.text.SimpleDateFormat;
254import java.util.ArrayList;
255import java.util.Arrays;
256import java.util.Collection;
257import java.util.Collections;
258import java.util.Comparator;
259import java.util.Date;
260import java.util.Iterator;
261import java.util.List;
262import java.util.Map;
263import java.util.Objects;
264import java.util.Set;
265import java.util.concurrent.CountDownLatch;
266import java.util.concurrent.TimeUnit;
267import java.util.concurrent.atomic.AtomicBoolean;
268import java.util.concurrent.atomic.AtomicInteger;
269import java.util.concurrent.atomic.AtomicLong;
270
271/**
272 * Keep track of all those .apks everywhere.
273 *
274 * This is very central to the platform's security; please run the unit
275 * tests whenever making modifications here:
276 *
277mmm frameworks/base/tests/AndroidTests
278adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
279adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
280 *
281 * {@hide}
282 */
283public class PackageManagerService extends IPackageManager.Stub {
284    static final String TAG = "PackageManager";
285    static final boolean DEBUG_SETTINGS = false;
286    static final boolean DEBUG_PREFERRED = false;
287    static final boolean DEBUG_UPGRADE = false;
288    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
289    private static final boolean DEBUG_BACKUP = false;
290    private static final boolean DEBUG_INSTALL = false;
291    private static final boolean DEBUG_REMOVE = false;
292    private static final boolean DEBUG_BROADCASTS = false;
293    private static final boolean DEBUG_SHOW_INFO = false;
294    private static final boolean DEBUG_PACKAGE_INFO = false;
295    private static final boolean DEBUG_INTENT_MATCHING = false;
296    private static final boolean DEBUG_PACKAGE_SCANNING = false;
297    private static final boolean DEBUG_VERIFY = false;
298    private static final boolean DEBUG_DEXOPT = false;
299    private static final boolean DEBUG_ABI_SELECTION = false;
300
301    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
302
303    private static final int RADIO_UID = Process.PHONE_UID;
304    private static final int LOG_UID = Process.LOG_UID;
305    private static final int NFC_UID = Process.NFC_UID;
306    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
307    private static final int SHELL_UID = Process.SHELL_UID;
308
309    // Cap the size of permission trees that 3rd party apps can define
310    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
311
312    // Suffix used during package installation when copying/moving
313    // package apks to install directory.
314    private static final String INSTALL_PACKAGE_SUFFIX = "-";
315
316    static final int SCAN_NO_DEX = 1<<1;
317    static final int SCAN_FORCE_DEX = 1<<2;
318    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
319    static final int SCAN_NEW_INSTALL = 1<<4;
320    static final int SCAN_NO_PATHS = 1<<5;
321    static final int SCAN_UPDATE_TIME = 1<<6;
322    static final int SCAN_DEFER_DEX = 1<<7;
323    static final int SCAN_BOOTING = 1<<8;
324    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
325    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
326    static final int SCAN_REPLACING = 1<<11;
327    static final int SCAN_REQUIRE_KNOWN = 1<<12;
328    static final int SCAN_MOVE = 1<<13;
329    static final int SCAN_INITIAL = 1<<14;
330
331    static final int REMOVE_CHATTY = 1<<16;
332
333    private static final int[] EMPTY_INT_ARRAY = new int[0];
334
335    /**
336     * Timeout (in milliseconds) after which the watchdog should declare that
337     * our handler thread is wedged.  The usual default for such things is one
338     * minute but we sometimes do very lengthy I/O operations on this thread,
339     * such as installing multi-gigabyte applications, so ours needs to be longer.
340     */
341    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
342
343    /**
344     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
345     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
346     * settings entry if available, otherwise we use the hardcoded default.  If it's been
347     * more than this long since the last fstrim, we force one during the boot sequence.
348     *
349     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
350     * one gets run at the next available charging+idle time.  This final mandatory
351     * no-fstrim check kicks in only of the other scheduling criteria is never met.
352     */
353    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
354
355    /**
356     * Whether verification is enabled by default.
357     */
358    private static final boolean DEFAULT_VERIFY_ENABLE = true;
359
360    /**
361     * The default maximum time to wait for the verification agent to return in
362     * milliseconds.
363     */
364    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
365
366    /**
367     * The default response for package verification timeout.
368     *
369     * This can be either PackageManager.VERIFICATION_ALLOW or
370     * PackageManager.VERIFICATION_REJECT.
371     */
372    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
373
374    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
375
376    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
377            DEFAULT_CONTAINER_PACKAGE,
378            "com.android.defcontainer.DefaultContainerService");
379
380    private static final String KILL_APP_REASON_GIDS_CHANGED =
381            "permission grant or revoke changed gids";
382
383    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
384            "permissions revoked";
385
386    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
387
388    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
389
390    /** Permission grant: not grant the permission. */
391    private static final int GRANT_DENIED = 1;
392
393    /** Permission grant: grant the permission as an install permission. */
394    private static final int GRANT_INSTALL = 2;
395
396    /** Permission grant: grant the permission as an install permission for a legacy app. */
397    private static final int GRANT_INSTALL_LEGACY = 3;
398
399    /** Permission grant: grant the permission as a runtime one. */
400    private static final int GRANT_RUNTIME = 4;
401
402    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
403    private static final int GRANT_UPGRADE = 5;
404
405    /** Canonical intent used to identify what counts as a "web browser" app */
406    private static final Intent sBrowserIntent;
407    static {
408        sBrowserIntent = new Intent();
409        sBrowserIntent.setAction(Intent.ACTION_VIEW);
410        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
411        sBrowserIntent.setData(Uri.parse("http:"));
412    }
413
414    final ServiceThread mHandlerThread;
415
416    final PackageHandler mHandler;
417
418    /**
419     * Messages for {@link #mHandler} that need to wait for system ready before
420     * being dispatched.
421     */
422    private ArrayList<Message> mPostSystemReadyMessages;
423
424    final int mSdkVersion = Build.VERSION.SDK_INT;
425
426    final Context mContext;
427    final boolean mFactoryTest;
428    final boolean mOnlyCore;
429    final boolean mLazyDexOpt;
430    final long mDexOptLRUThresholdInMills;
431    final DisplayMetrics mMetrics;
432    final int mDefParseFlags;
433    final String[] mSeparateProcesses;
434    final boolean mIsUpgrade;
435
436    // This is where all application persistent data goes.
437    final File mAppDataDir;
438
439    // This is where all application persistent data goes for secondary users.
440    final File mUserAppDataDir;
441
442    /** The location for ASEC container files on internal storage. */
443    final String mAsecInternalPath;
444
445    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
446    // LOCK HELD.  Can be called with mInstallLock held.
447    @GuardedBy("mInstallLock")
448    final Installer mInstaller;
449
450    /** Directory where installed third-party apps stored */
451    final File mAppInstallDir;
452
453    /**
454     * Directory to which applications installed internally have their
455     * 32 bit native libraries copied.
456     */
457    private File mAppLib32InstallDir;
458
459    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
460    // apps.
461    final File mDrmAppPrivateInstallDir;
462
463    // ----------------------------------------------------------------
464
465    // Lock for state used when installing and doing other long running
466    // operations.  Methods that must be called with this lock held have
467    // the suffix "LI".
468    final Object mInstallLock = new Object();
469
470    // ----------------------------------------------------------------
471
472    // Keys are String (package name), values are Package.  This also serves
473    // as the lock for the global state.  Methods that must be called with
474    // this lock held have the prefix "LP".
475    @GuardedBy("mPackages")
476    final ArrayMap<String, PackageParser.Package> mPackages =
477            new ArrayMap<String, PackageParser.Package>();
478
479    // Tracks available target package names -> overlay package paths.
480    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
481        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
482
483    /**
484     * Tracks new system packages [receiving in an OTA] that we expect to
485     * find updated user-installed versions. Keys are package name, values
486     * are package location.
487     */
488    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
489
490    final Settings mSettings;
491    boolean mRestoredSettings;
492
493    // System configuration read by SystemConfig.
494    final int[] mGlobalGids;
495    final SparseArray<ArraySet<String>> mSystemPermissions;
496    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
497
498    // If mac_permissions.xml was found for seinfo labeling.
499    boolean mFoundPolicyFile;
500
501    // If a recursive restorecon of /data/data/<pkg> is needed.
502    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
503
504    public static final class SharedLibraryEntry {
505        public final String path;
506        public final String apk;
507
508        SharedLibraryEntry(String _path, String _apk) {
509            path = _path;
510            apk = _apk;
511        }
512    }
513
514    // Currently known shared libraries.
515    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
516            new ArrayMap<String, SharedLibraryEntry>();
517
518    // All available activities, for your resolving pleasure.
519    final ActivityIntentResolver mActivities =
520            new ActivityIntentResolver();
521
522    // All available receivers, for your resolving pleasure.
523    final ActivityIntentResolver mReceivers =
524            new ActivityIntentResolver();
525
526    // All available services, for your resolving pleasure.
527    final ServiceIntentResolver mServices = new ServiceIntentResolver();
528
529    // All available providers, for your resolving pleasure.
530    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
531
532    // Mapping from provider base names (first directory in content URI codePath)
533    // to the provider information.
534    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
535            new ArrayMap<String, PackageParser.Provider>();
536
537    // Mapping from instrumentation class names to info about them.
538    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
539            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
540
541    // Mapping from permission names to info about them.
542    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
543            new ArrayMap<String, PackageParser.PermissionGroup>();
544
545    // Packages whose data we have transfered into another package, thus
546    // should no longer exist.
547    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
548
549    // Broadcast actions that are only available to the system.
550    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
551
552    /** List of packages waiting for verification. */
553    final SparseArray<PackageVerificationState> mPendingVerification
554            = new SparseArray<PackageVerificationState>();
555
556    /** Set of packages associated with each app op permission. */
557    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
558
559    final PackageInstallerService mInstallerService;
560
561    private final PackageDexOptimizer mPackageDexOptimizer;
562
563    private AtomicInteger mNextMoveId = new AtomicInteger();
564    private final MoveCallbacks mMoveCallbacks;
565
566    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
567
568    // Cache of users who need badging.
569    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
570
571    /** Token for keys in mPendingVerification. */
572    private int mPendingVerificationToken = 0;
573
574    volatile boolean mSystemReady;
575    volatile boolean mSafeMode;
576    volatile boolean mHasSystemUidErrors;
577
578    ApplicationInfo mAndroidApplication;
579    final ActivityInfo mResolveActivity = new ActivityInfo();
580    final ResolveInfo mResolveInfo = new ResolveInfo();
581    ComponentName mResolveComponentName;
582    PackageParser.Package mPlatformPackage;
583    ComponentName mCustomResolverComponentName;
584
585    boolean mResolverReplaced = false;
586
587    private final ComponentName mIntentFilterVerifierComponent;
588    private int mIntentFilterVerificationToken = 0;
589
590    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
591            = new SparseArray<IntentFilterVerificationState>();
592
593    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
594            new DefaultPermissionGrantPolicy(this);
595
596    private static class IFVerificationParams {
597        PackageParser.Package pkg;
598        boolean replacing;
599        int userId;
600        int verifierUid;
601
602        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
603                int _userId, int _verifierUid) {
604            pkg = _pkg;
605            replacing = _replacing;
606            userId = _userId;
607            replacing = _replacing;
608            verifierUid = _verifierUid;
609        }
610    }
611
612    private interface IntentFilterVerifier<T extends IntentFilter> {
613        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
614                                               T filter, String packageName);
615        void startVerifications(int userId);
616        void receiveVerificationResponse(int verificationId);
617    }
618
619    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
620        private Context mContext;
621        private ComponentName mIntentFilterVerifierComponent;
622        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
623
624        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
625            mContext = context;
626            mIntentFilterVerifierComponent = verifierComponent;
627        }
628
629        private String getDefaultScheme() {
630            return IntentFilter.SCHEME_HTTPS;
631        }
632
633        @Override
634        public void startVerifications(int userId) {
635            // Launch verifications requests
636            int count = mCurrentIntentFilterVerifications.size();
637            for (int n=0; n<count; n++) {
638                int verificationId = mCurrentIntentFilterVerifications.get(n);
639                final IntentFilterVerificationState ivs =
640                        mIntentFilterVerificationStates.get(verificationId);
641
642                String packageName = ivs.getPackageName();
643
644                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
645                final int filterCount = filters.size();
646                ArraySet<String> domainsSet = new ArraySet<>();
647                for (int m=0; m<filterCount; m++) {
648                    PackageParser.ActivityIntentInfo filter = filters.get(m);
649                    domainsSet.addAll(filter.getHostsList());
650                }
651                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
652                synchronized (mPackages) {
653                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
654                            packageName, domainsList) != null) {
655                        scheduleWriteSettingsLocked();
656                    }
657                }
658                sendVerificationRequest(userId, verificationId, ivs);
659            }
660            mCurrentIntentFilterVerifications.clear();
661        }
662
663        private void sendVerificationRequest(int userId, int verificationId,
664                IntentFilterVerificationState ivs) {
665
666            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
667            verificationIntent.putExtra(
668                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
669                    verificationId);
670            verificationIntent.putExtra(
671                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
672                    getDefaultScheme());
673            verificationIntent.putExtra(
674                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
675                    ivs.getHostsString());
676            verificationIntent.putExtra(
677                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
678                    ivs.getPackageName());
679            verificationIntent.setComponent(mIntentFilterVerifierComponent);
680            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
681
682            UserHandle user = new UserHandle(userId);
683            mContext.sendBroadcastAsUser(verificationIntent, user);
684            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
685                    "Sending IntentFilter verification broadcast");
686        }
687
688        public void receiveVerificationResponse(int verificationId) {
689            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
690
691            final boolean verified = ivs.isVerified();
692
693            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
694            final int count = filters.size();
695            if (DEBUG_DOMAIN_VERIFICATION) {
696                Slog.i(TAG, "Received verification response " + verificationId
697                        + " for " + count + " filters, verified=" + verified);
698            }
699            for (int n=0; n<count; n++) {
700                PackageParser.ActivityIntentInfo filter = filters.get(n);
701                filter.setVerified(verified);
702
703                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
704                        + " verified with result:" + verified + " and hosts:"
705                        + ivs.getHostsString());
706            }
707
708            mIntentFilterVerificationStates.remove(verificationId);
709
710            final String packageName = ivs.getPackageName();
711            IntentFilterVerificationInfo ivi = null;
712
713            synchronized (mPackages) {
714                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
715            }
716            if (ivi == null) {
717                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
718                        + verificationId + " packageName:" + packageName);
719                return;
720            }
721            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
722                    "Updating IntentFilterVerificationInfo for package " + packageName
723                            +" verificationId:" + verificationId);
724
725            synchronized (mPackages) {
726                if (verified) {
727                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
728                } else {
729                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
730                }
731                scheduleWriteSettingsLocked();
732
733                final int userId = ivs.getUserId();
734                if (userId != UserHandle.USER_ALL) {
735                    final int userStatus =
736                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
737
738                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
739                    boolean needUpdate = false;
740
741                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
742                    // already been set by the User thru the Disambiguation dialog
743                    switch (userStatus) {
744                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
745                            if (verified) {
746                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
747                            } else {
748                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
749                            }
750                            needUpdate = true;
751                            break;
752
753                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
754                            if (verified) {
755                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
756                                needUpdate = true;
757                            }
758                            break;
759
760                        default:
761                            // Nothing to do
762                    }
763
764                    if (needUpdate) {
765                        mSettings.updateIntentFilterVerificationStatusLPw(
766                                packageName, updatedStatus, userId);
767                        scheduleWritePackageRestrictionsLocked(userId);
768                    }
769                }
770            }
771        }
772
773        @Override
774        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
775                    ActivityIntentInfo filter, String packageName) {
776            if (!hasValidDomains(filter)) {
777                return false;
778            }
779            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
780            if (ivs == null) {
781                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
782                        packageName);
783            }
784            if (DEBUG_DOMAIN_VERIFICATION) {
785                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
786            }
787            ivs.addFilter(filter);
788            return true;
789        }
790
791        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
792                int userId, int verificationId, String packageName) {
793            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
794                    verifierUid, userId, packageName);
795            ivs.setPendingState();
796            synchronized (mPackages) {
797                mIntentFilterVerificationStates.append(verificationId, ivs);
798                mCurrentIntentFilterVerifications.add(verificationId);
799            }
800            return ivs;
801        }
802    }
803
804    private static boolean hasValidDomains(ActivityIntentInfo filter) {
805        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
806                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
807                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
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, args.user.getIdentifier(),
1344                                        args.installGrantPermissions);
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            if (TextUtils.isEmpty(fsUuid)) {
1660                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1661                return;
1662            }
1663
1664            // Remove any apps installed on the forgotten volume
1665            synchronized (mPackages) {
1666                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1667                for (PackageSetting ps : packages) {
1668                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1669                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1670                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1671                }
1672
1673                mSettings.onVolumeForgotten(fsUuid);
1674                mSettings.writeLPr();
1675            }
1676        }
1677    };
1678
1679    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1680            String[] grantedPermissions) {
1681        if (userId >= UserHandle.USER_OWNER) {
1682            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1683        } else if (userId == UserHandle.USER_ALL) {
1684            final int[] userIds;
1685            synchronized (mPackages) {
1686                userIds = UserManagerService.getInstance().getUserIds();
1687            }
1688            for (int someUserId : userIds) {
1689                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1690            }
1691        }
1692
1693        // We could have touched GID membership, so flush out packages.list
1694        synchronized (mPackages) {
1695            mSettings.writePackageListLPr();
1696        }
1697    }
1698
1699    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1700            String[] grantedPermissions) {
1701        SettingBase sb = (SettingBase) pkg.mExtras;
1702        if (sb == null) {
1703            return;
1704        }
1705
1706        PermissionsState permissionsState = sb.getPermissionsState();
1707
1708        for (String permission : pkg.requestedPermissions) {
1709            BasePermission bp = mSettings.mPermissions.get(permission);
1710            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1711                    || ArrayUtils.contains(grantedPermissions, permission))) {
1712                permissionsState.grantRuntimePermission(bp, userId);
1713            }
1714        }
1715    }
1716
1717    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1718        Bundle extras = null;
1719        switch (res.returnCode) {
1720            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1721                extras = new Bundle();
1722                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1723                        res.origPermission);
1724                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1725                        res.origPackage);
1726                break;
1727            }
1728            case PackageManager.INSTALL_SUCCEEDED: {
1729                extras = new Bundle();
1730                extras.putBoolean(Intent.EXTRA_REPLACING,
1731                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1732                break;
1733            }
1734        }
1735        return extras;
1736    }
1737
1738    void scheduleWriteSettingsLocked() {
1739        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1740            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1741        }
1742    }
1743
1744    void scheduleWritePackageRestrictionsLocked(int userId) {
1745        if (!sUserManager.exists(userId)) return;
1746        mDirtyUsers.add(userId);
1747        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1748            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1749        }
1750    }
1751
1752    public static PackageManagerService main(Context context, Installer installer,
1753            boolean factoryTest, boolean onlyCore) {
1754        PackageManagerService m = new PackageManagerService(context, installer,
1755                factoryTest, onlyCore);
1756        ServiceManager.addService("package", m);
1757        return m;
1758    }
1759
1760    static String[] splitString(String str, char sep) {
1761        int count = 1;
1762        int i = 0;
1763        while ((i=str.indexOf(sep, i)) >= 0) {
1764            count++;
1765            i++;
1766        }
1767
1768        String[] res = new String[count];
1769        i=0;
1770        count = 0;
1771        int lastI=0;
1772        while ((i=str.indexOf(sep, i)) >= 0) {
1773            res[count] = str.substring(lastI, i);
1774            count++;
1775            i++;
1776            lastI = i;
1777        }
1778        res[count] = str.substring(lastI, str.length());
1779        return res;
1780    }
1781
1782    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1783        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1784                Context.DISPLAY_SERVICE);
1785        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1786    }
1787
1788    public PackageManagerService(Context context, Installer installer,
1789            boolean factoryTest, boolean onlyCore) {
1790        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1791                SystemClock.uptimeMillis());
1792
1793        if (mSdkVersion <= 0) {
1794            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1795        }
1796
1797        mContext = context;
1798        mFactoryTest = factoryTest;
1799        mOnlyCore = onlyCore;
1800        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1801        mMetrics = new DisplayMetrics();
1802        mSettings = new Settings(mPackages);
1803        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1804                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1805        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1806                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1807        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1808                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1809        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1810                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1811        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1812                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1813        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1814                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1815
1816        // TODO: add a property to control this?
1817        long dexOptLRUThresholdInMinutes;
1818        if (mLazyDexOpt) {
1819            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1820        } else {
1821            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1822        }
1823        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1824
1825        String separateProcesses = SystemProperties.get("debug.separate_processes");
1826        if (separateProcesses != null && separateProcesses.length() > 0) {
1827            if ("*".equals(separateProcesses)) {
1828                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1829                mSeparateProcesses = null;
1830                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1831            } else {
1832                mDefParseFlags = 0;
1833                mSeparateProcesses = separateProcesses.split(",");
1834                Slog.w(TAG, "Running with debug.separate_processes: "
1835                        + separateProcesses);
1836            }
1837        } else {
1838            mDefParseFlags = 0;
1839            mSeparateProcesses = null;
1840        }
1841
1842        mInstaller = installer;
1843        mPackageDexOptimizer = new PackageDexOptimizer(this);
1844        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1845
1846        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1847                FgThread.get().getLooper());
1848
1849        getDefaultDisplayMetrics(context, mMetrics);
1850
1851        SystemConfig systemConfig = SystemConfig.getInstance();
1852        mGlobalGids = systemConfig.getGlobalGids();
1853        mSystemPermissions = systemConfig.getSystemPermissions();
1854        mAvailableFeatures = systemConfig.getAvailableFeatures();
1855
1856        synchronized (mInstallLock) {
1857        // writer
1858        synchronized (mPackages) {
1859            mHandlerThread = new ServiceThread(TAG,
1860                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1861            mHandlerThread.start();
1862            mHandler = new PackageHandler(mHandlerThread.getLooper());
1863            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1864
1865            File dataDir = Environment.getDataDirectory();
1866            mAppDataDir = new File(dataDir, "data");
1867            mAppInstallDir = new File(dataDir, "app");
1868            mAppLib32InstallDir = new File(dataDir, "app-lib");
1869            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1870            mUserAppDataDir = new File(dataDir, "user");
1871            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1872
1873            sUserManager = new UserManagerService(context, this,
1874                    mInstallLock, mPackages);
1875
1876            // Propagate permission configuration in to package manager.
1877            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1878                    = systemConfig.getPermissions();
1879            for (int i=0; i<permConfig.size(); i++) {
1880                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1881                BasePermission bp = mSettings.mPermissions.get(perm.name);
1882                if (bp == null) {
1883                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1884                    mSettings.mPermissions.put(perm.name, bp);
1885                }
1886                if (perm.gids != null) {
1887                    bp.setGids(perm.gids, perm.perUser);
1888                }
1889            }
1890
1891            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1892            for (int i=0; i<libConfig.size(); i++) {
1893                mSharedLibraries.put(libConfig.keyAt(i),
1894                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1895            }
1896
1897            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1898
1899            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1900                    mSdkVersion, mOnlyCore);
1901
1902            String customResolverActivity = Resources.getSystem().getString(
1903                    R.string.config_customResolverActivity);
1904            if (TextUtils.isEmpty(customResolverActivity)) {
1905                customResolverActivity = null;
1906            } else {
1907                mCustomResolverComponentName = ComponentName.unflattenFromString(
1908                        customResolverActivity);
1909            }
1910
1911            long startTime = SystemClock.uptimeMillis();
1912
1913            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1914                    startTime);
1915
1916            // Set flag to monitor and not change apk file paths when
1917            // scanning install directories.
1918            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1919
1920            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1921
1922            /**
1923             * Add everything in the in the boot class path to the
1924             * list of process files because dexopt will have been run
1925             * if necessary during zygote startup.
1926             */
1927            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1928            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1929
1930            if (bootClassPath != null) {
1931                String[] bootClassPathElements = splitString(bootClassPath, ':');
1932                for (String element : bootClassPathElements) {
1933                    alreadyDexOpted.add(element);
1934                }
1935            } else {
1936                Slog.w(TAG, "No BOOTCLASSPATH found!");
1937            }
1938
1939            if (systemServerClassPath != null) {
1940                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1941                for (String element : systemServerClassPathElements) {
1942                    alreadyDexOpted.add(element);
1943                }
1944            } else {
1945                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1946            }
1947
1948            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1949            final String[] dexCodeInstructionSets =
1950                    getDexCodeInstructionSets(
1951                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1952
1953            /**
1954             * Ensure all external libraries have had dexopt run on them.
1955             */
1956            if (mSharedLibraries.size() > 0) {
1957                // NOTE: For now, we're compiling these system "shared libraries"
1958                // (and framework jars) into all available architectures. It's possible
1959                // to compile them only when we come across an app that uses them (there's
1960                // already logic for that in scanPackageLI) but that adds some complexity.
1961                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1962                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1963                        final String lib = libEntry.path;
1964                        if (lib == null) {
1965                            continue;
1966                        }
1967
1968                        try {
1969                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1970                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1971                                alreadyDexOpted.add(lib);
1972                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1973                            }
1974                        } catch (FileNotFoundException e) {
1975                            Slog.w(TAG, "Library not found: " + lib);
1976                        } catch (IOException e) {
1977                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1978                                    + e.getMessage());
1979                        }
1980                    }
1981                }
1982            }
1983
1984            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1985
1986            // Gross hack for now: we know this file doesn't contain any
1987            // code, so don't dexopt it to avoid the resulting log spew.
1988            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1989
1990            // Gross hack for now: we know this file is only part of
1991            // the boot class path for art, so don't dexopt it to
1992            // avoid the resulting log spew.
1993            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1994
1995            /**
1996             * There are a number of commands implemented in Java, which
1997             * we currently need to do the dexopt on so that they can be
1998             * run from a non-root shell.
1999             */
2000            String[] frameworkFiles = frameworkDir.list();
2001            if (frameworkFiles != null) {
2002                // TODO: We could compile these only for the most preferred ABI. We should
2003                // first double check that the dex files for these commands are not referenced
2004                // by other system apps.
2005                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2006                    for (int i=0; i<frameworkFiles.length; i++) {
2007                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2008                        String path = libPath.getPath();
2009                        // Skip the file if we already did it.
2010                        if (alreadyDexOpted.contains(path)) {
2011                            continue;
2012                        }
2013                        // Skip the file if it is not a type we want to dexopt.
2014                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2015                            continue;
2016                        }
2017                        try {
2018                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2019                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2020                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2021                            }
2022                        } catch (FileNotFoundException e) {
2023                            Slog.w(TAG, "Jar not found: " + path);
2024                        } catch (IOException e) {
2025                            Slog.w(TAG, "Exception reading jar: " + path, e);
2026                        }
2027                    }
2028                }
2029            }
2030
2031            // Collect vendor overlay packages.
2032            // (Do this before scanning any apps.)
2033            // For security and version matching reason, only consider
2034            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2035            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2036            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2037                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2038
2039            // Find base frameworks (resource packages without code).
2040            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2041                    | PackageParser.PARSE_IS_SYSTEM_DIR
2042                    | PackageParser.PARSE_IS_PRIVILEGED,
2043                    scanFlags | SCAN_NO_DEX, 0);
2044
2045            // Collected privileged system packages.
2046            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2047            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2048                    | PackageParser.PARSE_IS_SYSTEM_DIR
2049                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2050
2051            // Collect ordinary system packages.
2052            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2053            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2054                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2055
2056            // Collect all vendor packages.
2057            File vendorAppDir = new File("/vendor/app");
2058            try {
2059                vendorAppDir = vendorAppDir.getCanonicalFile();
2060            } catch (IOException e) {
2061                // failed to look up canonical path, continue with original one
2062            }
2063            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2064                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2065
2066            // Collect all OEM packages.
2067            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2068            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2069                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2070
2071            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2072            mInstaller.moveFiles();
2073
2074            // Prune any system packages that no longer exist.
2075            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2076            if (!mOnlyCore) {
2077                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2078                while (psit.hasNext()) {
2079                    PackageSetting ps = psit.next();
2080
2081                    /*
2082                     * If this is not a system app, it can't be a
2083                     * disable system app.
2084                     */
2085                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2086                        continue;
2087                    }
2088
2089                    /*
2090                     * If the package is scanned, it's not erased.
2091                     */
2092                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2093                    if (scannedPkg != null) {
2094                        /*
2095                         * If the system app is both scanned and in the
2096                         * disabled packages list, then it must have been
2097                         * added via OTA. Remove it from the currently
2098                         * scanned package so the previously user-installed
2099                         * application can be scanned.
2100                         */
2101                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2102                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2103                                    + ps.name + "; removing system app.  Last known codePath="
2104                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2105                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2106                                    + scannedPkg.mVersionCode);
2107                            removePackageLI(ps, true);
2108                            mExpectingBetter.put(ps.name, ps.codePath);
2109                        }
2110
2111                        continue;
2112                    }
2113
2114                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2115                        psit.remove();
2116                        logCriticalInfo(Log.WARN, "System package " + ps.name
2117                                + " no longer exists; wiping its data");
2118                        removeDataDirsLI(null, ps.name);
2119                    } else {
2120                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2121                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2122                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2123                        }
2124                    }
2125                }
2126            }
2127
2128            //look for any incomplete package installations
2129            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2130            //clean up list
2131            for(int i = 0; i < deletePkgsList.size(); i++) {
2132                //clean up here
2133                cleanupInstallFailedPackage(deletePkgsList.get(i));
2134            }
2135            //delete tmp files
2136            deleteTempPackageFiles();
2137
2138            // Remove any shared userIDs that have no associated packages
2139            mSettings.pruneSharedUsersLPw();
2140
2141            if (!mOnlyCore) {
2142                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2143                        SystemClock.uptimeMillis());
2144                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2145
2146                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2147                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2148
2149                /**
2150                 * Remove disable package settings for any updated system
2151                 * apps that were removed via an OTA. If they're not a
2152                 * previously-updated app, remove them completely.
2153                 * Otherwise, just revoke their system-level permissions.
2154                 */
2155                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2156                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2157                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2158
2159                    String msg;
2160                    if (deletedPkg == null) {
2161                        msg = "Updated system package " + deletedAppName
2162                                + " no longer exists; wiping its data";
2163                        removeDataDirsLI(null, deletedAppName);
2164                    } else {
2165                        msg = "Updated system app + " + deletedAppName
2166                                + " no longer present; removing system privileges for "
2167                                + deletedAppName;
2168
2169                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2170
2171                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2172                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2173                    }
2174                    logCriticalInfo(Log.WARN, msg);
2175                }
2176
2177                /**
2178                 * Make sure all system apps that we expected to appear on
2179                 * the userdata partition actually showed up. If they never
2180                 * appeared, crawl back and revive the system version.
2181                 */
2182                for (int i = 0; i < mExpectingBetter.size(); i++) {
2183                    final String packageName = mExpectingBetter.keyAt(i);
2184                    if (!mPackages.containsKey(packageName)) {
2185                        final File scanFile = mExpectingBetter.valueAt(i);
2186
2187                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2188                                + " but never showed up; reverting to system");
2189
2190                        final int reparseFlags;
2191                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2192                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2193                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2194                                    | PackageParser.PARSE_IS_PRIVILEGED;
2195                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2196                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2197                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2198                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2199                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2200                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2201                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2202                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2203                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2204                        } else {
2205                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2206                            continue;
2207                        }
2208
2209                        mSettings.enableSystemPackageLPw(packageName);
2210
2211                        try {
2212                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2213                        } catch (PackageManagerException e) {
2214                            Slog.e(TAG, "Failed to parse original system package: "
2215                                    + e.getMessage());
2216                        }
2217                    }
2218                }
2219            }
2220            mExpectingBetter.clear();
2221
2222            // Now that we know all of the shared libraries, update all clients to have
2223            // the correct library paths.
2224            updateAllSharedLibrariesLPw();
2225
2226            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2227                // NOTE: We ignore potential failures here during a system scan (like
2228                // the rest of the commands above) because there's precious little we
2229                // can do about it. A settings error is reported, though.
2230                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2231                        false /* force dexopt */, false /* defer dexopt */);
2232            }
2233
2234            // Now that we know all the packages we are keeping,
2235            // read and update their last usage times.
2236            mPackageUsage.readLP();
2237
2238            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2239                    SystemClock.uptimeMillis());
2240            Slog.i(TAG, "Time to scan packages: "
2241                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2242                    + " seconds");
2243
2244            // If the platform SDK has changed since the last time we booted,
2245            // we need to re-grant app permission to catch any new ones that
2246            // appear.  This is really a hack, and means that apps can in some
2247            // cases get permissions that the user didn't initially explicitly
2248            // allow...  it would be nice to have some better way to handle
2249            // this situation.
2250            final VersionInfo ver = mSettings.getInternalVersion();
2251
2252            int updateFlags = UPDATE_PERMISSIONS_ALL;
2253            if (ver.sdkVersion != mSdkVersion) {
2254                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2255                        + mSdkVersion + "; regranting permissions for internal storage");
2256                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2257            }
2258            updatePermissionsLPw(null, null, updateFlags);
2259            ver.sdkVersion = mSdkVersion;
2260
2261            // If this is the first boot, and it is a normal boot, then
2262            // we need to initialize the default preferred apps.
2263            if (!mRestoredSettings && !onlyCore) {
2264                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2265                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2266                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2267            }
2268
2269            // If this is first boot after an OTA, and a normal boot, then
2270            // we need to clear code cache directories.
2271            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2272            if (mIsUpgrade && !onlyCore) {
2273                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2274                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2275                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2276                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2277                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2278                    }
2279                }
2280                ver.fingerprint = Build.FINGERPRINT;
2281            }
2282
2283            checkDefaultBrowser();
2284
2285            // All the changes are done during package scanning.
2286            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2287
2288            // can downgrade to reader
2289            mSettings.writeLPr();
2290
2291            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2292                    SystemClock.uptimeMillis());
2293
2294            mRequiredVerifierPackage = getRequiredVerifierLPr();
2295            mRequiredInstallerPackage = getRequiredInstallerLPr();
2296
2297            mInstallerService = new PackageInstallerService(context, this);
2298
2299            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2300            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2301                    mIntentFilterVerifierComponent);
2302
2303        } // synchronized (mPackages)
2304        } // synchronized (mInstallLock)
2305
2306        // Now after opening every single application zip, make sure they
2307        // are all flushed.  Not really needed, but keeps things nice and
2308        // tidy.
2309        Runtime.getRuntime().gc();
2310
2311        // Expose private service for system components to use.
2312        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2313    }
2314
2315    @Override
2316    public boolean isFirstBoot() {
2317        return !mRestoredSettings;
2318    }
2319
2320    @Override
2321    public boolean isOnlyCoreApps() {
2322        return mOnlyCore;
2323    }
2324
2325    @Override
2326    public boolean isUpgrade() {
2327        return mIsUpgrade;
2328    }
2329
2330    private String getRequiredVerifierLPr() {
2331        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2332        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2333                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2334
2335        String requiredVerifier = null;
2336
2337        final int N = receivers.size();
2338        for (int i = 0; i < N; i++) {
2339            final ResolveInfo info = receivers.get(i);
2340
2341            if (info.activityInfo == null) {
2342                continue;
2343            }
2344
2345            final String packageName = info.activityInfo.packageName;
2346
2347            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2348                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2349                continue;
2350            }
2351
2352            if (requiredVerifier != null) {
2353                throw new RuntimeException("There can be only one required verifier");
2354            }
2355
2356            requiredVerifier = packageName;
2357        }
2358
2359        return requiredVerifier;
2360    }
2361
2362    private String getRequiredInstallerLPr() {
2363        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2364        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2365        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2366
2367        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2368                PACKAGE_MIME_TYPE, 0, 0);
2369
2370        String requiredInstaller = null;
2371
2372        final int N = installers.size();
2373        for (int i = 0; i < N; i++) {
2374            final ResolveInfo info = installers.get(i);
2375            final String packageName = info.activityInfo.packageName;
2376
2377            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2378                continue;
2379            }
2380
2381            if (requiredInstaller != null) {
2382                throw new RuntimeException("There must be one required installer");
2383            }
2384
2385            requiredInstaller = packageName;
2386        }
2387
2388        if (requiredInstaller == null) {
2389            throw new RuntimeException("There must be one required installer");
2390        }
2391
2392        return requiredInstaller;
2393    }
2394
2395    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2396        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2397        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2398                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2399
2400        ComponentName verifierComponentName = null;
2401
2402        int priority = -1000;
2403        final int N = receivers.size();
2404        for (int i = 0; i < N; i++) {
2405            final ResolveInfo info = receivers.get(i);
2406
2407            if (info.activityInfo == null) {
2408                continue;
2409            }
2410
2411            final String packageName = info.activityInfo.packageName;
2412
2413            final PackageSetting ps = mSettings.mPackages.get(packageName);
2414            if (ps == null) {
2415                continue;
2416            }
2417
2418            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2419                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2420                continue;
2421            }
2422
2423            // Select the IntentFilterVerifier with the highest priority
2424            if (priority < info.priority) {
2425                priority = info.priority;
2426                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2427                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2428                        + verifierComponentName + " with priority: " + info.priority);
2429            }
2430        }
2431
2432        return verifierComponentName;
2433    }
2434
2435    private void primeDomainVerificationsLPw(int userId) {
2436        if (DEBUG_DOMAIN_VERIFICATION) {
2437            Slog.d(TAG, "Priming domain verifications in user " + userId);
2438        }
2439
2440        SystemConfig systemConfig = SystemConfig.getInstance();
2441        ArraySet<String> packages = systemConfig.getLinkedApps();
2442        ArraySet<String> domains = new ArraySet<String>();
2443
2444        for (String packageName : packages) {
2445            PackageParser.Package pkg = mPackages.get(packageName);
2446            if (pkg != null) {
2447                if (!pkg.isSystemApp()) {
2448                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2449                    continue;
2450                }
2451
2452                domains.clear();
2453                for (PackageParser.Activity a : pkg.activities) {
2454                    for (ActivityIntentInfo filter : a.intents) {
2455                        if (hasValidDomains(filter)) {
2456                            domains.addAll(filter.getHostsList());
2457                        }
2458                    }
2459                }
2460
2461                if (domains.size() > 0) {
2462                    if (DEBUG_DOMAIN_VERIFICATION) {
2463                        Slog.v(TAG, "      + " + packageName);
2464                    }
2465                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2466                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2467                    // and then 'always' in the per-user state actually used for intent resolution.
2468                    final IntentFilterVerificationInfo ivi;
2469                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2470                            new ArrayList<String>(domains));
2471                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2472                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2473                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2474                } else {
2475                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2476                            + "' does not handle web links");
2477                }
2478            } else {
2479                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2480            }
2481        }
2482
2483        scheduleWritePackageRestrictionsLocked(userId);
2484        scheduleWriteSettingsLocked();
2485    }
2486
2487    private void applyFactoryDefaultBrowserLPw(int userId) {
2488        // The default browser app's package name is stored in a string resource,
2489        // with a product-specific overlay used for vendor customization.
2490        String browserPkg = mContext.getResources().getString(
2491                com.android.internal.R.string.default_browser);
2492        if (!TextUtils.isEmpty(browserPkg)) {
2493            // non-empty string => required to be a known package
2494            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2495            if (ps == null) {
2496                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2497                browserPkg = null;
2498            } else {
2499                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2500            }
2501        }
2502
2503        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2504        // default.  If there's more than one, just leave everything alone.
2505        if (browserPkg == null) {
2506            calculateDefaultBrowserLPw(userId);
2507        }
2508    }
2509
2510    private void calculateDefaultBrowserLPw(int userId) {
2511        List<String> allBrowsers = resolveAllBrowserApps(userId);
2512        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2513        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2514    }
2515
2516    private List<String> resolveAllBrowserApps(int userId) {
2517        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2518        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2519                PackageManager.MATCH_ALL, userId);
2520
2521        final int count = list.size();
2522        List<String> result = new ArrayList<String>(count);
2523        for (int i=0; i<count; i++) {
2524            ResolveInfo info = list.get(i);
2525            if (info.activityInfo == null
2526                    || !info.handleAllWebDataURI
2527                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2528                    || result.contains(info.activityInfo.packageName)) {
2529                continue;
2530            }
2531            result.add(info.activityInfo.packageName);
2532        }
2533
2534        return result;
2535    }
2536
2537    private boolean packageIsBrowser(String packageName, int userId) {
2538        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2539                PackageManager.MATCH_ALL, userId);
2540        final int N = list.size();
2541        for (int i = 0; i < N; i++) {
2542            ResolveInfo info = list.get(i);
2543            if (packageName.equals(info.activityInfo.packageName)) {
2544                return true;
2545            }
2546        }
2547        return false;
2548    }
2549
2550    private void checkDefaultBrowser() {
2551        final int myUserId = UserHandle.myUserId();
2552        final String packageName = getDefaultBrowserPackageName(myUserId);
2553        if (packageName != null) {
2554            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2555            if (info == null) {
2556                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2557                synchronized (mPackages) {
2558                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2559                }
2560            }
2561        }
2562    }
2563
2564    @Override
2565    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2566            throws RemoteException {
2567        try {
2568            return super.onTransact(code, data, reply, flags);
2569        } catch (RuntimeException e) {
2570            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2571                Slog.wtf(TAG, "Package Manager Crash", e);
2572            }
2573            throw e;
2574        }
2575    }
2576
2577    void cleanupInstallFailedPackage(PackageSetting ps) {
2578        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2579
2580        removeDataDirsLI(ps.volumeUuid, ps.name);
2581        if (ps.codePath != null) {
2582            if (ps.codePath.isDirectory()) {
2583                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2584            } else {
2585                ps.codePath.delete();
2586            }
2587        }
2588        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2589            if (ps.resourcePath.isDirectory()) {
2590                FileUtils.deleteContents(ps.resourcePath);
2591            }
2592            ps.resourcePath.delete();
2593        }
2594        mSettings.removePackageLPw(ps.name);
2595    }
2596
2597    static int[] appendInts(int[] cur, int[] add) {
2598        if (add == null) return cur;
2599        if (cur == null) return add;
2600        final int N = add.length;
2601        for (int i=0; i<N; i++) {
2602            cur = appendInt(cur, add[i]);
2603        }
2604        return cur;
2605    }
2606
2607    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2608        if (!sUserManager.exists(userId)) return null;
2609        final PackageSetting ps = (PackageSetting) p.mExtras;
2610        if (ps == null) {
2611            return null;
2612        }
2613
2614        final PermissionsState permissionsState = ps.getPermissionsState();
2615
2616        final int[] gids = permissionsState.computeGids(userId);
2617        final Set<String> permissions = permissionsState.getPermissions(userId);
2618        final PackageUserState state = ps.readUserState(userId);
2619
2620        return PackageParser.generatePackageInfo(p, gids, flags,
2621                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2622    }
2623
2624    @Override
2625    public boolean isPackageFrozen(String packageName) {
2626        synchronized (mPackages) {
2627            final PackageSetting ps = mSettings.mPackages.get(packageName);
2628            if (ps != null) {
2629                return ps.frozen;
2630            }
2631        }
2632        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2633        return true;
2634    }
2635
2636    @Override
2637    public boolean isPackageAvailable(String packageName, int userId) {
2638        if (!sUserManager.exists(userId)) return false;
2639        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2640        synchronized (mPackages) {
2641            PackageParser.Package p = mPackages.get(packageName);
2642            if (p != null) {
2643                final PackageSetting ps = (PackageSetting) p.mExtras;
2644                if (ps != null) {
2645                    final PackageUserState state = ps.readUserState(userId);
2646                    if (state != null) {
2647                        return PackageParser.isAvailable(state);
2648                    }
2649                }
2650            }
2651        }
2652        return false;
2653    }
2654
2655    @Override
2656    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2657        if (!sUserManager.exists(userId)) return null;
2658        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2659        // reader
2660        synchronized (mPackages) {
2661            PackageParser.Package p = mPackages.get(packageName);
2662            if (DEBUG_PACKAGE_INFO)
2663                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2664            if (p != null) {
2665                return generatePackageInfo(p, flags, userId);
2666            }
2667            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2668                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2669            }
2670        }
2671        return null;
2672    }
2673
2674    @Override
2675    public String[] currentToCanonicalPackageNames(String[] names) {
2676        String[] out = new String[names.length];
2677        // reader
2678        synchronized (mPackages) {
2679            for (int i=names.length-1; i>=0; i--) {
2680                PackageSetting ps = mSettings.mPackages.get(names[i]);
2681                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2682            }
2683        }
2684        return out;
2685    }
2686
2687    @Override
2688    public String[] canonicalToCurrentPackageNames(String[] names) {
2689        String[] out = new String[names.length];
2690        // reader
2691        synchronized (mPackages) {
2692            for (int i=names.length-1; i>=0; i--) {
2693                String cur = mSettings.mRenamedPackages.get(names[i]);
2694                out[i] = cur != null ? cur : names[i];
2695            }
2696        }
2697        return out;
2698    }
2699
2700    @Override
2701    public int getPackageUid(String packageName, int userId) {
2702        if (!sUserManager.exists(userId)) return -1;
2703        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2704
2705        // reader
2706        synchronized (mPackages) {
2707            PackageParser.Package p = mPackages.get(packageName);
2708            if(p != null) {
2709                return UserHandle.getUid(userId, p.applicationInfo.uid);
2710            }
2711            PackageSetting ps = mSettings.mPackages.get(packageName);
2712            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2713                return -1;
2714            }
2715            p = ps.pkg;
2716            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2717        }
2718    }
2719
2720    @Override
2721    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2722        if (!sUserManager.exists(userId)) {
2723            return null;
2724        }
2725
2726        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2727                "getPackageGids");
2728
2729        // reader
2730        synchronized (mPackages) {
2731            PackageParser.Package p = mPackages.get(packageName);
2732            if (DEBUG_PACKAGE_INFO) {
2733                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2734            }
2735            if (p != null) {
2736                PackageSetting ps = (PackageSetting) p.mExtras;
2737                return ps.getPermissionsState().computeGids(userId);
2738            }
2739        }
2740
2741        return null;
2742    }
2743
2744    static PermissionInfo generatePermissionInfo(
2745            BasePermission bp, int flags) {
2746        if (bp.perm != null) {
2747            return PackageParser.generatePermissionInfo(bp.perm, flags);
2748        }
2749        PermissionInfo pi = new PermissionInfo();
2750        pi.name = bp.name;
2751        pi.packageName = bp.sourcePackage;
2752        pi.nonLocalizedLabel = bp.name;
2753        pi.protectionLevel = bp.protectionLevel;
2754        return pi;
2755    }
2756
2757    @Override
2758    public PermissionInfo getPermissionInfo(String name, int flags) {
2759        // reader
2760        synchronized (mPackages) {
2761            final BasePermission p = mSettings.mPermissions.get(name);
2762            if (p != null) {
2763                return generatePermissionInfo(p, flags);
2764            }
2765            return null;
2766        }
2767    }
2768
2769    @Override
2770    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2771        // reader
2772        synchronized (mPackages) {
2773            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2774            for (BasePermission p : mSettings.mPermissions.values()) {
2775                if (group == null) {
2776                    if (p.perm == null || p.perm.info.group == null) {
2777                        out.add(generatePermissionInfo(p, flags));
2778                    }
2779                } else {
2780                    if (p.perm != null && group.equals(p.perm.info.group)) {
2781                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2782                    }
2783                }
2784            }
2785
2786            if (out.size() > 0) {
2787                return out;
2788            }
2789            return mPermissionGroups.containsKey(group) ? out : null;
2790        }
2791    }
2792
2793    @Override
2794    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2795        // reader
2796        synchronized (mPackages) {
2797            return PackageParser.generatePermissionGroupInfo(
2798                    mPermissionGroups.get(name), flags);
2799        }
2800    }
2801
2802    @Override
2803    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2804        // reader
2805        synchronized (mPackages) {
2806            final int N = mPermissionGroups.size();
2807            ArrayList<PermissionGroupInfo> out
2808                    = new ArrayList<PermissionGroupInfo>(N);
2809            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2810                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2811            }
2812            return out;
2813        }
2814    }
2815
2816    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2817            int userId) {
2818        if (!sUserManager.exists(userId)) return null;
2819        PackageSetting ps = mSettings.mPackages.get(packageName);
2820        if (ps != null) {
2821            if (ps.pkg == null) {
2822                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2823                        flags, userId);
2824                if (pInfo != null) {
2825                    return pInfo.applicationInfo;
2826                }
2827                return null;
2828            }
2829            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2830                    ps.readUserState(userId), userId);
2831        }
2832        return null;
2833    }
2834
2835    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2836            int userId) {
2837        if (!sUserManager.exists(userId)) return null;
2838        PackageSetting ps = mSettings.mPackages.get(packageName);
2839        if (ps != null) {
2840            PackageParser.Package pkg = ps.pkg;
2841            if (pkg == null) {
2842                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2843                    return null;
2844                }
2845                // Only data remains, so we aren't worried about code paths
2846                pkg = new PackageParser.Package(packageName);
2847                pkg.applicationInfo.packageName = packageName;
2848                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2849                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2850                pkg.applicationInfo.dataDir = Environment
2851                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2852                        .getAbsolutePath();
2853                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2854                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2855            }
2856            return generatePackageInfo(pkg, flags, userId);
2857        }
2858        return null;
2859    }
2860
2861    @Override
2862    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2863        if (!sUserManager.exists(userId)) return null;
2864        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2865        // writer
2866        synchronized (mPackages) {
2867            PackageParser.Package p = mPackages.get(packageName);
2868            if (DEBUG_PACKAGE_INFO) Log.v(
2869                    TAG, "getApplicationInfo " + packageName
2870                    + ": " + p);
2871            if (p != null) {
2872                PackageSetting ps = mSettings.mPackages.get(packageName);
2873                if (ps == null) return null;
2874                // Note: isEnabledLP() does not apply here - always return info
2875                return PackageParser.generateApplicationInfo(
2876                        p, flags, ps.readUserState(userId), userId);
2877            }
2878            if ("android".equals(packageName)||"system".equals(packageName)) {
2879                return mAndroidApplication;
2880            }
2881            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2882                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2883            }
2884        }
2885        return null;
2886    }
2887
2888    @Override
2889    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2890            final IPackageDataObserver observer) {
2891        mContext.enforceCallingOrSelfPermission(
2892                android.Manifest.permission.CLEAR_APP_CACHE, null);
2893        // Queue up an async operation since clearing cache may take a little while.
2894        mHandler.post(new Runnable() {
2895            public void run() {
2896                mHandler.removeCallbacks(this);
2897                int retCode = -1;
2898                synchronized (mInstallLock) {
2899                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2900                    if (retCode < 0) {
2901                        Slog.w(TAG, "Couldn't clear application caches");
2902                    }
2903                }
2904                if (observer != null) {
2905                    try {
2906                        observer.onRemoveCompleted(null, (retCode >= 0));
2907                    } catch (RemoteException e) {
2908                        Slog.w(TAG, "RemoveException when invoking call back");
2909                    }
2910                }
2911            }
2912        });
2913    }
2914
2915    @Override
2916    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2917            final IntentSender pi) {
2918        mContext.enforceCallingOrSelfPermission(
2919                android.Manifest.permission.CLEAR_APP_CACHE, null);
2920        // Queue up an async operation since clearing cache may take a little while.
2921        mHandler.post(new Runnable() {
2922            public void run() {
2923                mHandler.removeCallbacks(this);
2924                int retCode = -1;
2925                synchronized (mInstallLock) {
2926                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2927                    if (retCode < 0) {
2928                        Slog.w(TAG, "Couldn't clear application caches");
2929                    }
2930                }
2931                if(pi != null) {
2932                    try {
2933                        // Callback via pending intent
2934                        int code = (retCode >= 0) ? 1 : 0;
2935                        pi.sendIntent(null, code, null,
2936                                null, null);
2937                    } catch (SendIntentException e1) {
2938                        Slog.i(TAG, "Failed to send pending intent");
2939                    }
2940                }
2941            }
2942        });
2943    }
2944
2945    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2946        synchronized (mInstallLock) {
2947            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2948                throw new IOException("Failed to free enough space");
2949            }
2950        }
2951    }
2952
2953    @Override
2954    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2955        if (!sUserManager.exists(userId)) return null;
2956        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2957        synchronized (mPackages) {
2958            PackageParser.Activity a = mActivities.mActivities.get(component);
2959
2960            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2961            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2962                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2963                if (ps == null) return null;
2964                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2965                        userId);
2966            }
2967            if (mResolveComponentName.equals(component)) {
2968                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2969                        new PackageUserState(), userId);
2970            }
2971        }
2972        return null;
2973    }
2974
2975    @Override
2976    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2977            String resolvedType) {
2978        synchronized (mPackages) {
2979            if (component.equals(mResolveComponentName)) {
2980                // The resolver supports EVERYTHING!
2981                return true;
2982            }
2983            PackageParser.Activity a = mActivities.mActivities.get(component);
2984            if (a == null) {
2985                return false;
2986            }
2987            for (int i=0; i<a.intents.size(); i++) {
2988                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2989                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2990                    return true;
2991                }
2992            }
2993            return false;
2994        }
2995    }
2996
2997    @Override
2998    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2999        if (!sUserManager.exists(userId)) return null;
3000        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3001        synchronized (mPackages) {
3002            PackageParser.Activity a = mReceivers.mActivities.get(component);
3003            if (DEBUG_PACKAGE_INFO) Log.v(
3004                TAG, "getReceiverInfo " + component + ": " + a);
3005            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3006                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3007                if (ps == null) return null;
3008                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3009                        userId);
3010            }
3011        }
3012        return null;
3013    }
3014
3015    @Override
3016    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3017        if (!sUserManager.exists(userId)) return null;
3018        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3019        synchronized (mPackages) {
3020            PackageParser.Service s = mServices.mServices.get(component);
3021            if (DEBUG_PACKAGE_INFO) Log.v(
3022                TAG, "getServiceInfo " + component + ": " + s);
3023            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3024                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3025                if (ps == null) return null;
3026                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3027                        userId);
3028            }
3029        }
3030        return null;
3031    }
3032
3033    @Override
3034    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3035        if (!sUserManager.exists(userId)) return null;
3036        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3037        synchronized (mPackages) {
3038            PackageParser.Provider p = mProviders.mProviders.get(component);
3039            if (DEBUG_PACKAGE_INFO) Log.v(
3040                TAG, "getProviderInfo " + component + ": " + p);
3041            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3042                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3043                if (ps == null) return null;
3044                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3045                        userId);
3046            }
3047        }
3048        return null;
3049    }
3050
3051    @Override
3052    public String[] getSystemSharedLibraryNames() {
3053        Set<String> libSet;
3054        synchronized (mPackages) {
3055            libSet = mSharedLibraries.keySet();
3056            int size = libSet.size();
3057            if (size > 0) {
3058                String[] libs = new String[size];
3059                libSet.toArray(libs);
3060                return libs;
3061            }
3062        }
3063        return null;
3064    }
3065
3066    /**
3067     * @hide
3068     */
3069    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3070        synchronized (mPackages) {
3071            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3072            if (lib != null && lib.apk != null) {
3073                return mPackages.get(lib.apk);
3074            }
3075        }
3076        return null;
3077    }
3078
3079    @Override
3080    public FeatureInfo[] getSystemAvailableFeatures() {
3081        Collection<FeatureInfo> featSet;
3082        synchronized (mPackages) {
3083            featSet = mAvailableFeatures.values();
3084            int size = featSet.size();
3085            if (size > 0) {
3086                FeatureInfo[] features = new FeatureInfo[size+1];
3087                featSet.toArray(features);
3088                FeatureInfo fi = new FeatureInfo();
3089                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3090                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3091                features[size] = fi;
3092                return features;
3093            }
3094        }
3095        return null;
3096    }
3097
3098    @Override
3099    public boolean hasSystemFeature(String name) {
3100        synchronized (mPackages) {
3101            return mAvailableFeatures.containsKey(name);
3102        }
3103    }
3104
3105    private void checkValidCaller(int uid, int userId) {
3106        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3107            return;
3108
3109        throw new SecurityException("Caller uid=" + uid
3110                + " is not privileged to communicate with user=" + userId);
3111    }
3112
3113    @Override
3114    public int checkPermission(String permName, String pkgName, int userId) {
3115        if (!sUserManager.exists(userId)) {
3116            return PackageManager.PERMISSION_DENIED;
3117        }
3118
3119        synchronized (mPackages) {
3120            final PackageParser.Package p = mPackages.get(pkgName);
3121            if (p != null && p.mExtras != null) {
3122                final PackageSetting ps = (PackageSetting) p.mExtras;
3123                final PermissionsState permissionsState = ps.getPermissionsState();
3124                if (permissionsState.hasPermission(permName, userId)) {
3125                    return PackageManager.PERMISSION_GRANTED;
3126                }
3127                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3128                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3129                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3130                    return PackageManager.PERMISSION_GRANTED;
3131                }
3132            }
3133        }
3134
3135        return PackageManager.PERMISSION_DENIED;
3136    }
3137
3138    @Override
3139    public int checkUidPermission(String permName, int uid) {
3140        final int userId = UserHandle.getUserId(uid);
3141
3142        if (!sUserManager.exists(userId)) {
3143            return PackageManager.PERMISSION_DENIED;
3144        }
3145
3146        synchronized (mPackages) {
3147            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3148            if (obj != null) {
3149                final SettingBase ps = (SettingBase) obj;
3150                final PermissionsState permissionsState = ps.getPermissionsState();
3151                if (permissionsState.hasPermission(permName, userId)) {
3152                    return PackageManager.PERMISSION_GRANTED;
3153                }
3154                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3155                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3156                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3157                    return PackageManager.PERMISSION_GRANTED;
3158                }
3159            } else {
3160                ArraySet<String> perms = mSystemPermissions.get(uid);
3161                if (perms != null) {
3162                    if (perms.contains(permName)) {
3163                        return PackageManager.PERMISSION_GRANTED;
3164                    }
3165                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3166                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3167                        return PackageManager.PERMISSION_GRANTED;
3168                    }
3169                }
3170            }
3171        }
3172
3173        return PackageManager.PERMISSION_DENIED;
3174    }
3175
3176    @Override
3177    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3178        if (UserHandle.getCallingUserId() != userId) {
3179            mContext.enforceCallingPermission(
3180                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3181                    "isPermissionRevokedByPolicy for user " + userId);
3182        }
3183
3184        if (checkPermission(permission, packageName, userId)
3185                == PackageManager.PERMISSION_GRANTED) {
3186            return false;
3187        }
3188
3189        final long identity = Binder.clearCallingIdentity();
3190        try {
3191            final int flags = getPermissionFlags(permission, packageName, userId);
3192            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3193        } finally {
3194            Binder.restoreCallingIdentity(identity);
3195        }
3196    }
3197
3198    @Override
3199    public String getPermissionControllerPackageName() {
3200        synchronized (mPackages) {
3201            return mRequiredInstallerPackage;
3202        }
3203    }
3204
3205    /**
3206     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3207     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3208     * @param checkShell TODO(yamasani):
3209     * @param message the message to log on security exception
3210     */
3211    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3212            boolean checkShell, String message) {
3213        if (userId < 0) {
3214            throw new IllegalArgumentException("Invalid userId " + userId);
3215        }
3216        if (checkShell) {
3217            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3218        }
3219        if (userId == UserHandle.getUserId(callingUid)) return;
3220        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3221            if (requireFullPermission) {
3222                mContext.enforceCallingOrSelfPermission(
3223                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3224            } else {
3225                try {
3226                    mContext.enforceCallingOrSelfPermission(
3227                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3228                } catch (SecurityException se) {
3229                    mContext.enforceCallingOrSelfPermission(
3230                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3231                }
3232            }
3233        }
3234    }
3235
3236    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3237        if (callingUid == Process.SHELL_UID) {
3238            if (userHandle >= 0
3239                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3240                throw new SecurityException("Shell does not have permission to access user "
3241                        + userHandle);
3242            } else if (userHandle < 0) {
3243                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3244                        + Debug.getCallers(3));
3245            }
3246        }
3247    }
3248
3249    private BasePermission findPermissionTreeLP(String permName) {
3250        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3251            if (permName.startsWith(bp.name) &&
3252                    permName.length() > bp.name.length() &&
3253                    permName.charAt(bp.name.length()) == '.') {
3254                return bp;
3255            }
3256        }
3257        return null;
3258    }
3259
3260    private BasePermission checkPermissionTreeLP(String permName) {
3261        if (permName != null) {
3262            BasePermission bp = findPermissionTreeLP(permName);
3263            if (bp != null) {
3264                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3265                    return bp;
3266                }
3267                throw new SecurityException("Calling uid "
3268                        + Binder.getCallingUid()
3269                        + " is not allowed to add to permission tree "
3270                        + bp.name + " owned by uid " + bp.uid);
3271            }
3272        }
3273        throw new SecurityException("No permission tree found for " + permName);
3274    }
3275
3276    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3277        if (s1 == null) {
3278            return s2 == null;
3279        }
3280        if (s2 == null) {
3281            return false;
3282        }
3283        if (s1.getClass() != s2.getClass()) {
3284            return false;
3285        }
3286        return s1.equals(s2);
3287    }
3288
3289    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3290        if (pi1.icon != pi2.icon) return false;
3291        if (pi1.logo != pi2.logo) return false;
3292        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3293        if (!compareStrings(pi1.name, pi2.name)) return false;
3294        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3295        // We'll take care of setting this one.
3296        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3297        // These are not currently stored in settings.
3298        //if (!compareStrings(pi1.group, pi2.group)) return false;
3299        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3300        //if (pi1.labelRes != pi2.labelRes) return false;
3301        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3302        return true;
3303    }
3304
3305    int permissionInfoFootprint(PermissionInfo info) {
3306        int size = info.name.length();
3307        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3308        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3309        return size;
3310    }
3311
3312    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3313        int size = 0;
3314        for (BasePermission perm : mSettings.mPermissions.values()) {
3315            if (perm.uid == tree.uid) {
3316                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3317            }
3318        }
3319        return size;
3320    }
3321
3322    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3323        // We calculate the max size of permissions defined by this uid and throw
3324        // if that plus the size of 'info' would exceed our stated maximum.
3325        if (tree.uid != Process.SYSTEM_UID) {
3326            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3327            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3328                throw new SecurityException("Permission tree size cap exceeded");
3329            }
3330        }
3331    }
3332
3333    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3334        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3335            throw new SecurityException("Label must be specified in permission");
3336        }
3337        BasePermission tree = checkPermissionTreeLP(info.name);
3338        BasePermission bp = mSettings.mPermissions.get(info.name);
3339        boolean added = bp == null;
3340        boolean changed = true;
3341        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3342        if (added) {
3343            enforcePermissionCapLocked(info, tree);
3344            bp = new BasePermission(info.name, tree.sourcePackage,
3345                    BasePermission.TYPE_DYNAMIC);
3346        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3347            throw new SecurityException(
3348                    "Not allowed to modify non-dynamic permission "
3349                    + info.name);
3350        } else {
3351            if (bp.protectionLevel == fixedLevel
3352                    && bp.perm.owner.equals(tree.perm.owner)
3353                    && bp.uid == tree.uid
3354                    && comparePermissionInfos(bp.perm.info, info)) {
3355                changed = false;
3356            }
3357        }
3358        bp.protectionLevel = fixedLevel;
3359        info = new PermissionInfo(info);
3360        info.protectionLevel = fixedLevel;
3361        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3362        bp.perm.info.packageName = tree.perm.info.packageName;
3363        bp.uid = tree.uid;
3364        if (added) {
3365            mSettings.mPermissions.put(info.name, bp);
3366        }
3367        if (changed) {
3368            if (!async) {
3369                mSettings.writeLPr();
3370            } else {
3371                scheduleWriteSettingsLocked();
3372            }
3373        }
3374        return added;
3375    }
3376
3377    @Override
3378    public boolean addPermission(PermissionInfo info) {
3379        synchronized (mPackages) {
3380            return addPermissionLocked(info, false);
3381        }
3382    }
3383
3384    @Override
3385    public boolean addPermissionAsync(PermissionInfo info) {
3386        synchronized (mPackages) {
3387            return addPermissionLocked(info, true);
3388        }
3389    }
3390
3391    @Override
3392    public void removePermission(String name) {
3393        synchronized (mPackages) {
3394            checkPermissionTreeLP(name);
3395            BasePermission bp = mSettings.mPermissions.get(name);
3396            if (bp != null) {
3397                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3398                    throw new SecurityException(
3399                            "Not allowed to modify non-dynamic permission "
3400                            + name);
3401                }
3402                mSettings.mPermissions.remove(name);
3403                mSettings.writeLPr();
3404            }
3405        }
3406    }
3407
3408    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3409            BasePermission bp) {
3410        int index = pkg.requestedPermissions.indexOf(bp.name);
3411        if (index == -1) {
3412            throw new SecurityException("Package " + pkg.packageName
3413                    + " has not requested permission " + bp.name);
3414        }
3415        if (!bp.isRuntime()) {
3416            throw new SecurityException("Permission " + bp.name
3417                    + " is not a changeable permission type");
3418        }
3419    }
3420
3421    @Override
3422    public void grantRuntimePermission(String packageName, String name, final int userId) {
3423        if (!sUserManager.exists(userId)) {
3424            Log.e(TAG, "No such user:" + userId);
3425            return;
3426        }
3427
3428        mContext.enforceCallingOrSelfPermission(
3429                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3430                "grantRuntimePermission");
3431
3432        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3433                "grantRuntimePermission");
3434
3435        final int uid;
3436        final SettingBase sb;
3437
3438        synchronized (mPackages) {
3439            final PackageParser.Package pkg = mPackages.get(packageName);
3440            if (pkg == null) {
3441                throw new IllegalArgumentException("Unknown package: " + packageName);
3442            }
3443
3444            final BasePermission bp = mSettings.mPermissions.get(name);
3445            if (bp == null) {
3446                throw new IllegalArgumentException("Unknown permission: " + name);
3447            }
3448
3449            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3450
3451            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3452            sb = (SettingBase) pkg.mExtras;
3453            if (sb == null) {
3454                throw new IllegalArgumentException("Unknown package: " + packageName);
3455            }
3456
3457            final PermissionsState permissionsState = sb.getPermissionsState();
3458
3459            final int flags = permissionsState.getPermissionFlags(name, userId);
3460            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3461                throw new SecurityException("Cannot grant system fixed permission: "
3462                        + name + " for package: " + packageName);
3463            }
3464
3465            final int result = permissionsState.grantRuntimePermission(bp, userId);
3466            switch (result) {
3467                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3468                    return;
3469                }
3470
3471                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3472                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3473                    mHandler.post(new Runnable() {
3474                        @Override
3475                        public void run() {
3476                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3477                        }
3478                    });
3479                } break;
3480            }
3481
3482            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3483
3484            // Not critical if that is lost - app has to request again.
3485            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3486        }
3487
3488        // Only need to do this if user is initialized. Otherwise it's a new user
3489        // and there are no processes running as the user yet and there's no need
3490        // to make an expensive call to remount processes for the changed permissions.
3491        if (READ_EXTERNAL_STORAGE.equals(name)
3492                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3493            final long token = Binder.clearCallingIdentity();
3494            try {
3495                if (sUserManager.isInitialized(userId)) {
3496                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3497                            MountServiceInternal.class);
3498                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3499                }
3500            } finally {
3501                Binder.restoreCallingIdentity(token);
3502            }
3503        }
3504    }
3505
3506    @Override
3507    public void revokeRuntimePermission(String packageName, String name, int userId) {
3508        if (!sUserManager.exists(userId)) {
3509            Log.e(TAG, "No such user:" + userId);
3510            return;
3511        }
3512
3513        mContext.enforceCallingOrSelfPermission(
3514                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3515                "revokeRuntimePermission");
3516
3517        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3518                "revokeRuntimePermission");
3519
3520        final int appId;
3521
3522        synchronized (mPackages) {
3523            final PackageParser.Package pkg = mPackages.get(packageName);
3524            if (pkg == null) {
3525                throw new IllegalArgumentException("Unknown package: " + packageName);
3526            }
3527
3528            final BasePermission bp = mSettings.mPermissions.get(name);
3529            if (bp == null) {
3530                throw new IllegalArgumentException("Unknown permission: " + name);
3531            }
3532
3533            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3534
3535            SettingBase sb = (SettingBase) pkg.mExtras;
3536            if (sb == null) {
3537                throw new IllegalArgumentException("Unknown package: " + packageName);
3538            }
3539
3540            final PermissionsState permissionsState = sb.getPermissionsState();
3541
3542            final int flags = permissionsState.getPermissionFlags(name, userId);
3543            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3544                throw new SecurityException("Cannot revoke system fixed permission: "
3545                        + name + " for package: " + packageName);
3546            }
3547
3548            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3549                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3550                return;
3551            }
3552
3553            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3554
3555            // Critical, after this call app should never have the permission.
3556            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3557
3558            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3559        }
3560
3561        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3562    }
3563
3564    @Override
3565    public void resetRuntimePermissions() {
3566        mContext.enforceCallingOrSelfPermission(
3567                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3568                "revokeRuntimePermission");
3569
3570        int callingUid = Binder.getCallingUid();
3571        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3572            mContext.enforceCallingOrSelfPermission(
3573                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3574                    "resetRuntimePermissions");
3575        }
3576
3577        synchronized (mPackages) {
3578            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3579            for (int userId : UserManagerService.getInstance().getUserIds()) {
3580                final int packageCount = mPackages.size();
3581                for (int i = 0; i < packageCount; i++) {
3582                    PackageParser.Package pkg = mPackages.valueAt(i);
3583                    if (!(pkg.mExtras instanceof PackageSetting)) {
3584                        continue;
3585                    }
3586                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3587                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3588                }
3589            }
3590        }
3591    }
3592
3593    @Override
3594    public int getPermissionFlags(String name, String packageName, int userId) {
3595        if (!sUserManager.exists(userId)) {
3596            return 0;
3597        }
3598
3599        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3600
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3602                "getPermissionFlags");
3603
3604        synchronized (mPackages) {
3605            final PackageParser.Package pkg = mPackages.get(packageName);
3606            if (pkg == null) {
3607                throw new IllegalArgumentException("Unknown package: " + packageName);
3608            }
3609
3610            final BasePermission bp = mSettings.mPermissions.get(name);
3611            if (bp == null) {
3612                throw new IllegalArgumentException("Unknown permission: " + name);
3613            }
3614
3615            SettingBase sb = (SettingBase) pkg.mExtras;
3616            if (sb == null) {
3617                throw new IllegalArgumentException("Unknown package: " + packageName);
3618            }
3619
3620            PermissionsState permissionsState = sb.getPermissionsState();
3621            return permissionsState.getPermissionFlags(name, userId);
3622        }
3623    }
3624
3625    @Override
3626    public void updatePermissionFlags(String name, String packageName, int flagMask,
3627            int flagValues, int userId) {
3628        if (!sUserManager.exists(userId)) {
3629            return;
3630        }
3631
3632        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3633
3634        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3635                "updatePermissionFlags");
3636
3637        // Only the system can change these flags and nothing else.
3638        if (getCallingUid() != Process.SYSTEM_UID) {
3639            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3640            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3641            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3642            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3643        }
3644
3645        synchronized (mPackages) {
3646            final PackageParser.Package pkg = mPackages.get(packageName);
3647            if (pkg == null) {
3648                throw new IllegalArgumentException("Unknown package: " + packageName);
3649            }
3650
3651            final BasePermission bp = mSettings.mPermissions.get(name);
3652            if (bp == null) {
3653                throw new IllegalArgumentException("Unknown permission: " + name);
3654            }
3655
3656            SettingBase sb = (SettingBase) pkg.mExtras;
3657            if (sb == null) {
3658                throw new IllegalArgumentException("Unknown package: " + packageName);
3659            }
3660
3661            PermissionsState permissionsState = sb.getPermissionsState();
3662
3663            // Only the package manager can change flags for system component permissions.
3664            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3665            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3666                return;
3667            }
3668
3669            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3670
3671            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3672                // Install and runtime permissions are stored in different places,
3673                // so figure out what permission changed and persist the change.
3674                if (permissionsState.getInstallPermissionState(name) != null) {
3675                    scheduleWriteSettingsLocked();
3676                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3677                        || hadState) {
3678                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3679                }
3680            }
3681        }
3682    }
3683
3684    /**
3685     * Update the permission flags for all packages and runtime permissions of a user in order
3686     * to allow device or profile owner to remove POLICY_FIXED.
3687     */
3688    @Override
3689    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3690        if (!sUserManager.exists(userId)) {
3691            return;
3692        }
3693
3694        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3695
3696        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3697                "updatePermissionFlagsForAllApps");
3698
3699        // Only the system can change system fixed flags.
3700        if (getCallingUid() != Process.SYSTEM_UID) {
3701            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3702            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3703        }
3704
3705        synchronized (mPackages) {
3706            boolean changed = false;
3707            final int packageCount = mPackages.size();
3708            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3709                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3710                SettingBase sb = (SettingBase) pkg.mExtras;
3711                if (sb == null) {
3712                    continue;
3713                }
3714                PermissionsState permissionsState = sb.getPermissionsState();
3715                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3716                        userId, flagMask, flagValues);
3717            }
3718            if (changed) {
3719                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3720            }
3721        }
3722    }
3723
3724    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3725        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3726                != PackageManager.PERMISSION_GRANTED
3727            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3728                != PackageManager.PERMISSION_GRANTED) {
3729            throw new SecurityException(message + " requires "
3730                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3731                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3732        }
3733    }
3734
3735    @Override
3736    public boolean shouldShowRequestPermissionRationale(String permissionName,
3737            String packageName, int userId) {
3738        if (UserHandle.getCallingUserId() != userId) {
3739            mContext.enforceCallingPermission(
3740                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3741                    "canShowRequestPermissionRationale for user " + userId);
3742        }
3743
3744        final int uid = getPackageUid(packageName, userId);
3745        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3746            return false;
3747        }
3748
3749        if (checkPermission(permissionName, packageName, userId)
3750                == PackageManager.PERMISSION_GRANTED) {
3751            return false;
3752        }
3753
3754        final int flags;
3755
3756        final long identity = Binder.clearCallingIdentity();
3757        try {
3758            flags = getPermissionFlags(permissionName,
3759                    packageName, userId);
3760        } finally {
3761            Binder.restoreCallingIdentity(identity);
3762        }
3763
3764        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3765                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3766                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3767
3768        if ((flags & fixedFlags) != 0) {
3769            return false;
3770        }
3771
3772        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3773    }
3774
3775    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3776        BasePermission bp = mSettings.mPermissions.get(permission);
3777        if (bp == null) {
3778            throw new SecurityException("Missing " + permission + " permission");
3779        }
3780
3781        SettingBase sb = (SettingBase) pkg.mExtras;
3782        PermissionsState permissionsState = sb.getPermissionsState();
3783
3784        if (permissionsState.grantInstallPermission(bp) !=
3785                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3786            scheduleWriteSettingsLocked();
3787        }
3788    }
3789
3790    @Override
3791    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3792        mContext.enforceCallingOrSelfPermission(
3793                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3794                "addOnPermissionsChangeListener");
3795
3796        synchronized (mPackages) {
3797            mOnPermissionChangeListeners.addListenerLocked(listener);
3798        }
3799    }
3800
3801    @Override
3802    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3803        synchronized (mPackages) {
3804            mOnPermissionChangeListeners.removeListenerLocked(listener);
3805        }
3806    }
3807
3808    @Override
3809    public boolean isProtectedBroadcast(String actionName) {
3810        synchronized (mPackages) {
3811            return mProtectedBroadcasts.contains(actionName);
3812        }
3813    }
3814
3815    @Override
3816    public int checkSignatures(String pkg1, String pkg2) {
3817        synchronized (mPackages) {
3818            final PackageParser.Package p1 = mPackages.get(pkg1);
3819            final PackageParser.Package p2 = mPackages.get(pkg2);
3820            if (p1 == null || p1.mExtras == null
3821                    || p2 == null || p2.mExtras == null) {
3822                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3823            }
3824            return compareSignatures(p1.mSignatures, p2.mSignatures);
3825        }
3826    }
3827
3828    @Override
3829    public int checkUidSignatures(int uid1, int uid2) {
3830        // Map to base uids.
3831        uid1 = UserHandle.getAppId(uid1);
3832        uid2 = UserHandle.getAppId(uid2);
3833        // reader
3834        synchronized (mPackages) {
3835            Signature[] s1;
3836            Signature[] s2;
3837            Object obj = mSettings.getUserIdLPr(uid1);
3838            if (obj != null) {
3839                if (obj instanceof SharedUserSetting) {
3840                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3841                } else if (obj instanceof PackageSetting) {
3842                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3843                } else {
3844                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3845                }
3846            } else {
3847                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3848            }
3849            obj = mSettings.getUserIdLPr(uid2);
3850            if (obj != null) {
3851                if (obj instanceof SharedUserSetting) {
3852                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3853                } else if (obj instanceof PackageSetting) {
3854                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3855                } else {
3856                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3857                }
3858            } else {
3859                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3860            }
3861            return compareSignatures(s1, s2);
3862        }
3863    }
3864
3865    private void killUid(int appId, int userId, String reason) {
3866        final long identity = Binder.clearCallingIdentity();
3867        try {
3868            IActivityManager am = ActivityManagerNative.getDefault();
3869            if (am != null) {
3870                try {
3871                    am.killUid(appId, userId, reason);
3872                } catch (RemoteException e) {
3873                    /* ignore - same process */
3874                }
3875            }
3876        } finally {
3877            Binder.restoreCallingIdentity(identity);
3878        }
3879    }
3880
3881    /**
3882     * Compares two sets of signatures. Returns:
3883     * <br />
3884     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3885     * <br />
3886     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3887     * <br />
3888     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3889     * <br />
3890     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3891     * <br />
3892     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3893     */
3894    static int compareSignatures(Signature[] s1, Signature[] s2) {
3895        if (s1 == null) {
3896            return s2 == null
3897                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3898                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3899        }
3900
3901        if (s2 == null) {
3902            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3903        }
3904
3905        if (s1.length != s2.length) {
3906            return PackageManager.SIGNATURE_NO_MATCH;
3907        }
3908
3909        // Since both signature sets are of size 1, we can compare without HashSets.
3910        if (s1.length == 1) {
3911            return s1[0].equals(s2[0]) ?
3912                    PackageManager.SIGNATURE_MATCH :
3913                    PackageManager.SIGNATURE_NO_MATCH;
3914        }
3915
3916        ArraySet<Signature> set1 = new ArraySet<Signature>();
3917        for (Signature sig : s1) {
3918            set1.add(sig);
3919        }
3920        ArraySet<Signature> set2 = new ArraySet<Signature>();
3921        for (Signature sig : s2) {
3922            set2.add(sig);
3923        }
3924        // Make sure s2 contains all signatures in s1.
3925        if (set1.equals(set2)) {
3926            return PackageManager.SIGNATURE_MATCH;
3927        }
3928        return PackageManager.SIGNATURE_NO_MATCH;
3929    }
3930
3931    /**
3932     * If the database version for this type of package (internal storage or
3933     * external storage) is less than the version where package signatures
3934     * were updated, return true.
3935     */
3936    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3937        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3938        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3939    }
3940
3941    /**
3942     * Used for backward compatibility to make sure any packages with
3943     * certificate chains get upgraded to the new style. {@code existingSigs}
3944     * will be in the old format (since they were stored on disk from before the
3945     * system upgrade) and {@code scannedSigs} will be in the newer format.
3946     */
3947    private int compareSignaturesCompat(PackageSignatures existingSigs,
3948            PackageParser.Package scannedPkg) {
3949        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3950            return PackageManager.SIGNATURE_NO_MATCH;
3951        }
3952
3953        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3954        for (Signature sig : existingSigs.mSignatures) {
3955            existingSet.add(sig);
3956        }
3957        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3958        for (Signature sig : scannedPkg.mSignatures) {
3959            try {
3960                Signature[] chainSignatures = sig.getChainSignatures();
3961                for (Signature chainSig : chainSignatures) {
3962                    scannedCompatSet.add(chainSig);
3963                }
3964            } catch (CertificateEncodingException e) {
3965                scannedCompatSet.add(sig);
3966            }
3967        }
3968        /*
3969         * Make sure the expanded scanned set contains all signatures in the
3970         * existing one.
3971         */
3972        if (scannedCompatSet.equals(existingSet)) {
3973            // Migrate the old signatures to the new scheme.
3974            existingSigs.assignSignatures(scannedPkg.mSignatures);
3975            // The new KeySets will be re-added later in the scanning process.
3976            synchronized (mPackages) {
3977                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3978            }
3979            return PackageManager.SIGNATURE_MATCH;
3980        }
3981        return PackageManager.SIGNATURE_NO_MATCH;
3982    }
3983
3984    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3985        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3986        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
3987    }
3988
3989    private int compareSignaturesRecover(PackageSignatures existingSigs,
3990            PackageParser.Package scannedPkg) {
3991        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3992            return PackageManager.SIGNATURE_NO_MATCH;
3993        }
3994
3995        String msg = null;
3996        try {
3997            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3998                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3999                        + scannedPkg.packageName);
4000                return PackageManager.SIGNATURE_MATCH;
4001            }
4002        } catch (CertificateException e) {
4003            msg = e.getMessage();
4004        }
4005
4006        logCriticalInfo(Log.INFO,
4007                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4008        return PackageManager.SIGNATURE_NO_MATCH;
4009    }
4010
4011    @Override
4012    public String[] getPackagesForUid(int uid) {
4013        uid = UserHandle.getAppId(uid);
4014        // reader
4015        synchronized (mPackages) {
4016            Object obj = mSettings.getUserIdLPr(uid);
4017            if (obj instanceof SharedUserSetting) {
4018                final SharedUserSetting sus = (SharedUserSetting) obj;
4019                final int N = sus.packages.size();
4020                final String[] res = new String[N];
4021                final Iterator<PackageSetting> it = sus.packages.iterator();
4022                int i = 0;
4023                while (it.hasNext()) {
4024                    res[i++] = it.next().name;
4025                }
4026                return res;
4027            } else if (obj instanceof PackageSetting) {
4028                final PackageSetting ps = (PackageSetting) obj;
4029                return new String[] { ps.name };
4030            }
4031        }
4032        return null;
4033    }
4034
4035    @Override
4036    public String getNameForUid(int uid) {
4037        // reader
4038        synchronized (mPackages) {
4039            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4040            if (obj instanceof SharedUserSetting) {
4041                final SharedUserSetting sus = (SharedUserSetting) obj;
4042                return sus.name + ":" + sus.userId;
4043            } else if (obj instanceof PackageSetting) {
4044                final PackageSetting ps = (PackageSetting) obj;
4045                return ps.name;
4046            }
4047        }
4048        return null;
4049    }
4050
4051    @Override
4052    public int getUidForSharedUser(String sharedUserName) {
4053        if(sharedUserName == null) {
4054            return -1;
4055        }
4056        // reader
4057        synchronized (mPackages) {
4058            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4059            if (suid == null) {
4060                return -1;
4061            }
4062            return suid.userId;
4063        }
4064    }
4065
4066    @Override
4067    public int getFlagsForUid(int uid) {
4068        synchronized (mPackages) {
4069            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4070            if (obj instanceof SharedUserSetting) {
4071                final SharedUserSetting sus = (SharedUserSetting) obj;
4072                return sus.pkgFlags;
4073            } else if (obj instanceof PackageSetting) {
4074                final PackageSetting ps = (PackageSetting) obj;
4075                return ps.pkgFlags;
4076            }
4077        }
4078        return 0;
4079    }
4080
4081    @Override
4082    public int getPrivateFlagsForUid(int uid) {
4083        synchronized (mPackages) {
4084            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4085            if (obj instanceof SharedUserSetting) {
4086                final SharedUserSetting sus = (SharedUserSetting) obj;
4087                return sus.pkgPrivateFlags;
4088            } else if (obj instanceof PackageSetting) {
4089                final PackageSetting ps = (PackageSetting) obj;
4090                return ps.pkgPrivateFlags;
4091            }
4092        }
4093        return 0;
4094    }
4095
4096    @Override
4097    public boolean isUidPrivileged(int uid) {
4098        uid = UserHandle.getAppId(uid);
4099        // reader
4100        synchronized (mPackages) {
4101            Object obj = mSettings.getUserIdLPr(uid);
4102            if (obj instanceof SharedUserSetting) {
4103                final SharedUserSetting sus = (SharedUserSetting) obj;
4104                final Iterator<PackageSetting> it = sus.packages.iterator();
4105                while (it.hasNext()) {
4106                    if (it.next().isPrivileged()) {
4107                        return true;
4108                    }
4109                }
4110            } else if (obj instanceof PackageSetting) {
4111                final PackageSetting ps = (PackageSetting) obj;
4112                return ps.isPrivileged();
4113            }
4114        }
4115        return false;
4116    }
4117
4118    @Override
4119    public String[] getAppOpPermissionPackages(String permissionName) {
4120        synchronized (mPackages) {
4121            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4122            if (pkgs == null) {
4123                return null;
4124            }
4125            return pkgs.toArray(new String[pkgs.size()]);
4126        }
4127    }
4128
4129    @Override
4130    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4131            int flags, int userId) {
4132        if (!sUserManager.exists(userId)) return null;
4133        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4134        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4135        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4136    }
4137
4138    @Override
4139    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4140            IntentFilter filter, int match, ComponentName activity) {
4141        final int userId = UserHandle.getCallingUserId();
4142        if (DEBUG_PREFERRED) {
4143            Log.v(TAG, "setLastChosenActivity intent=" + intent
4144                + " resolvedType=" + resolvedType
4145                + " flags=" + flags
4146                + " filter=" + filter
4147                + " match=" + match
4148                + " activity=" + activity);
4149            filter.dump(new PrintStreamPrinter(System.out), "    ");
4150        }
4151        intent.setComponent(null);
4152        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4153        // Find any earlier preferred or last chosen entries and nuke them
4154        findPreferredActivity(intent, resolvedType,
4155                flags, query, 0, false, true, false, userId);
4156        // Add the new activity as the last chosen for this filter
4157        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4158                "Setting last chosen");
4159    }
4160
4161    @Override
4162    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4163        final int userId = UserHandle.getCallingUserId();
4164        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4165        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4166        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4167                false, false, false, userId);
4168    }
4169
4170    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4171            int flags, List<ResolveInfo> query, int userId) {
4172        if (query != null) {
4173            final int N = query.size();
4174            if (N == 1) {
4175                return query.get(0);
4176            } else if (N > 1) {
4177                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4178                // If there is more than one activity with the same priority,
4179                // then let the user decide between them.
4180                ResolveInfo r0 = query.get(0);
4181                ResolveInfo r1 = query.get(1);
4182                if (DEBUG_INTENT_MATCHING || debug) {
4183                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4184                            + r1.activityInfo.name + "=" + r1.priority);
4185                }
4186                // If the first activity has a higher priority, or a different
4187                // default, then it is always desireable to pick it.
4188                if (r0.priority != r1.priority
4189                        || r0.preferredOrder != r1.preferredOrder
4190                        || r0.isDefault != r1.isDefault) {
4191                    return query.get(0);
4192                }
4193                // If we have saved a preference for a preferred activity for
4194                // this Intent, use that.
4195                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4196                        flags, query, r0.priority, true, false, debug, userId);
4197                if (ri != null) {
4198                    return ri;
4199                }
4200                if (userId != 0) {
4201                    ri = new ResolveInfo(mResolveInfo);
4202                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4203                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4204                            ri.activityInfo.applicationInfo);
4205                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4206                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4207                    return ri;
4208                }
4209                return mResolveInfo;
4210            }
4211        }
4212        return null;
4213    }
4214
4215    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4216            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4217        final int N = query.size();
4218        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4219                .get(userId);
4220        // Get the list of persistent preferred activities that handle the intent
4221        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4222        List<PersistentPreferredActivity> pprefs = ppir != null
4223                ? ppir.queryIntent(intent, resolvedType,
4224                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4225                : null;
4226        if (pprefs != null && pprefs.size() > 0) {
4227            final int M = pprefs.size();
4228            for (int i=0; i<M; i++) {
4229                final PersistentPreferredActivity ppa = pprefs.get(i);
4230                if (DEBUG_PREFERRED || debug) {
4231                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4232                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4233                            + "\n  component=" + ppa.mComponent);
4234                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4235                }
4236                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4237                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4238                if (DEBUG_PREFERRED || debug) {
4239                    Slog.v(TAG, "Found persistent preferred activity:");
4240                    if (ai != null) {
4241                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4242                    } else {
4243                        Slog.v(TAG, "  null");
4244                    }
4245                }
4246                if (ai == null) {
4247                    // This previously registered persistent preferred activity
4248                    // component is no longer known. Ignore it and do NOT remove it.
4249                    continue;
4250                }
4251                for (int j=0; j<N; j++) {
4252                    final ResolveInfo ri = query.get(j);
4253                    if (!ri.activityInfo.applicationInfo.packageName
4254                            .equals(ai.applicationInfo.packageName)) {
4255                        continue;
4256                    }
4257                    if (!ri.activityInfo.name.equals(ai.name)) {
4258                        continue;
4259                    }
4260                    //  Found a persistent preference that can handle the intent.
4261                    if (DEBUG_PREFERRED || debug) {
4262                        Slog.v(TAG, "Returning persistent preferred activity: " +
4263                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4264                    }
4265                    return ri;
4266                }
4267            }
4268        }
4269        return null;
4270    }
4271
4272    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4273            List<ResolveInfo> query, int priority, boolean always,
4274            boolean removeMatches, boolean debug, int userId) {
4275        if (!sUserManager.exists(userId)) return null;
4276        // writer
4277        synchronized (mPackages) {
4278            if (intent.getSelector() != null) {
4279                intent = intent.getSelector();
4280            }
4281            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4282
4283            // Try to find a matching persistent preferred activity.
4284            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4285                    debug, userId);
4286
4287            // If a persistent preferred activity matched, use it.
4288            if (pri != null) {
4289                return pri;
4290            }
4291
4292            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4293            // Get the list of preferred activities that handle the intent
4294            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4295            List<PreferredActivity> prefs = pir != null
4296                    ? pir.queryIntent(intent, resolvedType,
4297                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4298                    : null;
4299            if (prefs != null && prefs.size() > 0) {
4300                boolean changed = false;
4301                try {
4302                    // First figure out how good the original match set is.
4303                    // We will only allow preferred activities that came
4304                    // from the same match quality.
4305                    int match = 0;
4306
4307                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4308
4309                    final int N = query.size();
4310                    for (int j=0; j<N; j++) {
4311                        final ResolveInfo ri = query.get(j);
4312                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4313                                + ": 0x" + Integer.toHexString(match));
4314                        if (ri.match > match) {
4315                            match = ri.match;
4316                        }
4317                    }
4318
4319                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4320                            + Integer.toHexString(match));
4321
4322                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4323                    final int M = prefs.size();
4324                    for (int i=0; i<M; i++) {
4325                        final PreferredActivity pa = prefs.get(i);
4326                        if (DEBUG_PREFERRED || debug) {
4327                            Slog.v(TAG, "Checking PreferredActivity ds="
4328                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4329                                    + "\n  component=" + pa.mPref.mComponent);
4330                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4331                        }
4332                        if (pa.mPref.mMatch != match) {
4333                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4334                                    + Integer.toHexString(pa.mPref.mMatch));
4335                            continue;
4336                        }
4337                        // If it's not an "always" type preferred activity and that's what we're
4338                        // looking for, skip it.
4339                        if (always && !pa.mPref.mAlways) {
4340                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4341                            continue;
4342                        }
4343                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4344                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4345                        if (DEBUG_PREFERRED || debug) {
4346                            Slog.v(TAG, "Found preferred activity:");
4347                            if (ai != null) {
4348                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4349                            } else {
4350                                Slog.v(TAG, "  null");
4351                            }
4352                        }
4353                        if (ai == null) {
4354                            // This previously registered preferred activity
4355                            // component is no longer known.  Most likely an update
4356                            // to the app was installed and in the new version this
4357                            // component no longer exists.  Clean it up by removing
4358                            // it from the preferred activities list, and skip it.
4359                            Slog.w(TAG, "Removing dangling preferred activity: "
4360                                    + pa.mPref.mComponent);
4361                            pir.removeFilter(pa);
4362                            changed = true;
4363                            continue;
4364                        }
4365                        for (int j=0; j<N; j++) {
4366                            final ResolveInfo ri = query.get(j);
4367                            if (!ri.activityInfo.applicationInfo.packageName
4368                                    .equals(ai.applicationInfo.packageName)) {
4369                                continue;
4370                            }
4371                            if (!ri.activityInfo.name.equals(ai.name)) {
4372                                continue;
4373                            }
4374
4375                            if (removeMatches) {
4376                                pir.removeFilter(pa);
4377                                changed = true;
4378                                if (DEBUG_PREFERRED) {
4379                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4380                                }
4381                                break;
4382                            }
4383
4384                            // Okay we found a previously set preferred or last chosen app.
4385                            // If the result set is different from when this
4386                            // was created, we need to clear it and re-ask the
4387                            // user their preference, if we're looking for an "always" type entry.
4388                            if (always && !pa.mPref.sameSet(query)) {
4389                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4390                                        + intent + " type " + resolvedType);
4391                                if (DEBUG_PREFERRED) {
4392                                    Slog.v(TAG, "Removing preferred activity since set changed "
4393                                            + pa.mPref.mComponent);
4394                                }
4395                                pir.removeFilter(pa);
4396                                // Re-add the filter as a "last chosen" entry (!always)
4397                                PreferredActivity lastChosen = new PreferredActivity(
4398                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4399                                pir.addFilter(lastChosen);
4400                                changed = true;
4401                                return null;
4402                            }
4403
4404                            // Yay! Either the set matched or we're looking for the last chosen
4405                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4406                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4407                            return ri;
4408                        }
4409                    }
4410                } finally {
4411                    if (changed) {
4412                        if (DEBUG_PREFERRED) {
4413                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4414                        }
4415                        scheduleWritePackageRestrictionsLocked(userId);
4416                    }
4417                }
4418            }
4419        }
4420        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4421        return null;
4422    }
4423
4424    /*
4425     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4426     */
4427    @Override
4428    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4429            int targetUserId) {
4430        mContext.enforceCallingOrSelfPermission(
4431                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4432        List<CrossProfileIntentFilter> matches =
4433                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4434        if (matches != null) {
4435            int size = matches.size();
4436            for (int i = 0; i < size; i++) {
4437                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4438            }
4439        }
4440        if (hasWebURI(intent)) {
4441            // cross-profile app linking works only towards the parent.
4442            final UserInfo parent = getProfileParent(sourceUserId);
4443            synchronized(mPackages) {
4444                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4445                        intent, resolvedType, 0, sourceUserId, parent.id);
4446                return xpDomainInfo != null;
4447            }
4448        }
4449        return false;
4450    }
4451
4452    private UserInfo getProfileParent(int userId) {
4453        final long identity = Binder.clearCallingIdentity();
4454        try {
4455            return sUserManager.getProfileParent(userId);
4456        } finally {
4457            Binder.restoreCallingIdentity(identity);
4458        }
4459    }
4460
4461    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4462            String resolvedType, int userId) {
4463        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4464        if (resolver != null) {
4465            return resolver.queryIntent(intent, resolvedType, false, userId);
4466        }
4467        return null;
4468    }
4469
4470    @Override
4471    public List<ResolveInfo> queryIntentActivities(Intent intent,
4472            String resolvedType, int flags, int userId) {
4473        if (!sUserManager.exists(userId)) return Collections.emptyList();
4474        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4475        ComponentName comp = intent.getComponent();
4476        if (comp == null) {
4477            if (intent.getSelector() != null) {
4478                intent = intent.getSelector();
4479                comp = intent.getComponent();
4480            }
4481        }
4482
4483        if (comp != null) {
4484            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4485            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4486            if (ai != null) {
4487                final ResolveInfo ri = new ResolveInfo();
4488                ri.activityInfo = ai;
4489                list.add(ri);
4490            }
4491            return list;
4492        }
4493
4494        // reader
4495        synchronized (mPackages) {
4496            final String pkgName = intent.getPackage();
4497            if (pkgName == null) {
4498                List<CrossProfileIntentFilter> matchingFilters =
4499                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4500                // Check for results that need to skip the current profile.
4501                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4502                        resolvedType, flags, userId);
4503                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4504                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4505                    result.add(xpResolveInfo);
4506                    return filterIfNotPrimaryUser(result, userId);
4507                }
4508
4509                // Check for results in the current profile.
4510                List<ResolveInfo> result = mActivities.queryIntent(
4511                        intent, resolvedType, flags, userId);
4512
4513                // Check for cross profile results.
4514                xpResolveInfo = queryCrossProfileIntents(
4515                        matchingFilters, intent, resolvedType, flags, userId);
4516                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4517                    result.add(xpResolveInfo);
4518                    Collections.sort(result, mResolvePrioritySorter);
4519                }
4520                result = filterIfNotPrimaryUser(result, userId);
4521                if (hasWebURI(intent)) {
4522                    CrossProfileDomainInfo xpDomainInfo = null;
4523                    final UserInfo parent = getProfileParent(userId);
4524                    if (parent != null) {
4525                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4526                                flags, userId, parent.id);
4527                    }
4528                    if (xpDomainInfo != null) {
4529                        if (xpResolveInfo != null) {
4530                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4531                            // in the result.
4532                            result.remove(xpResolveInfo);
4533                        }
4534                        if (result.size() == 0) {
4535                            result.add(xpDomainInfo.resolveInfo);
4536                            return result;
4537                        }
4538                    } else if (result.size() <= 1) {
4539                        return result;
4540                    }
4541                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4542                            xpDomainInfo, userId);
4543                    Collections.sort(result, mResolvePrioritySorter);
4544                }
4545                return result;
4546            }
4547            final PackageParser.Package pkg = mPackages.get(pkgName);
4548            if (pkg != null) {
4549                return filterIfNotPrimaryUser(
4550                        mActivities.queryIntentForPackage(
4551                                intent, resolvedType, flags, pkg.activities, userId),
4552                        userId);
4553            }
4554            return new ArrayList<ResolveInfo>();
4555        }
4556    }
4557
4558    private static class CrossProfileDomainInfo {
4559        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4560        ResolveInfo resolveInfo;
4561        /* Best domain verification status of the activities found in the other profile */
4562        int bestDomainVerificationStatus;
4563    }
4564
4565    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4566            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4567        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4568                sourceUserId)) {
4569            return null;
4570        }
4571        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4572                resolvedType, flags, parentUserId);
4573
4574        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4575            return null;
4576        }
4577        CrossProfileDomainInfo result = null;
4578        int size = resultTargetUser.size();
4579        for (int i = 0; i < size; i++) {
4580            ResolveInfo riTargetUser = resultTargetUser.get(i);
4581            // Intent filter verification is only for filters that specify a host. So don't return
4582            // those that handle all web uris.
4583            if (riTargetUser.handleAllWebDataURI) {
4584                continue;
4585            }
4586            String packageName = riTargetUser.activityInfo.packageName;
4587            PackageSetting ps = mSettings.mPackages.get(packageName);
4588            if (ps == null) {
4589                continue;
4590            }
4591            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4592            int status = (int)(verificationState >> 32);
4593            if (result == null) {
4594                result = new CrossProfileDomainInfo();
4595                result.resolveInfo =
4596                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4597                result.bestDomainVerificationStatus = status;
4598            } else {
4599                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4600                        result.bestDomainVerificationStatus);
4601            }
4602        }
4603        // Don't consider matches with status NEVER across profiles.
4604        if (result != null && result.bestDomainVerificationStatus
4605                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4606            return null;
4607        }
4608        return result;
4609    }
4610
4611    /**
4612     * Verification statuses are ordered from the worse to the best, except for
4613     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4614     */
4615    private int bestDomainVerificationStatus(int status1, int status2) {
4616        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4617            return status2;
4618        }
4619        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4620            return status1;
4621        }
4622        return (int) MathUtils.max(status1, status2);
4623    }
4624
4625    private boolean isUserEnabled(int userId) {
4626        long callingId = Binder.clearCallingIdentity();
4627        try {
4628            UserInfo userInfo = sUserManager.getUserInfo(userId);
4629            return userInfo != null && userInfo.isEnabled();
4630        } finally {
4631            Binder.restoreCallingIdentity(callingId);
4632        }
4633    }
4634
4635    /**
4636     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4637     *
4638     * @return filtered list
4639     */
4640    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4641        if (userId == UserHandle.USER_OWNER) {
4642            return resolveInfos;
4643        }
4644        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4645            ResolveInfo info = resolveInfos.get(i);
4646            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4647                resolveInfos.remove(i);
4648            }
4649        }
4650        return resolveInfos;
4651    }
4652
4653    private static boolean hasWebURI(Intent intent) {
4654        if (intent.getData() == null) {
4655            return false;
4656        }
4657        final String scheme = intent.getScheme();
4658        if (TextUtils.isEmpty(scheme)) {
4659            return false;
4660        }
4661        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4662    }
4663
4664    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4665            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4666            int userId) {
4667        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4668
4669        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4670            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4671                    candidates.size());
4672        }
4673
4674        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4675        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4676        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4677        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4678        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4679
4680        synchronized (mPackages) {
4681            final int count = candidates.size();
4682            // First, try to use linked apps. Partition the candidates into four lists:
4683            // one for the final results, one for the "do not use ever", one for "undefined status"
4684            // and finally one for "browser app type".
4685            for (int n=0; n<count; n++) {
4686                ResolveInfo info = candidates.get(n);
4687                String packageName = info.activityInfo.packageName;
4688                PackageSetting ps = mSettings.mPackages.get(packageName);
4689                if (ps != null) {
4690                    // Add to the special match all list (Browser use case)
4691                    if (info.handleAllWebDataURI) {
4692                        matchAllList.add(info);
4693                        continue;
4694                    }
4695                    // Try to get the status from User settings first
4696                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4697                    int status = (int)(packedStatus >> 32);
4698                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4699                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4700                        if (DEBUG_DOMAIN_VERIFICATION) {
4701                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4702                                    + " : linkgen=" + linkGeneration);
4703                        }
4704                        // Use link-enabled generation as preferredOrder, i.e.
4705                        // prefer newly-enabled over earlier-enabled.
4706                        info.preferredOrder = linkGeneration;
4707                        alwaysList.add(info);
4708                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4709                        if (DEBUG_DOMAIN_VERIFICATION) {
4710                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4711                        }
4712                        neverList.add(info);
4713                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4714                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4715                        if (DEBUG_DOMAIN_VERIFICATION) {
4716                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4717                        }
4718                        undefinedList.add(info);
4719                    }
4720                }
4721            }
4722            // First try to add the "always" resolution(s) for the current user, if any
4723            if (alwaysList.size() > 0) {
4724                result.addAll(alwaysList);
4725            // if there is an "always" for the parent user, add it.
4726            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4727                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4728                result.add(xpDomainInfo.resolveInfo);
4729            } else {
4730                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4731                result.addAll(undefinedList);
4732                if (xpDomainInfo != null && (
4733                        xpDomainInfo.bestDomainVerificationStatus
4734                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4735                        || xpDomainInfo.bestDomainVerificationStatus
4736                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4737                    result.add(xpDomainInfo.resolveInfo);
4738                }
4739                // Also add Browsers (all of them or only the default one)
4740                if ((matchFlags & MATCH_ALL) != 0) {
4741                    result.addAll(matchAllList);
4742                } else {
4743                    // Browser/generic handling case.  If there's a default browser, go straight
4744                    // to that (but only if there is no other higher-priority match).
4745                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4746                    int maxMatchPrio = 0;
4747                    ResolveInfo defaultBrowserMatch = null;
4748                    final int numCandidates = matchAllList.size();
4749                    for (int n = 0; n < numCandidates; n++) {
4750                        ResolveInfo info = matchAllList.get(n);
4751                        // track the highest overall match priority...
4752                        if (info.priority > maxMatchPrio) {
4753                            maxMatchPrio = info.priority;
4754                        }
4755                        // ...and the highest-priority default browser match
4756                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4757                            if (defaultBrowserMatch == null
4758                                    || (defaultBrowserMatch.priority < info.priority)) {
4759                                if (debug) {
4760                                    Slog.v(TAG, "Considering default browser match " + info);
4761                                }
4762                                defaultBrowserMatch = info;
4763                            }
4764                        }
4765                    }
4766                    if (defaultBrowserMatch != null
4767                            && defaultBrowserMatch.priority >= maxMatchPrio
4768                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4769                    {
4770                        if (debug) {
4771                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4772                        }
4773                        result.add(defaultBrowserMatch);
4774                    } else {
4775                        result.addAll(matchAllList);
4776                    }
4777                }
4778
4779                // If there is nothing selected, add all candidates and remove the ones that the user
4780                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4781                if (result.size() == 0) {
4782                    result.addAll(candidates);
4783                    result.removeAll(neverList);
4784                }
4785            }
4786        }
4787        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4788            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4789                    result.size());
4790            for (ResolveInfo info : result) {
4791                Slog.v(TAG, "  + " + info.activityInfo);
4792            }
4793        }
4794        return result;
4795    }
4796
4797    // Returns a packed value as a long:
4798    //
4799    // high 'int'-sized word: link status: undefined/ask/never/always.
4800    // low 'int'-sized word: relative priority among 'always' results.
4801    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4802        long result = ps.getDomainVerificationStatusForUser(userId);
4803        // if none available, get the master status
4804        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4805            if (ps.getIntentFilterVerificationInfo() != null) {
4806                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4807            }
4808        }
4809        return result;
4810    }
4811
4812    private ResolveInfo querySkipCurrentProfileIntents(
4813            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4814            int flags, int sourceUserId) {
4815        if (matchingFilters != null) {
4816            int size = matchingFilters.size();
4817            for (int i = 0; i < size; i ++) {
4818                CrossProfileIntentFilter filter = matchingFilters.get(i);
4819                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4820                    // Checking if there are activities in the target user that can handle the
4821                    // intent.
4822                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4823                            flags, sourceUserId);
4824                    if (resolveInfo != null) {
4825                        return resolveInfo;
4826                    }
4827                }
4828            }
4829        }
4830        return null;
4831    }
4832
4833    // Return matching ResolveInfo if any for skip current profile intent filters.
4834    private ResolveInfo queryCrossProfileIntents(
4835            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4836            int flags, int sourceUserId) {
4837        if (matchingFilters != null) {
4838            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4839            // match the same intent. For performance reasons, it is better not to
4840            // run queryIntent twice for the same userId
4841            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4842            int size = matchingFilters.size();
4843            for (int i = 0; i < size; i++) {
4844                CrossProfileIntentFilter filter = matchingFilters.get(i);
4845                int targetUserId = filter.getTargetUserId();
4846                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4847                        && !alreadyTriedUserIds.get(targetUserId)) {
4848                    // Checking if there are activities in the target user that can handle the
4849                    // intent.
4850                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4851                            flags, sourceUserId);
4852                    if (resolveInfo != null) return resolveInfo;
4853                    alreadyTriedUserIds.put(targetUserId, true);
4854                }
4855            }
4856        }
4857        return null;
4858    }
4859
4860    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4861            String resolvedType, int flags, int sourceUserId) {
4862        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4863                resolvedType, flags, filter.getTargetUserId());
4864        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4865            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4866        }
4867        return null;
4868    }
4869
4870    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4871            int sourceUserId, int targetUserId) {
4872        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4873        String className;
4874        if (targetUserId == UserHandle.USER_OWNER) {
4875            className = FORWARD_INTENT_TO_USER_OWNER;
4876        } else {
4877            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4878        }
4879        ComponentName forwardingActivityComponentName = new ComponentName(
4880                mAndroidApplication.packageName, className);
4881        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4882                sourceUserId);
4883        if (targetUserId == UserHandle.USER_OWNER) {
4884            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4885            forwardingResolveInfo.noResourceId = true;
4886        }
4887        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4888        forwardingResolveInfo.priority = 0;
4889        forwardingResolveInfo.preferredOrder = 0;
4890        forwardingResolveInfo.match = 0;
4891        forwardingResolveInfo.isDefault = true;
4892        forwardingResolveInfo.filter = filter;
4893        forwardingResolveInfo.targetUserId = targetUserId;
4894        return forwardingResolveInfo;
4895    }
4896
4897    @Override
4898    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4899            Intent[] specifics, String[] specificTypes, Intent intent,
4900            String resolvedType, int flags, int userId) {
4901        if (!sUserManager.exists(userId)) return Collections.emptyList();
4902        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4903                false, "query intent activity options");
4904        final String resultsAction = intent.getAction();
4905
4906        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4907                | PackageManager.GET_RESOLVED_FILTER, userId);
4908
4909        if (DEBUG_INTENT_MATCHING) {
4910            Log.v(TAG, "Query " + intent + ": " + results);
4911        }
4912
4913        int specificsPos = 0;
4914        int N;
4915
4916        // todo: note that the algorithm used here is O(N^2).  This
4917        // isn't a problem in our current environment, but if we start running
4918        // into situations where we have more than 5 or 10 matches then this
4919        // should probably be changed to something smarter...
4920
4921        // First we go through and resolve each of the specific items
4922        // that were supplied, taking care of removing any corresponding
4923        // duplicate items in the generic resolve list.
4924        if (specifics != null) {
4925            for (int i=0; i<specifics.length; i++) {
4926                final Intent sintent = specifics[i];
4927                if (sintent == null) {
4928                    continue;
4929                }
4930
4931                if (DEBUG_INTENT_MATCHING) {
4932                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4933                }
4934
4935                String action = sintent.getAction();
4936                if (resultsAction != null && resultsAction.equals(action)) {
4937                    // If this action was explicitly requested, then don't
4938                    // remove things that have it.
4939                    action = null;
4940                }
4941
4942                ResolveInfo ri = null;
4943                ActivityInfo ai = null;
4944
4945                ComponentName comp = sintent.getComponent();
4946                if (comp == null) {
4947                    ri = resolveIntent(
4948                        sintent,
4949                        specificTypes != null ? specificTypes[i] : null,
4950                            flags, userId);
4951                    if (ri == null) {
4952                        continue;
4953                    }
4954                    if (ri == mResolveInfo) {
4955                        // ACK!  Must do something better with this.
4956                    }
4957                    ai = ri.activityInfo;
4958                    comp = new ComponentName(ai.applicationInfo.packageName,
4959                            ai.name);
4960                } else {
4961                    ai = getActivityInfo(comp, flags, userId);
4962                    if (ai == null) {
4963                        continue;
4964                    }
4965                }
4966
4967                // Look for any generic query activities that are duplicates
4968                // of this specific one, and remove them from the results.
4969                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4970                N = results.size();
4971                int j;
4972                for (j=specificsPos; j<N; j++) {
4973                    ResolveInfo sri = results.get(j);
4974                    if ((sri.activityInfo.name.equals(comp.getClassName())
4975                            && sri.activityInfo.applicationInfo.packageName.equals(
4976                                    comp.getPackageName()))
4977                        || (action != null && sri.filter.matchAction(action))) {
4978                        results.remove(j);
4979                        if (DEBUG_INTENT_MATCHING) Log.v(
4980                            TAG, "Removing duplicate item from " + j
4981                            + " due to specific " + specificsPos);
4982                        if (ri == null) {
4983                            ri = sri;
4984                        }
4985                        j--;
4986                        N--;
4987                    }
4988                }
4989
4990                // Add this specific item to its proper place.
4991                if (ri == null) {
4992                    ri = new ResolveInfo();
4993                    ri.activityInfo = ai;
4994                }
4995                results.add(specificsPos, ri);
4996                ri.specificIndex = i;
4997                specificsPos++;
4998            }
4999        }
5000
5001        // Now we go through the remaining generic results and remove any
5002        // duplicate actions that are found here.
5003        N = results.size();
5004        for (int i=specificsPos; i<N-1; i++) {
5005            final ResolveInfo rii = results.get(i);
5006            if (rii.filter == null) {
5007                continue;
5008            }
5009
5010            // Iterate over all of the actions of this result's intent
5011            // filter...  typically this should be just one.
5012            final Iterator<String> it = rii.filter.actionsIterator();
5013            if (it == null) {
5014                continue;
5015            }
5016            while (it.hasNext()) {
5017                final String action = it.next();
5018                if (resultsAction != null && resultsAction.equals(action)) {
5019                    // If this action was explicitly requested, then don't
5020                    // remove things that have it.
5021                    continue;
5022                }
5023                for (int j=i+1; j<N; j++) {
5024                    final ResolveInfo rij = results.get(j);
5025                    if (rij.filter != null && rij.filter.hasAction(action)) {
5026                        results.remove(j);
5027                        if (DEBUG_INTENT_MATCHING) Log.v(
5028                            TAG, "Removing duplicate item from " + j
5029                            + " due to action " + action + " at " + i);
5030                        j--;
5031                        N--;
5032                    }
5033                }
5034            }
5035
5036            // If the caller didn't request filter information, drop it now
5037            // so we don't have to marshall/unmarshall it.
5038            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5039                rii.filter = null;
5040            }
5041        }
5042
5043        // Filter out the caller activity if so requested.
5044        if (caller != null) {
5045            N = results.size();
5046            for (int i=0; i<N; i++) {
5047                ActivityInfo ainfo = results.get(i).activityInfo;
5048                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5049                        && caller.getClassName().equals(ainfo.name)) {
5050                    results.remove(i);
5051                    break;
5052                }
5053            }
5054        }
5055
5056        // If the caller didn't request filter information,
5057        // drop them now so we don't have to
5058        // marshall/unmarshall it.
5059        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5060            N = results.size();
5061            for (int i=0; i<N; i++) {
5062                results.get(i).filter = null;
5063            }
5064        }
5065
5066        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5067        return results;
5068    }
5069
5070    @Override
5071    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5072            int userId) {
5073        if (!sUserManager.exists(userId)) return Collections.emptyList();
5074        ComponentName comp = intent.getComponent();
5075        if (comp == null) {
5076            if (intent.getSelector() != null) {
5077                intent = intent.getSelector();
5078                comp = intent.getComponent();
5079            }
5080        }
5081        if (comp != null) {
5082            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5083            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5084            if (ai != null) {
5085                ResolveInfo ri = new ResolveInfo();
5086                ri.activityInfo = ai;
5087                list.add(ri);
5088            }
5089            return list;
5090        }
5091
5092        // reader
5093        synchronized (mPackages) {
5094            String pkgName = intent.getPackage();
5095            if (pkgName == null) {
5096                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5097            }
5098            final PackageParser.Package pkg = mPackages.get(pkgName);
5099            if (pkg != null) {
5100                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5101                        userId);
5102            }
5103            return null;
5104        }
5105    }
5106
5107    @Override
5108    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5109        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5110        if (!sUserManager.exists(userId)) return null;
5111        if (query != null) {
5112            if (query.size() >= 1) {
5113                // If there is more than one service with the same priority,
5114                // just arbitrarily pick the first one.
5115                return query.get(0);
5116            }
5117        }
5118        return null;
5119    }
5120
5121    @Override
5122    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5123            int userId) {
5124        if (!sUserManager.exists(userId)) return Collections.emptyList();
5125        ComponentName comp = intent.getComponent();
5126        if (comp == null) {
5127            if (intent.getSelector() != null) {
5128                intent = intent.getSelector();
5129                comp = intent.getComponent();
5130            }
5131        }
5132        if (comp != null) {
5133            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5134            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5135            if (si != null) {
5136                final ResolveInfo ri = new ResolveInfo();
5137                ri.serviceInfo = si;
5138                list.add(ri);
5139            }
5140            return list;
5141        }
5142
5143        // reader
5144        synchronized (mPackages) {
5145            String pkgName = intent.getPackage();
5146            if (pkgName == null) {
5147                return mServices.queryIntent(intent, resolvedType, flags, userId);
5148            }
5149            final PackageParser.Package pkg = mPackages.get(pkgName);
5150            if (pkg != null) {
5151                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5152                        userId);
5153            }
5154            return null;
5155        }
5156    }
5157
5158    @Override
5159    public List<ResolveInfo> queryIntentContentProviders(
5160            Intent intent, String resolvedType, int flags, int userId) {
5161        if (!sUserManager.exists(userId)) return Collections.emptyList();
5162        ComponentName comp = intent.getComponent();
5163        if (comp == null) {
5164            if (intent.getSelector() != null) {
5165                intent = intent.getSelector();
5166                comp = intent.getComponent();
5167            }
5168        }
5169        if (comp != null) {
5170            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5171            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5172            if (pi != null) {
5173                final ResolveInfo ri = new ResolveInfo();
5174                ri.providerInfo = pi;
5175                list.add(ri);
5176            }
5177            return list;
5178        }
5179
5180        // reader
5181        synchronized (mPackages) {
5182            String pkgName = intent.getPackage();
5183            if (pkgName == null) {
5184                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5185            }
5186            final PackageParser.Package pkg = mPackages.get(pkgName);
5187            if (pkg != null) {
5188                return mProviders.queryIntentForPackage(
5189                        intent, resolvedType, flags, pkg.providers, userId);
5190            }
5191            return null;
5192        }
5193    }
5194
5195    @Override
5196    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5197        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5198
5199        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5200
5201        // writer
5202        synchronized (mPackages) {
5203            ArrayList<PackageInfo> list;
5204            if (listUninstalled) {
5205                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5206                for (PackageSetting ps : mSettings.mPackages.values()) {
5207                    PackageInfo pi;
5208                    if (ps.pkg != null) {
5209                        pi = generatePackageInfo(ps.pkg, flags, userId);
5210                    } else {
5211                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5212                    }
5213                    if (pi != null) {
5214                        list.add(pi);
5215                    }
5216                }
5217            } else {
5218                list = new ArrayList<PackageInfo>(mPackages.size());
5219                for (PackageParser.Package p : mPackages.values()) {
5220                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5221                    if (pi != null) {
5222                        list.add(pi);
5223                    }
5224                }
5225            }
5226
5227            return new ParceledListSlice<PackageInfo>(list);
5228        }
5229    }
5230
5231    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5232            String[] permissions, boolean[] tmp, int flags, int userId) {
5233        int numMatch = 0;
5234        final PermissionsState permissionsState = ps.getPermissionsState();
5235        for (int i=0; i<permissions.length; i++) {
5236            final String permission = permissions[i];
5237            if (permissionsState.hasPermission(permission, userId)) {
5238                tmp[i] = true;
5239                numMatch++;
5240            } else {
5241                tmp[i] = false;
5242            }
5243        }
5244        if (numMatch == 0) {
5245            return;
5246        }
5247        PackageInfo pi;
5248        if (ps.pkg != null) {
5249            pi = generatePackageInfo(ps.pkg, flags, userId);
5250        } else {
5251            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5252        }
5253        // The above might return null in cases of uninstalled apps or install-state
5254        // skew across users/profiles.
5255        if (pi != null) {
5256            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5257                if (numMatch == permissions.length) {
5258                    pi.requestedPermissions = permissions;
5259                } else {
5260                    pi.requestedPermissions = new String[numMatch];
5261                    numMatch = 0;
5262                    for (int i=0; i<permissions.length; i++) {
5263                        if (tmp[i]) {
5264                            pi.requestedPermissions[numMatch] = permissions[i];
5265                            numMatch++;
5266                        }
5267                    }
5268                }
5269            }
5270            list.add(pi);
5271        }
5272    }
5273
5274    @Override
5275    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5276            String[] permissions, 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<PackageInfo> list = new ArrayList<PackageInfo>();
5283            boolean[] tmpBools = new boolean[permissions.length];
5284            if (listUninstalled) {
5285                for (PackageSetting ps : mSettings.mPackages.values()) {
5286                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5287                }
5288            } else {
5289                for (PackageParser.Package pkg : mPackages.values()) {
5290                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5291                    if (ps != null) {
5292                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5293                                userId);
5294                    }
5295                }
5296            }
5297
5298            return new ParceledListSlice<PackageInfo>(list);
5299        }
5300    }
5301
5302    @Override
5303    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5304        if (!sUserManager.exists(userId)) return null;
5305        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5306
5307        // writer
5308        synchronized (mPackages) {
5309            ArrayList<ApplicationInfo> list;
5310            if (listUninstalled) {
5311                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5312                for (PackageSetting ps : mSettings.mPackages.values()) {
5313                    ApplicationInfo ai;
5314                    if (ps.pkg != null) {
5315                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5316                                ps.readUserState(userId), userId);
5317                    } else {
5318                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5319                    }
5320                    if (ai != null) {
5321                        list.add(ai);
5322                    }
5323                }
5324            } else {
5325                list = new ArrayList<ApplicationInfo>(mPackages.size());
5326                for (PackageParser.Package p : mPackages.values()) {
5327                    if (p.mExtras != null) {
5328                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5329                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5330                        if (ai != null) {
5331                            list.add(ai);
5332                        }
5333                    }
5334                }
5335            }
5336
5337            return new ParceledListSlice<ApplicationInfo>(list);
5338        }
5339    }
5340
5341    public List<ApplicationInfo> getPersistentApplications(int flags) {
5342        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5343
5344        // reader
5345        synchronized (mPackages) {
5346            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5347            final int userId = UserHandle.getCallingUserId();
5348            while (i.hasNext()) {
5349                final PackageParser.Package p = i.next();
5350                if (p.applicationInfo != null
5351                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5352                        && (!mSafeMode || isSystemApp(p))) {
5353                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5354                    if (ps != null) {
5355                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5356                                ps.readUserState(userId), userId);
5357                        if (ai != null) {
5358                            finalList.add(ai);
5359                        }
5360                    }
5361                }
5362            }
5363        }
5364
5365        return finalList;
5366    }
5367
5368    @Override
5369    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5370        if (!sUserManager.exists(userId)) return null;
5371        // reader
5372        synchronized (mPackages) {
5373            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5374            PackageSetting ps = provider != null
5375                    ? mSettings.mPackages.get(provider.owner.packageName)
5376                    : null;
5377            return ps != null
5378                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5379                    && (!mSafeMode || (provider.info.applicationInfo.flags
5380                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5381                    ? PackageParser.generateProviderInfo(provider, flags,
5382                            ps.readUserState(userId), userId)
5383                    : null;
5384        }
5385    }
5386
5387    /**
5388     * @deprecated
5389     */
5390    @Deprecated
5391    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5392        // reader
5393        synchronized (mPackages) {
5394            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5395                    .entrySet().iterator();
5396            final int userId = UserHandle.getCallingUserId();
5397            while (i.hasNext()) {
5398                Map.Entry<String, PackageParser.Provider> entry = i.next();
5399                PackageParser.Provider p = entry.getValue();
5400                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5401
5402                if (ps != null && p.syncable
5403                        && (!mSafeMode || (p.info.applicationInfo.flags
5404                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5405                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5406                            ps.readUserState(userId), userId);
5407                    if (info != null) {
5408                        outNames.add(entry.getKey());
5409                        outInfo.add(info);
5410                    }
5411                }
5412            }
5413        }
5414    }
5415
5416    @Override
5417    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5418            int uid, int flags) {
5419        ArrayList<ProviderInfo> finalList = null;
5420        // reader
5421        synchronized (mPackages) {
5422            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5423            final int userId = processName != null ?
5424                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5425            while (i.hasNext()) {
5426                final PackageParser.Provider p = i.next();
5427                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5428                if (ps != null && p.info.authority != null
5429                        && (processName == null
5430                                || (p.info.processName.equals(processName)
5431                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5432                        && mSettings.isEnabledLPr(p.info, flags, userId)
5433                        && (!mSafeMode
5434                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5435                    if (finalList == null) {
5436                        finalList = new ArrayList<ProviderInfo>(3);
5437                    }
5438                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5439                            ps.readUserState(userId), userId);
5440                    if (info != null) {
5441                        finalList.add(info);
5442                    }
5443                }
5444            }
5445        }
5446
5447        if (finalList != null) {
5448            Collections.sort(finalList, mProviderInitOrderSorter);
5449            return new ParceledListSlice<ProviderInfo>(finalList);
5450        }
5451
5452        return null;
5453    }
5454
5455    @Override
5456    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5457            int flags) {
5458        // reader
5459        synchronized (mPackages) {
5460            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5461            return PackageParser.generateInstrumentationInfo(i, flags);
5462        }
5463    }
5464
5465    @Override
5466    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5467            int flags) {
5468        ArrayList<InstrumentationInfo> finalList =
5469            new ArrayList<InstrumentationInfo>();
5470
5471        // reader
5472        synchronized (mPackages) {
5473            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5474            while (i.hasNext()) {
5475                final PackageParser.Instrumentation p = i.next();
5476                if (targetPackage == null
5477                        || targetPackage.equals(p.info.targetPackage)) {
5478                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5479                            flags);
5480                    if (ii != null) {
5481                        finalList.add(ii);
5482                    }
5483                }
5484            }
5485        }
5486
5487        return finalList;
5488    }
5489
5490    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5491        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5492        if (overlays == null) {
5493            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5494            return;
5495        }
5496        for (PackageParser.Package opkg : overlays.values()) {
5497            // Not much to do if idmap fails: we already logged the error
5498            // and we certainly don't want to abort installation of pkg simply
5499            // because an overlay didn't fit properly. For these reasons,
5500            // ignore the return value of createIdmapForPackagePairLI.
5501            createIdmapForPackagePairLI(pkg, opkg);
5502        }
5503    }
5504
5505    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5506            PackageParser.Package opkg) {
5507        if (!opkg.mTrustedOverlay) {
5508            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5509                    opkg.baseCodePath + ": overlay not trusted");
5510            return false;
5511        }
5512        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5513        if (overlaySet == null) {
5514            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5515                    opkg.baseCodePath + " but target package has no known overlays");
5516            return false;
5517        }
5518        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5519        // TODO: generate idmap for split APKs
5520        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5521            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5522                    + opkg.baseCodePath);
5523            return false;
5524        }
5525        PackageParser.Package[] overlayArray =
5526            overlaySet.values().toArray(new PackageParser.Package[0]);
5527        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5528            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5529                return p1.mOverlayPriority - p2.mOverlayPriority;
5530            }
5531        };
5532        Arrays.sort(overlayArray, cmp);
5533
5534        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5535        int i = 0;
5536        for (PackageParser.Package p : overlayArray) {
5537            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5538        }
5539        return true;
5540    }
5541
5542    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5543        final File[] files = dir.listFiles();
5544        if (ArrayUtils.isEmpty(files)) {
5545            Log.d(TAG, "No files in app dir " + dir);
5546            return;
5547        }
5548
5549        if (DEBUG_PACKAGE_SCANNING) {
5550            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5551                    + " flags=0x" + Integer.toHexString(parseFlags));
5552        }
5553
5554        for (File file : files) {
5555            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5556                    && !PackageInstallerService.isStageName(file.getName());
5557            if (!isPackage) {
5558                // Ignore entries which are not packages
5559                continue;
5560            }
5561            try {
5562                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5563                        scanFlags, currentTime, null);
5564            } catch (PackageManagerException e) {
5565                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5566
5567                // Delete invalid userdata apps
5568                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5569                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5570                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5571                    if (file.isDirectory()) {
5572                        mInstaller.rmPackageDir(file.getAbsolutePath());
5573                    } else {
5574                        file.delete();
5575                    }
5576                }
5577            }
5578        }
5579    }
5580
5581    private static File getSettingsProblemFile() {
5582        File dataDir = Environment.getDataDirectory();
5583        File systemDir = new File(dataDir, "system");
5584        File fname = new File(systemDir, "uiderrors.txt");
5585        return fname;
5586    }
5587
5588    static void reportSettingsProblem(int priority, String msg) {
5589        logCriticalInfo(priority, msg);
5590    }
5591
5592    static void logCriticalInfo(int priority, String msg) {
5593        Slog.println(priority, TAG, msg);
5594        EventLogTags.writePmCriticalInfo(msg);
5595        try {
5596            File fname = getSettingsProblemFile();
5597            FileOutputStream out = new FileOutputStream(fname, true);
5598            PrintWriter pw = new FastPrintWriter(out);
5599            SimpleDateFormat formatter = new SimpleDateFormat();
5600            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5601            pw.println(dateString + ": " + msg);
5602            pw.close();
5603            FileUtils.setPermissions(
5604                    fname.toString(),
5605                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5606                    -1, -1);
5607        } catch (java.io.IOException e) {
5608        }
5609    }
5610
5611    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5612            PackageParser.Package pkg, File srcFile, int parseFlags)
5613            throws PackageManagerException {
5614        if (ps != null
5615                && ps.codePath.equals(srcFile)
5616                && ps.timeStamp == srcFile.lastModified()
5617                && !isCompatSignatureUpdateNeeded(pkg)
5618                && !isRecoverSignatureUpdateNeeded(pkg)) {
5619            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5620            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5621            ArraySet<PublicKey> signingKs;
5622            synchronized (mPackages) {
5623                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5624            }
5625            if (ps.signatures.mSignatures != null
5626                    && ps.signatures.mSignatures.length != 0
5627                    && signingKs != null) {
5628                // Optimization: reuse the existing cached certificates
5629                // if the package appears to be unchanged.
5630                pkg.mSignatures = ps.signatures.mSignatures;
5631                pkg.mSigningKeys = signingKs;
5632                return;
5633            }
5634
5635            Slog.w(TAG, "PackageSetting for " + ps.name
5636                    + " is missing signatures.  Collecting certs again to recover them.");
5637        } else {
5638            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5639        }
5640
5641        try {
5642            pp.collectCertificates(pkg, parseFlags);
5643            pp.collectManifestDigest(pkg);
5644        } catch (PackageParserException e) {
5645            throw PackageManagerException.from(e);
5646        }
5647    }
5648
5649    /*
5650     *  Scan a package and return the newly parsed package.
5651     *  Returns null in case of errors and the error code is stored in mLastScanError
5652     */
5653    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5654            long currentTime, UserHandle user) throws PackageManagerException {
5655        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5656        parseFlags |= mDefParseFlags;
5657        PackageParser pp = new PackageParser();
5658        pp.setSeparateProcesses(mSeparateProcesses);
5659        pp.setOnlyCoreApps(mOnlyCore);
5660        pp.setDisplayMetrics(mMetrics);
5661
5662        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5663            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5664        }
5665
5666        final PackageParser.Package pkg;
5667        try {
5668            pkg = pp.parsePackage(scanFile, parseFlags);
5669        } catch (PackageParserException e) {
5670            throw PackageManagerException.from(e);
5671        }
5672
5673        PackageSetting ps = null;
5674        PackageSetting updatedPkg;
5675        // reader
5676        synchronized (mPackages) {
5677            // Look to see if we already know about this package.
5678            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5679            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5680                // This package has been renamed to its original name.  Let's
5681                // use that.
5682                ps = mSettings.peekPackageLPr(oldName);
5683            }
5684            // If there was no original package, see one for the real package name.
5685            if (ps == null) {
5686                ps = mSettings.peekPackageLPr(pkg.packageName);
5687            }
5688            // Check to see if this package could be hiding/updating a system
5689            // package.  Must look for it either under the original or real
5690            // package name depending on our state.
5691            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5692            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5693        }
5694        boolean updatedPkgBetter = false;
5695        // First check if this is a system package that may involve an update
5696        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5697            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5698            // it needs to drop FLAG_PRIVILEGED.
5699            if (locationIsPrivileged(scanFile)) {
5700                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5701            } else {
5702                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5703            }
5704
5705            if (ps != null && !ps.codePath.equals(scanFile)) {
5706                // The path has changed from what was last scanned...  check the
5707                // version of the new path against what we have stored to determine
5708                // what to do.
5709                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5710                if (pkg.mVersionCode <= ps.versionCode) {
5711                    // The system package has been updated and the code path does not match
5712                    // Ignore entry. Skip it.
5713                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5714                            + " ignored: updated version " + ps.versionCode
5715                            + " better than this " + pkg.mVersionCode);
5716                    if (!updatedPkg.codePath.equals(scanFile)) {
5717                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5718                                + ps.name + " changing from " + updatedPkg.codePathString
5719                                + " to " + scanFile);
5720                        updatedPkg.codePath = scanFile;
5721                        updatedPkg.codePathString = scanFile.toString();
5722                        updatedPkg.resourcePath = scanFile;
5723                        updatedPkg.resourcePathString = scanFile.toString();
5724                    }
5725                    updatedPkg.pkg = pkg;
5726                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5727                            "Package " + ps.name + " at " + scanFile
5728                                    + " ignored: updated version " + ps.versionCode
5729                                    + " better than this " + pkg.mVersionCode);
5730                } else {
5731                    // The current app on the system partition is better than
5732                    // what we have updated to on the data partition; switch
5733                    // back to the system partition version.
5734                    // At this point, its safely assumed that package installation for
5735                    // apps in system partition will go through. If not there won't be a working
5736                    // version of the app
5737                    // writer
5738                    synchronized (mPackages) {
5739                        // Just remove the loaded entries from package lists.
5740                        mPackages.remove(ps.name);
5741                    }
5742
5743                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5744                            + " reverting from " + ps.codePathString
5745                            + ": new version " + pkg.mVersionCode
5746                            + " better than installed " + ps.versionCode);
5747
5748                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5749                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5750                    synchronized (mInstallLock) {
5751                        args.cleanUpResourcesLI();
5752                    }
5753                    synchronized (mPackages) {
5754                        mSettings.enableSystemPackageLPw(ps.name);
5755                    }
5756                    updatedPkgBetter = true;
5757                }
5758            }
5759        }
5760
5761        if (updatedPkg != null) {
5762            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5763            // initially
5764            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5765
5766            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5767            // flag set initially
5768            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5769                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5770            }
5771        }
5772
5773        // Verify certificates against what was last scanned
5774        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5775
5776        /*
5777         * A new system app appeared, but we already had a non-system one of the
5778         * same name installed earlier.
5779         */
5780        boolean shouldHideSystemApp = false;
5781        if (updatedPkg == null && ps != null
5782                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5783            /*
5784             * Check to make sure the signatures match first. If they don't,
5785             * wipe the installed application and its data.
5786             */
5787            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5788                    != PackageManager.SIGNATURE_MATCH) {
5789                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5790                        + " signatures don't match existing userdata copy; removing");
5791                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5792                ps = null;
5793            } else {
5794                /*
5795                 * If the newly-added system app is an older version than the
5796                 * already installed version, hide it. It will be scanned later
5797                 * and re-added like an update.
5798                 */
5799                if (pkg.mVersionCode <= ps.versionCode) {
5800                    shouldHideSystemApp = true;
5801                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5802                            + " but new version " + pkg.mVersionCode + " better than installed "
5803                            + ps.versionCode + "; hiding system");
5804                } else {
5805                    /*
5806                     * The newly found system app is a newer version that the
5807                     * one previously installed. Simply remove the
5808                     * already-installed application and replace it with our own
5809                     * while keeping the application data.
5810                     */
5811                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5812                            + " reverting from " + ps.codePathString + ": new version "
5813                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5814                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5815                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5816                    synchronized (mInstallLock) {
5817                        args.cleanUpResourcesLI();
5818                    }
5819                }
5820            }
5821        }
5822
5823        // The apk is forward locked (not public) if its code and resources
5824        // are kept in different files. (except for app in either system or
5825        // vendor path).
5826        // TODO grab this value from PackageSettings
5827        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5828            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5829                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5830            }
5831        }
5832
5833        // TODO: extend to support forward-locked splits
5834        String resourcePath = null;
5835        String baseResourcePath = null;
5836        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5837            if (ps != null && ps.resourcePathString != null) {
5838                resourcePath = ps.resourcePathString;
5839                baseResourcePath = ps.resourcePathString;
5840            } else {
5841                // Should not happen at all. Just log an error.
5842                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5843            }
5844        } else {
5845            resourcePath = pkg.codePath;
5846            baseResourcePath = pkg.baseCodePath;
5847        }
5848
5849        // Set application objects path explicitly.
5850        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5851        pkg.applicationInfo.setCodePath(pkg.codePath);
5852        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5853        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5854        pkg.applicationInfo.setResourcePath(resourcePath);
5855        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5856        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5857
5858        // Note that we invoke the following method only if we are about to unpack an application
5859        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5860                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5861
5862        /*
5863         * If the system app should be overridden by a previously installed
5864         * data, hide the system app now and let the /data/app scan pick it up
5865         * again.
5866         */
5867        if (shouldHideSystemApp) {
5868            synchronized (mPackages) {
5869                /*
5870                 * We have to grant systems permissions before we hide, because
5871                 * grantPermissions will assume the package update is trying to
5872                 * expand its permissions.
5873                 */
5874                grantPermissionsLPw(pkg, true, pkg.packageName);
5875                mSettings.disableSystemPackageLPw(pkg.packageName);
5876            }
5877        }
5878
5879        return scannedPkg;
5880    }
5881
5882    private static String fixProcessName(String defProcessName,
5883            String processName, int uid) {
5884        if (processName == null) {
5885            return defProcessName;
5886        }
5887        return processName;
5888    }
5889
5890    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5891            throws PackageManagerException {
5892        if (pkgSetting.signatures.mSignatures != null) {
5893            // Already existing package. Make sure signatures match
5894            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5895                    == PackageManager.SIGNATURE_MATCH;
5896            if (!match) {
5897                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5898                        == PackageManager.SIGNATURE_MATCH;
5899            }
5900            if (!match) {
5901                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5902                        == PackageManager.SIGNATURE_MATCH;
5903            }
5904            if (!match) {
5905                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5906                        + pkg.packageName + " signatures do not match the "
5907                        + "previously installed version; ignoring!");
5908            }
5909        }
5910
5911        // Check for shared user signatures
5912        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5913            // Already existing package. Make sure signatures match
5914            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5915                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5916            if (!match) {
5917                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5918                        == PackageManager.SIGNATURE_MATCH;
5919            }
5920            if (!match) {
5921                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5922                        == PackageManager.SIGNATURE_MATCH;
5923            }
5924            if (!match) {
5925                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5926                        "Package " + pkg.packageName
5927                        + " has no signatures that match those in shared user "
5928                        + pkgSetting.sharedUser.name + "; ignoring!");
5929            }
5930        }
5931    }
5932
5933    /**
5934     * Enforces that only the system UID or root's UID can call a method exposed
5935     * via Binder.
5936     *
5937     * @param message used as message if SecurityException is thrown
5938     * @throws SecurityException if the caller is not system or root
5939     */
5940    private static final void enforceSystemOrRoot(String message) {
5941        final int uid = Binder.getCallingUid();
5942        if (uid != Process.SYSTEM_UID && uid != 0) {
5943            throw new SecurityException(message);
5944        }
5945    }
5946
5947    @Override
5948    public void performBootDexOpt() {
5949        enforceSystemOrRoot("Only the system can request dexopt be performed");
5950
5951        // Before everything else, see whether we need to fstrim.
5952        try {
5953            IMountService ms = PackageHelper.getMountService();
5954            if (ms != null) {
5955                final boolean isUpgrade = isUpgrade();
5956                boolean doTrim = isUpgrade;
5957                if (doTrim) {
5958                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5959                } else {
5960                    final long interval = android.provider.Settings.Global.getLong(
5961                            mContext.getContentResolver(),
5962                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5963                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5964                    if (interval > 0) {
5965                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5966                        if (timeSinceLast > interval) {
5967                            doTrim = true;
5968                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5969                                    + "; running immediately");
5970                        }
5971                    }
5972                }
5973                if (doTrim) {
5974                    if (!isFirstBoot()) {
5975                        try {
5976                            ActivityManagerNative.getDefault().showBootMessage(
5977                                    mContext.getResources().getString(
5978                                            R.string.android_upgrading_fstrim), true);
5979                        } catch (RemoteException e) {
5980                        }
5981                    }
5982                    ms.runMaintenance();
5983                }
5984            } else {
5985                Slog.e(TAG, "Mount service unavailable!");
5986            }
5987        } catch (RemoteException e) {
5988            // Can't happen; MountService is local
5989        }
5990
5991        final ArraySet<PackageParser.Package> pkgs;
5992        synchronized (mPackages) {
5993            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5994        }
5995
5996        if (pkgs != null) {
5997            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5998            // in case the device runs out of space.
5999            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6000            // Give priority to core apps.
6001            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6002                PackageParser.Package pkg = it.next();
6003                if (pkg.coreApp) {
6004                    if (DEBUG_DEXOPT) {
6005                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6006                    }
6007                    sortedPkgs.add(pkg);
6008                    it.remove();
6009                }
6010            }
6011            // Give priority to system apps that listen for pre boot complete.
6012            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6013            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6014            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6015                PackageParser.Package pkg = it.next();
6016                if (pkgNames.contains(pkg.packageName)) {
6017                    if (DEBUG_DEXOPT) {
6018                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6019                    }
6020                    sortedPkgs.add(pkg);
6021                    it.remove();
6022                }
6023            }
6024            // Give priority to system apps.
6025            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6026                PackageParser.Package pkg = it.next();
6027                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6028                    if (DEBUG_DEXOPT) {
6029                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6030                    }
6031                    sortedPkgs.add(pkg);
6032                    it.remove();
6033                }
6034            }
6035            // Give priority to updated system apps.
6036            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6037                PackageParser.Package pkg = it.next();
6038                if (pkg.isUpdatedSystemApp()) {
6039                    if (DEBUG_DEXOPT) {
6040                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6041                    }
6042                    sortedPkgs.add(pkg);
6043                    it.remove();
6044                }
6045            }
6046            // Give priority to apps that listen for boot complete.
6047            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6048            pkgNames = getPackageNamesForIntent(intent);
6049            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6050                PackageParser.Package pkg = it.next();
6051                if (pkgNames.contains(pkg.packageName)) {
6052                    if (DEBUG_DEXOPT) {
6053                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6054                    }
6055                    sortedPkgs.add(pkg);
6056                    it.remove();
6057                }
6058            }
6059            // Filter out packages that aren't recently used.
6060            filterRecentlyUsedApps(pkgs);
6061            // Add all remaining apps.
6062            for (PackageParser.Package pkg : pkgs) {
6063                if (DEBUG_DEXOPT) {
6064                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6065                }
6066                sortedPkgs.add(pkg);
6067            }
6068
6069            // If we want to be lazy, filter everything that wasn't recently used.
6070            if (mLazyDexOpt) {
6071                filterRecentlyUsedApps(sortedPkgs);
6072            }
6073
6074            int i = 0;
6075            int total = sortedPkgs.size();
6076            File dataDir = Environment.getDataDirectory();
6077            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6078            if (lowThreshold == 0) {
6079                throw new IllegalStateException("Invalid low memory threshold");
6080            }
6081            for (PackageParser.Package pkg : sortedPkgs) {
6082                long usableSpace = dataDir.getUsableSpace();
6083                if (usableSpace < lowThreshold) {
6084                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6085                    break;
6086                }
6087                performBootDexOpt(pkg, ++i, total);
6088            }
6089        }
6090    }
6091
6092    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6093        // Filter out packages that aren't recently used.
6094        //
6095        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6096        // should do a full dexopt.
6097        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6098            int total = pkgs.size();
6099            int skipped = 0;
6100            long now = System.currentTimeMillis();
6101            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6102                PackageParser.Package pkg = i.next();
6103                long then = pkg.mLastPackageUsageTimeInMills;
6104                if (then + mDexOptLRUThresholdInMills < now) {
6105                    if (DEBUG_DEXOPT) {
6106                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6107                              ((then == 0) ? "never" : new Date(then)));
6108                    }
6109                    i.remove();
6110                    skipped++;
6111                }
6112            }
6113            if (DEBUG_DEXOPT) {
6114                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6115            }
6116        }
6117    }
6118
6119    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6120        List<ResolveInfo> ris = null;
6121        try {
6122            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6123                    intent, null, 0, UserHandle.USER_OWNER);
6124        } catch (RemoteException e) {
6125        }
6126        ArraySet<String> pkgNames = new ArraySet<String>();
6127        if (ris != null) {
6128            for (ResolveInfo ri : ris) {
6129                pkgNames.add(ri.activityInfo.packageName);
6130            }
6131        }
6132        return pkgNames;
6133    }
6134
6135    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6136        if (DEBUG_DEXOPT) {
6137            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6138        }
6139        if (!isFirstBoot()) {
6140            try {
6141                ActivityManagerNative.getDefault().showBootMessage(
6142                        mContext.getResources().getString(R.string.android_upgrading_apk,
6143                                curr, total), true);
6144            } catch (RemoteException e) {
6145            }
6146        }
6147        PackageParser.Package p = pkg;
6148        synchronized (mInstallLock) {
6149            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6150                    false /* force dex */, false /* defer */, true /* include dependencies */);
6151        }
6152    }
6153
6154    @Override
6155    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6156        return performDexOpt(packageName, instructionSet, false);
6157    }
6158
6159    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6160        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6161        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6162        if (!dexopt && !updateUsage) {
6163            // We aren't going to dexopt or update usage, so bail early.
6164            return false;
6165        }
6166        PackageParser.Package p;
6167        final String targetInstructionSet;
6168        synchronized (mPackages) {
6169            p = mPackages.get(packageName);
6170            if (p == null) {
6171                return false;
6172            }
6173            if (updateUsage) {
6174                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6175            }
6176            mPackageUsage.write(false);
6177            if (!dexopt) {
6178                // We aren't going to dexopt, so bail early.
6179                return false;
6180            }
6181
6182            targetInstructionSet = instructionSet != null ? instructionSet :
6183                    getPrimaryInstructionSet(p.applicationInfo);
6184            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6185                return false;
6186            }
6187        }
6188        long callingId = Binder.clearCallingIdentity();
6189        try {
6190            synchronized (mInstallLock) {
6191                final String[] instructionSets = new String[] { targetInstructionSet };
6192                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6193                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6194                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6195            }
6196        } finally {
6197            Binder.restoreCallingIdentity(callingId);
6198        }
6199    }
6200
6201    public ArraySet<String> getPackagesThatNeedDexOpt() {
6202        ArraySet<String> pkgs = null;
6203        synchronized (mPackages) {
6204            for (PackageParser.Package p : mPackages.values()) {
6205                if (DEBUG_DEXOPT) {
6206                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6207                }
6208                if (!p.mDexOptPerformed.isEmpty()) {
6209                    continue;
6210                }
6211                if (pkgs == null) {
6212                    pkgs = new ArraySet<String>();
6213                }
6214                pkgs.add(p.packageName);
6215            }
6216        }
6217        return pkgs;
6218    }
6219
6220    public void shutdown() {
6221        mPackageUsage.write(true);
6222    }
6223
6224    @Override
6225    public void forceDexOpt(String packageName) {
6226        enforceSystemOrRoot("forceDexOpt");
6227
6228        PackageParser.Package pkg;
6229        synchronized (mPackages) {
6230            pkg = mPackages.get(packageName);
6231            if (pkg == null) {
6232                throw new IllegalArgumentException("Missing package: " + packageName);
6233            }
6234        }
6235
6236        synchronized (mInstallLock) {
6237            final String[] instructionSets = new String[] {
6238                    getPrimaryInstructionSet(pkg.applicationInfo) };
6239            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6240                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6241            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6242                throw new IllegalStateException("Failed to dexopt: " + res);
6243            }
6244        }
6245    }
6246
6247    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6248        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6249            Slog.w(TAG, "Unable to update from " + oldPkg.name
6250                    + " to " + newPkg.packageName
6251                    + ": old package not in system partition");
6252            return false;
6253        } else if (mPackages.get(oldPkg.name) != null) {
6254            Slog.w(TAG, "Unable to update from " + oldPkg.name
6255                    + " to " + newPkg.packageName
6256                    + ": old package still exists");
6257            return false;
6258        }
6259        return true;
6260    }
6261
6262    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6263        int[] users = sUserManager.getUserIds();
6264        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6265        if (res < 0) {
6266            return res;
6267        }
6268        for (int user : users) {
6269            if (user != 0) {
6270                res = mInstaller.createUserData(volumeUuid, packageName,
6271                        UserHandle.getUid(user, uid), user, seinfo);
6272                if (res < 0) {
6273                    return res;
6274                }
6275            }
6276        }
6277        return res;
6278    }
6279
6280    private int removeDataDirsLI(String volumeUuid, String packageName) {
6281        int[] users = sUserManager.getUserIds();
6282        int res = 0;
6283        for (int user : users) {
6284            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6285            if (resInner < 0) {
6286                res = resInner;
6287            }
6288        }
6289
6290        return res;
6291    }
6292
6293    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6294        int[] users = sUserManager.getUserIds();
6295        int res = 0;
6296        for (int user : users) {
6297            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6298            if (resInner < 0) {
6299                res = resInner;
6300            }
6301        }
6302        return res;
6303    }
6304
6305    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6306            PackageParser.Package changingLib) {
6307        if (file.path != null) {
6308            usesLibraryFiles.add(file.path);
6309            return;
6310        }
6311        PackageParser.Package p = mPackages.get(file.apk);
6312        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6313            // If we are doing this while in the middle of updating a library apk,
6314            // then we need to make sure to use that new apk for determining the
6315            // dependencies here.  (We haven't yet finished committing the new apk
6316            // to the package manager state.)
6317            if (p == null || p.packageName.equals(changingLib.packageName)) {
6318                p = changingLib;
6319            }
6320        }
6321        if (p != null) {
6322            usesLibraryFiles.addAll(p.getAllCodePaths());
6323        }
6324    }
6325
6326    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6327            PackageParser.Package changingLib) throws PackageManagerException {
6328        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6329            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6330            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6331            for (int i=0; i<N; i++) {
6332                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6333                if (file == null) {
6334                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6335                            "Package " + pkg.packageName + " requires unavailable shared library "
6336                            + pkg.usesLibraries.get(i) + "; failing!");
6337                }
6338                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6339            }
6340            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6341            for (int i=0; i<N; i++) {
6342                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6343                if (file == null) {
6344                    Slog.w(TAG, "Package " + pkg.packageName
6345                            + " desires unavailable shared library "
6346                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6347                } else {
6348                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6349                }
6350            }
6351            N = usesLibraryFiles.size();
6352            if (N > 0) {
6353                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6354            } else {
6355                pkg.usesLibraryFiles = null;
6356            }
6357        }
6358    }
6359
6360    private static boolean hasString(List<String> list, List<String> which) {
6361        if (list == null) {
6362            return false;
6363        }
6364        for (int i=list.size()-1; i>=0; i--) {
6365            for (int j=which.size()-1; j>=0; j--) {
6366                if (which.get(j).equals(list.get(i))) {
6367                    return true;
6368                }
6369            }
6370        }
6371        return false;
6372    }
6373
6374    private void updateAllSharedLibrariesLPw() {
6375        for (PackageParser.Package pkg : mPackages.values()) {
6376            try {
6377                updateSharedLibrariesLPw(pkg, null);
6378            } catch (PackageManagerException e) {
6379                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6380            }
6381        }
6382    }
6383
6384    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6385            PackageParser.Package changingPkg) {
6386        ArrayList<PackageParser.Package> res = null;
6387        for (PackageParser.Package pkg : mPackages.values()) {
6388            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6389                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6390                if (res == null) {
6391                    res = new ArrayList<PackageParser.Package>();
6392                }
6393                res.add(pkg);
6394                try {
6395                    updateSharedLibrariesLPw(pkg, changingPkg);
6396                } catch (PackageManagerException e) {
6397                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6398                }
6399            }
6400        }
6401        return res;
6402    }
6403
6404    /**
6405     * Derive the value of the {@code cpuAbiOverride} based on the provided
6406     * value and an optional stored value from the package settings.
6407     */
6408    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6409        String cpuAbiOverride = null;
6410
6411        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6412            cpuAbiOverride = null;
6413        } else if (abiOverride != null) {
6414            cpuAbiOverride = abiOverride;
6415        } else if (settings != null) {
6416            cpuAbiOverride = settings.cpuAbiOverrideString;
6417        }
6418
6419        return cpuAbiOverride;
6420    }
6421
6422    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6423            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6424        boolean success = false;
6425        try {
6426            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6427                    currentTime, user);
6428            success = true;
6429            return res;
6430        } finally {
6431            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6432                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6433            }
6434        }
6435    }
6436
6437    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6438            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6439        final File scanFile = new File(pkg.codePath);
6440        if (pkg.applicationInfo.getCodePath() == null ||
6441                pkg.applicationInfo.getResourcePath() == null) {
6442            // Bail out. The resource and code paths haven't been set.
6443            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6444                    "Code and resource paths haven't been set correctly");
6445        }
6446
6447        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6448            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6449        } else {
6450            // Only allow system apps to be flagged as core apps.
6451            pkg.coreApp = false;
6452        }
6453
6454        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6455            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6456        }
6457
6458        if (mCustomResolverComponentName != null &&
6459                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6460            setUpCustomResolverActivity(pkg);
6461        }
6462
6463        if (pkg.packageName.equals("android")) {
6464            synchronized (mPackages) {
6465                if (mAndroidApplication != null) {
6466                    Slog.w(TAG, "*************************************************");
6467                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6468                    Slog.w(TAG, " file=" + scanFile);
6469                    Slog.w(TAG, "*************************************************");
6470                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6471                            "Core android package being redefined.  Skipping.");
6472                }
6473
6474                // Set up information for our fall-back user intent resolution activity.
6475                mPlatformPackage = pkg;
6476                pkg.mVersionCode = mSdkVersion;
6477                mAndroidApplication = pkg.applicationInfo;
6478
6479                if (!mResolverReplaced) {
6480                    mResolveActivity.applicationInfo = mAndroidApplication;
6481                    mResolveActivity.name = ResolverActivity.class.getName();
6482                    mResolveActivity.packageName = mAndroidApplication.packageName;
6483                    mResolveActivity.processName = "system:ui";
6484                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6485                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6486                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6487                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6488                    mResolveActivity.exported = true;
6489                    mResolveActivity.enabled = true;
6490                    mResolveInfo.activityInfo = mResolveActivity;
6491                    mResolveInfo.priority = 0;
6492                    mResolveInfo.preferredOrder = 0;
6493                    mResolveInfo.match = 0;
6494                    mResolveComponentName = new ComponentName(
6495                            mAndroidApplication.packageName, mResolveActivity.name);
6496                }
6497            }
6498        }
6499
6500        if (DEBUG_PACKAGE_SCANNING) {
6501            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6502                Log.d(TAG, "Scanning package " + pkg.packageName);
6503        }
6504
6505        if (mPackages.containsKey(pkg.packageName)
6506                || mSharedLibraries.containsKey(pkg.packageName)) {
6507            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6508                    "Application package " + pkg.packageName
6509                    + " already installed.  Skipping duplicate.");
6510        }
6511
6512        // If we're only installing presumed-existing packages, require that the
6513        // scanned APK is both already known and at the path previously established
6514        // for it.  Previously unknown packages we pick up normally, but if we have an
6515        // a priori expectation about this package's install presence, enforce it.
6516        // With a singular exception for new system packages. When an OTA contains
6517        // a new system package, we allow the codepath to change from a system location
6518        // to the user-installed location. If we don't allow this change, any newer,
6519        // user-installed version of the application will be ignored.
6520        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6521            if (mExpectingBetter.containsKey(pkg.packageName)) {
6522                logCriticalInfo(Log.WARN,
6523                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6524            } else {
6525                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6526                if (known != null) {
6527                    if (DEBUG_PACKAGE_SCANNING) {
6528                        Log.d(TAG, "Examining " + pkg.codePath
6529                                + " and requiring known paths " + known.codePathString
6530                                + " & " + known.resourcePathString);
6531                    }
6532                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6533                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6534                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6535                                "Application package " + pkg.packageName
6536                                + " found at " + pkg.applicationInfo.getCodePath()
6537                                + " but expected at " + known.codePathString + "; ignoring.");
6538                    }
6539                }
6540            }
6541        }
6542
6543        // Initialize package source and resource directories
6544        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6545        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6546
6547        SharedUserSetting suid = null;
6548        PackageSetting pkgSetting = null;
6549
6550        if (!isSystemApp(pkg)) {
6551            // Only system apps can use these features.
6552            pkg.mOriginalPackages = null;
6553            pkg.mRealPackage = null;
6554            pkg.mAdoptPermissions = null;
6555        }
6556
6557        // writer
6558        synchronized (mPackages) {
6559            if (pkg.mSharedUserId != null) {
6560                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6561                if (suid == null) {
6562                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6563                            "Creating application package " + pkg.packageName
6564                            + " for shared user failed");
6565                }
6566                if (DEBUG_PACKAGE_SCANNING) {
6567                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6568                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6569                                + "): packages=" + suid.packages);
6570                }
6571            }
6572
6573            // Check if we are renaming from an original package name.
6574            PackageSetting origPackage = null;
6575            String realName = null;
6576            if (pkg.mOriginalPackages != null) {
6577                // This package may need to be renamed to a previously
6578                // installed name.  Let's check on that...
6579                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6580                if (pkg.mOriginalPackages.contains(renamed)) {
6581                    // This package had originally been installed as the
6582                    // original name, and we have already taken care of
6583                    // transitioning to the new one.  Just update the new
6584                    // one to continue using the old name.
6585                    realName = pkg.mRealPackage;
6586                    if (!pkg.packageName.equals(renamed)) {
6587                        // Callers into this function may have already taken
6588                        // care of renaming the package; only do it here if
6589                        // it is not already done.
6590                        pkg.setPackageName(renamed);
6591                    }
6592
6593                } else {
6594                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6595                        if ((origPackage = mSettings.peekPackageLPr(
6596                                pkg.mOriginalPackages.get(i))) != null) {
6597                            // We do have the package already installed under its
6598                            // original name...  should we use it?
6599                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6600                                // New package is not compatible with original.
6601                                origPackage = null;
6602                                continue;
6603                            } else if (origPackage.sharedUser != null) {
6604                                // Make sure uid is compatible between packages.
6605                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6606                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6607                                            + " to " + pkg.packageName + ": old uid "
6608                                            + origPackage.sharedUser.name
6609                                            + " differs from " + pkg.mSharedUserId);
6610                                    origPackage = null;
6611                                    continue;
6612                                }
6613                            } else {
6614                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6615                                        + pkg.packageName + " to old name " + origPackage.name);
6616                            }
6617                            break;
6618                        }
6619                    }
6620                }
6621            }
6622
6623            if (mTransferedPackages.contains(pkg.packageName)) {
6624                Slog.w(TAG, "Package " + pkg.packageName
6625                        + " was transferred to another, but its .apk remains");
6626            }
6627
6628            // Just create the setting, don't add it yet. For already existing packages
6629            // the PkgSetting exists already and doesn't have to be created.
6630            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6631                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6632                    pkg.applicationInfo.primaryCpuAbi,
6633                    pkg.applicationInfo.secondaryCpuAbi,
6634                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6635                    user, false);
6636            if (pkgSetting == null) {
6637                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6638                        "Creating application package " + pkg.packageName + " failed");
6639            }
6640
6641            if (pkgSetting.origPackage != null) {
6642                // If we are first transitioning from an original package,
6643                // fix up the new package's name now.  We need to do this after
6644                // looking up the package under its new name, so getPackageLP
6645                // can take care of fiddling things correctly.
6646                pkg.setPackageName(origPackage.name);
6647
6648                // File a report about this.
6649                String msg = "New package " + pkgSetting.realName
6650                        + " renamed to replace old package " + pkgSetting.name;
6651                reportSettingsProblem(Log.WARN, msg);
6652
6653                // Make a note of it.
6654                mTransferedPackages.add(origPackage.name);
6655
6656                // No longer need to retain this.
6657                pkgSetting.origPackage = null;
6658            }
6659
6660            if (realName != null) {
6661                // Make a note of it.
6662                mTransferedPackages.add(pkg.packageName);
6663            }
6664
6665            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6666                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6667            }
6668
6669            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6670                // Check all shared libraries and map to their actual file path.
6671                // We only do this here for apps not on a system dir, because those
6672                // are the only ones that can fail an install due to this.  We
6673                // will take care of the system apps by updating all of their
6674                // library paths after the scan is done.
6675                updateSharedLibrariesLPw(pkg, null);
6676            }
6677
6678            if (mFoundPolicyFile) {
6679                SELinuxMMAC.assignSeinfoValue(pkg);
6680            }
6681
6682            pkg.applicationInfo.uid = pkgSetting.appId;
6683            pkg.mExtras = pkgSetting;
6684            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6685                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6686                    // We just determined the app is signed correctly, so bring
6687                    // over the latest parsed certs.
6688                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6689                } else {
6690                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6691                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6692                                "Package " + pkg.packageName + " upgrade keys do not match the "
6693                                + "previously installed version");
6694                    } else {
6695                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6696                        String msg = "System package " + pkg.packageName
6697                            + " signature changed; retaining data.";
6698                        reportSettingsProblem(Log.WARN, msg);
6699                    }
6700                }
6701            } else {
6702                try {
6703                    verifySignaturesLP(pkgSetting, pkg);
6704                    // We just determined the app is signed correctly, so bring
6705                    // over the latest parsed certs.
6706                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6707                } catch (PackageManagerException e) {
6708                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6709                        throw e;
6710                    }
6711                    // The signature has changed, but this package is in the system
6712                    // image...  let's recover!
6713                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6714                    // However...  if this package is part of a shared user, but it
6715                    // doesn't match the signature of the shared user, let's fail.
6716                    // What this means is that you can't change the signatures
6717                    // associated with an overall shared user, which doesn't seem all
6718                    // that unreasonable.
6719                    if (pkgSetting.sharedUser != null) {
6720                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6721                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6722                            throw new PackageManagerException(
6723                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6724                                            "Signature mismatch for shared user : "
6725                                            + pkgSetting.sharedUser);
6726                        }
6727                    }
6728                    // File a report about this.
6729                    String msg = "System package " + pkg.packageName
6730                        + " signature changed; retaining data.";
6731                    reportSettingsProblem(Log.WARN, msg);
6732                }
6733            }
6734            // Verify that this new package doesn't have any content providers
6735            // that conflict with existing packages.  Only do this if the
6736            // package isn't already installed, since we don't want to break
6737            // things that are installed.
6738            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6739                final int N = pkg.providers.size();
6740                int i;
6741                for (i=0; i<N; i++) {
6742                    PackageParser.Provider p = pkg.providers.get(i);
6743                    if (p.info.authority != null) {
6744                        String names[] = p.info.authority.split(";");
6745                        for (int j = 0; j < names.length; j++) {
6746                            if (mProvidersByAuthority.containsKey(names[j])) {
6747                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6748                                final String otherPackageName =
6749                                        ((other != null && other.getComponentName() != null) ?
6750                                                other.getComponentName().getPackageName() : "?");
6751                                throw new PackageManagerException(
6752                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6753                                                "Can't install because provider name " + names[j]
6754                                                + " (in package " + pkg.applicationInfo.packageName
6755                                                + ") is already used by " + otherPackageName);
6756                            }
6757                        }
6758                    }
6759                }
6760            }
6761
6762            if (pkg.mAdoptPermissions != null) {
6763                // This package wants to adopt ownership of permissions from
6764                // another package.
6765                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6766                    final String origName = pkg.mAdoptPermissions.get(i);
6767                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6768                    if (orig != null) {
6769                        if (verifyPackageUpdateLPr(orig, pkg)) {
6770                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6771                                    + pkg.packageName);
6772                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6773                        }
6774                    }
6775                }
6776            }
6777        }
6778
6779        final String pkgName = pkg.packageName;
6780
6781        final long scanFileTime = scanFile.lastModified();
6782        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6783        pkg.applicationInfo.processName = fixProcessName(
6784                pkg.applicationInfo.packageName,
6785                pkg.applicationInfo.processName,
6786                pkg.applicationInfo.uid);
6787
6788        File dataPath;
6789        if (mPlatformPackage == pkg) {
6790            // The system package is special.
6791            dataPath = new File(Environment.getDataDirectory(), "system");
6792
6793            pkg.applicationInfo.dataDir = dataPath.getPath();
6794
6795        } else {
6796            // This is a normal package, need to make its data directory.
6797            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6798                    UserHandle.USER_OWNER, pkg.packageName);
6799
6800            boolean uidError = false;
6801            if (dataPath.exists()) {
6802                int currentUid = 0;
6803                try {
6804                    StructStat stat = Os.stat(dataPath.getPath());
6805                    currentUid = stat.st_uid;
6806                } catch (ErrnoException e) {
6807                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6808                }
6809
6810                // If we have mismatched owners for the data path, we have a problem.
6811                if (currentUid != pkg.applicationInfo.uid) {
6812                    boolean recovered = false;
6813                    if (currentUid == 0) {
6814                        // The directory somehow became owned by root.  Wow.
6815                        // This is probably because the system was stopped while
6816                        // installd was in the middle of messing with its libs
6817                        // directory.  Ask installd to fix that.
6818                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6819                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6820                        if (ret >= 0) {
6821                            recovered = true;
6822                            String msg = "Package " + pkg.packageName
6823                                    + " unexpectedly changed to uid 0; recovered to " +
6824                                    + pkg.applicationInfo.uid;
6825                            reportSettingsProblem(Log.WARN, msg);
6826                        }
6827                    }
6828                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6829                            || (scanFlags&SCAN_BOOTING) != 0)) {
6830                        // If this is a system app, we can at least delete its
6831                        // current data so the application will still work.
6832                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6833                        if (ret >= 0) {
6834                            // TODO: Kill the processes first
6835                            // Old data gone!
6836                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6837                                    ? "System package " : "Third party package ";
6838                            String msg = prefix + pkg.packageName
6839                                    + " has changed from uid: "
6840                                    + currentUid + " to "
6841                                    + pkg.applicationInfo.uid + "; old data erased";
6842                            reportSettingsProblem(Log.WARN, msg);
6843                            recovered = true;
6844
6845                            // And now re-install the app.
6846                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6847                                    pkg.applicationInfo.seinfo);
6848                            if (ret == -1) {
6849                                // Ack should not happen!
6850                                msg = prefix + pkg.packageName
6851                                        + " could not have data directory re-created after delete.";
6852                                reportSettingsProblem(Log.WARN, msg);
6853                                throw new PackageManagerException(
6854                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6855                            }
6856                        }
6857                        if (!recovered) {
6858                            mHasSystemUidErrors = true;
6859                        }
6860                    } else if (!recovered) {
6861                        // If we allow this install to proceed, we will be broken.
6862                        // Abort, abort!
6863                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6864                                "scanPackageLI");
6865                    }
6866                    if (!recovered) {
6867                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6868                            + pkg.applicationInfo.uid + "/fs_"
6869                            + currentUid;
6870                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6871                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6872                        String msg = "Package " + pkg.packageName
6873                                + " has mismatched uid: "
6874                                + currentUid + " on disk, "
6875                                + pkg.applicationInfo.uid + " in settings";
6876                        // writer
6877                        synchronized (mPackages) {
6878                            mSettings.mReadMessages.append(msg);
6879                            mSettings.mReadMessages.append('\n');
6880                            uidError = true;
6881                            if (!pkgSetting.uidError) {
6882                                reportSettingsProblem(Log.ERROR, msg);
6883                            }
6884                        }
6885                    }
6886                }
6887                pkg.applicationInfo.dataDir = dataPath.getPath();
6888                if (mShouldRestoreconData) {
6889                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6890                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6891                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6892                }
6893            } else {
6894                if (DEBUG_PACKAGE_SCANNING) {
6895                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6896                        Log.v(TAG, "Want this data dir: " + dataPath);
6897                }
6898                //invoke installer to do the actual installation
6899                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6900                        pkg.applicationInfo.seinfo);
6901                if (ret < 0) {
6902                    // Error from installer
6903                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6904                            "Unable to create data dirs [errorCode=" + ret + "]");
6905                }
6906
6907                if (dataPath.exists()) {
6908                    pkg.applicationInfo.dataDir = dataPath.getPath();
6909                } else {
6910                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6911                    pkg.applicationInfo.dataDir = null;
6912                }
6913            }
6914
6915            pkgSetting.uidError = uidError;
6916        }
6917
6918        final String path = scanFile.getPath();
6919        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6920
6921        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6922            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6923
6924            // Some system apps still use directory structure for native libraries
6925            // in which case we might end up not detecting abi solely based on apk
6926            // structure. Try to detect abi based on directory structure.
6927            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6928                    pkg.applicationInfo.primaryCpuAbi == null) {
6929                setBundledAppAbisAndRoots(pkg, pkgSetting);
6930                setNativeLibraryPaths(pkg);
6931            }
6932
6933        } else {
6934            if ((scanFlags & SCAN_MOVE) != 0) {
6935                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6936                // but we already have this packages package info in the PackageSetting. We just
6937                // use that and derive the native library path based on the new codepath.
6938                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6939                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6940            }
6941
6942            // Set native library paths again. For moves, the path will be updated based on the
6943            // ABIs we've determined above. For non-moves, the path will be updated based on the
6944            // ABIs we determined during compilation, but the path will depend on the final
6945            // package path (after the rename away from the stage path).
6946            setNativeLibraryPaths(pkg);
6947        }
6948
6949        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6950        final int[] userIds = sUserManager.getUserIds();
6951        synchronized (mInstallLock) {
6952            // Make sure all user data directories are ready to roll; we're okay
6953            // if they already exist
6954            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6955                for (int userId : userIds) {
6956                    if (userId != 0) {
6957                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6958                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6959                                pkg.applicationInfo.seinfo);
6960                    }
6961                }
6962            }
6963
6964            // Create a native library symlink only if we have native libraries
6965            // and if the native libraries are 32 bit libraries. We do not provide
6966            // this symlink for 64 bit libraries.
6967            if (pkg.applicationInfo.primaryCpuAbi != null &&
6968                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6969                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6970                for (int userId : userIds) {
6971                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6972                            nativeLibPath, userId) < 0) {
6973                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6974                                "Failed linking native library dir (user=" + userId + ")");
6975                    }
6976                }
6977            }
6978        }
6979
6980        // This is a special case for the "system" package, where the ABI is
6981        // dictated by the zygote configuration (and init.rc). We should keep track
6982        // of this ABI so that we can deal with "normal" applications that run under
6983        // the same UID correctly.
6984        if (mPlatformPackage == pkg) {
6985            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6986                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6987        }
6988
6989        // If there's a mismatch between the abi-override in the package setting
6990        // and the abiOverride specified for the install. Warn about this because we
6991        // would've already compiled the app without taking the package setting into
6992        // account.
6993        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6994            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6995                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6996                        " for package: " + pkg.packageName);
6997            }
6998        }
6999
7000        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7001        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7002        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7003
7004        // Copy the derived override back to the parsed package, so that we can
7005        // update the package settings accordingly.
7006        pkg.cpuAbiOverride = cpuAbiOverride;
7007
7008        if (DEBUG_ABI_SELECTION) {
7009            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7010                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7011                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7012        }
7013
7014        // Push the derived path down into PackageSettings so we know what to
7015        // clean up at uninstall time.
7016        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7017
7018        if (DEBUG_ABI_SELECTION) {
7019            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7020                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7021                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7022        }
7023
7024        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7025            // We don't do this here during boot because we can do it all
7026            // at once after scanning all existing packages.
7027            //
7028            // We also do this *before* we perform dexopt on this package, so that
7029            // we can avoid redundant dexopts, and also to make sure we've got the
7030            // code and package path correct.
7031            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7032                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7033        }
7034
7035        if ((scanFlags & SCAN_NO_DEX) == 0) {
7036            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7037                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7038            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7039                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7040            }
7041        }
7042        if (mFactoryTest && pkg.requestedPermissions.contains(
7043                android.Manifest.permission.FACTORY_TEST)) {
7044            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7045        }
7046
7047        ArrayList<PackageParser.Package> clientLibPkgs = null;
7048
7049        // writer
7050        synchronized (mPackages) {
7051            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7052                // Only system apps can add new shared libraries.
7053                if (pkg.libraryNames != null) {
7054                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7055                        String name = pkg.libraryNames.get(i);
7056                        boolean allowed = false;
7057                        if (pkg.isUpdatedSystemApp()) {
7058                            // New library entries can only be added through the
7059                            // system image.  This is important to get rid of a lot
7060                            // of nasty edge cases: for example if we allowed a non-
7061                            // system update of the app to add a library, then uninstalling
7062                            // the update would make the library go away, and assumptions
7063                            // we made such as through app install filtering would now
7064                            // have allowed apps on the device which aren't compatible
7065                            // with it.  Better to just have the restriction here, be
7066                            // conservative, and create many fewer cases that can negatively
7067                            // impact the user experience.
7068                            final PackageSetting sysPs = mSettings
7069                                    .getDisabledSystemPkgLPr(pkg.packageName);
7070                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7071                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7072                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7073                                        allowed = true;
7074                                        allowed = true;
7075                                        break;
7076                                    }
7077                                }
7078                            }
7079                        } else {
7080                            allowed = true;
7081                        }
7082                        if (allowed) {
7083                            if (!mSharedLibraries.containsKey(name)) {
7084                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7085                            } else if (!name.equals(pkg.packageName)) {
7086                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7087                                        + name + " already exists; skipping");
7088                            }
7089                        } else {
7090                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7091                                    + name + " that is not declared on system image; skipping");
7092                        }
7093                    }
7094                    if ((scanFlags&SCAN_BOOTING) == 0) {
7095                        // If we are not booting, we need to update any applications
7096                        // that are clients of our shared library.  If we are booting,
7097                        // this will all be done once the scan is complete.
7098                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7099                    }
7100                }
7101            }
7102        }
7103
7104        // We also need to dexopt any apps that are dependent on this library.  Note that
7105        // if these fail, we should abort the install since installing the library will
7106        // result in some apps being broken.
7107        if (clientLibPkgs != null) {
7108            if ((scanFlags & SCAN_NO_DEX) == 0) {
7109                for (int i = 0; i < clientLibPkgs.size(); i++) {
7110                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7111                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7112                            null /* instruction sets */, forceDex,
7113                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7114                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7115                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7116                                "scanPackageLI failed to dexopt clientLibPkgs");
7117                    }
7118                }
7119            }
7120        }
7121
7122        // Request the ActivityManager to kill the process(only for existing packages)
7123        // so that we do not end up in a confused state while the user is still using the older
7124        // version of the application while the new one gets installed.
7125        if ((scanFlags & SCAN_REPLACING) != 0) {
7126            killApplication(pkg.applicationInfo.packageName,
7127                        pkg.applicationInfo.uid, "replace pkg");
7128        }
7129
7130        // Also need to kill any apps that are dependent on the library.
7131        if (clientLibPkgs != null) {
7132            for (int i=0; i<clientLibPkgs.size(); i++) {
7133                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7134                killApplication(clientPkg.applicationInfo.packageName,
7135                        clientPkg.applicationInfo.uid, "update lib");
7136            }
7137        }
7138
7139        // Make sure we're not adding any bogus keyset info
7140        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7141        ksms.assertScannedPackageValid(pkg);
7142
7143        // writer
7144        synchronized (mPackages) {
7145            // We don't expect installation to fail beyond this point
7146
7147            // Add the new setting to mSettings
7148            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7149            // Add the new setting to mPackages
7150            mPackages.put(pkg.applicationInfo.packageName, pkg);
7151            // Make sure we don't accidentally delete its data.
7152            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7153            while (iter.hasNext()) {
7154                PackageCleanItem item = iter.next();
7155                if (pkgName.equals(item.packageName)) {
7156                    iter.remove();
7157                }
7158            }
7159
7160            // Take care of first install / last update times.
7161            if (currentTime != 0) {
7162                if (pkgSetting.firstInstallTime == 0) {
7163                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7164                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7165                    pkgSetting.lastUpdateTime = currentTime;
7166                }
7167            } else if (pkgSetting.firstInstallTime == 0) {
7168                // We need *something*.  Take time time stamp of the file.
7169                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7170            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7171                if (scanFileTime != pkgSetting.timeStamp) {
7172                    // A package on the system image has changed; consider this
7173                    // to be an update.
7174                    pkgSetting.lastUpdateTime = scanFileTime;
7175                }
7176            }
7177
7178            // Add the package's KeySets to the global KeySetManagerService
7179            ksms.addScannedPackageLPw(pkg);
7180
7181            int N = pkg.providers.size();
7182            StringBuilder r = null;
7183            int i;
7184            for (i=0; i<N; i++) {
7185                PackageParser.Provider p = pkg.providers.get(i);
7186                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7187                        p.info.processName, pkg.applicationInfo.uid);
7188                mProviders.addProvider(p);
7189                p.syncable = p.info.isSyncable;
7190                if (p.info.authority != null) {
7191                    String names[] = p.info.authority.split(";");
7192                    p.info.authority = null;
7193                    for (int j = 0; j < names.length; j++) {
7194                        if (j == 1 && p.syncable) {
7195                            // We only want the first authority for a provider to possibly be
7196                            // syncable, so if we already added this provider using a different
7197                            // authority clear the syncable flag. We copy the provider before
7198                            // changing it because the mProviders object contains a reference
7199                            // to a provider that we don't want to change.
7200                            // Only do this for the second authority since the resulting provider
7201                            // object can be the same for all future authorities for this provider.
7202                            p = new PackageParser.Provider(p);
7203                            p.syncable = false;
7204                        }
7205                        if (!mProvidersByAuthority.containsKey(names[j])) {
7206                            mProvidersByAuthority.put(names[j], p);
7207                            if (p.info.authority == null) {
7208                                p.info.authority = names[j];
7209                            } else {
7210                                p.info.authority = p.info.authority + ";" + names[j];
7211                            }
7212                            if (DEBUG_PACKAGE_SCANNING) {
7213                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7214                                    Log.d(TAG, "Registered content provider: " + names[j]
7215                                            + ", className = " + p.info.name + ", isSyncable = "
7216                                            + p.info.isSyncable);
7217                            }
7218                        } else {
7219                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7220                            Slog.w(TAG, "Skipping provider name " + names[j] +
7221                                    " (in package " + pkg.applicationInfo.packageName +
7222                                    "): name already used by "
7223                                    + ((other != null && other.getComponentName() != null)
7224                                            ? other.getComponentName().getPackageName() : "?"));
7225                        }
7226                    }
7227                }
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(p.info.name);
7235                }
7236            }
7237            if (r != null) {
7238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7239            }
7240
7241            N = pkg.services.size();
7242            r = null;
7243            for (i=0; i<N; i++) {
7244                PackageParser.Service s = pkg.services.get(i);
7245                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7246                        s.info.processName, pkg.applicationInfo.uid);
7247                mServices.addService(s);
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(s.info.name);
7255                }
7256            }
7257            if (r != null) {
7258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7259            }
7260
7261            N = pkg.receivers.size();
7262            r = null;
7263            for (i=0; i<N; i++) {
7264                PackageParser.Activity a = pkg.receivers.get(i);
7265                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7266                        a.info.processName, pkg.applicationInfo.uid);
7267                mReceivers.addActivity(a, "receiver");
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(a.info.name);
7275                }
7276            }
7277            if (r != null) {
7278                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7279            }
7280
7281            N = pkg.activities.size();
7282            r = null;
7283            for (i=0; i<N; i++) {
7284                PackageParser.Activity a = pkg.activities.get(i);
7285                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7286                        a.info.processName, pkg.applicationInfo.uid);
7287                mActivities.addActivity(a, "activity");
7288                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7289                    if (r == null) {
7290                        r = new StringBuilder(256);
7291                    } else {
7292                        r.append(' ');
7293                    }
7294                    r.append(a.info.name);
7295                }
7296            }
7297            if (r != null) {
7298                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7299            }
7300
7301            N = pkg.permissionGroups.size();
7302            r = null;
7303            for (i=0; i<N; i++) {
7304                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7305                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7306                if (cur == null) {
7307                    mPermissionGroups.put(pg.info.name, pg);
7308                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7309                        if (r == null) {
7310                            r = new StringBuilder(256);
7311                        } else {
7312                            r.append(' ');
7313                        }
7314                        r.append(pg.info.name);
7315                    }
7316                } else {
7317                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7318                            + pg.info.packageName + " ignored: original from "
7319                            + cur.info.packageName);
7320                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7321                        if (r == null) {
7322                            r = new StringBuilder(256);
7323                        } else {
7324                            r.append(' ');
7325                        }
7326                        r.append("DUP:");
7327                        r.append(pg.info.name);
7328                    }
7329                }
7330            }
7331            if (r != null) {
7332                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7333            }
7334
7335            N = pkg.permissions.size();
7336            r = null;
7337            for (i=0; i<N; i++) {
7338                PackageParser.Permission p = pkg.permissions.get(i);
7339
7340                // Assume by default that we did not install this permission into the system.
7341                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7342
7343                // Now that permission groups have a special meaning, we ignore permission
7344                // groups for legacy apps to prevent unexpected behavior. In particular,
7345                // permissions for one app being granted to someone just becuase they happen
7346                // to be in a group defined by another app (before this had no implications).
7347                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7348                    p.group = mPermissionGroups.get(p.info.group);
7349                    // Warn for a permission in an unknown group.
7350                    if (p.info.group != null && p.group == null) {
7351                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7352                                + p.info.packageName + " in an unknown group " + p.info.group);
7353                    }
7354                }
7355
7356                ArrayMap<String, BasePermission> permissionMap =
7357                        p.tree ? mSettings.mPermissionTrees
7358                                : mSettings.mPermissions;
7359                BasePermission bp = permissionMap.get(p.info.name);
7360
7361                // Allow system apps to redefine non-system permissions
7362                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7363                    final boolean currentOwnerIsSystem = (bp.perm != null
7364                            && isSystemApp(bp.perm.owner));
7365                    if (isSystemApp(p.owner)) {
7366                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7367                            // It's a built-in permission and no owner, take ownership now
7368                            bp.packageSetting = pkgSetting;
7369                            bp.perm = p;
7370                            bp.uid = pkg.applicationInfo.uid;
7371                            bp.sourcePackage = p.info.packageName;
7372                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7373                        } else if (!currentOwnerIsSystem) {
7374                            String msg = "New decl " + p.owner + " of permission  "
7375                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7376                            reportSettingsProblem(Log.WARN, msg);
7377                            bp = null;
7378                        }
7379                    }
7380                }
7381
7382                if (bp == null) {
7383                    bp = new BasePermission(p.info.name, p.info.packageName,
7384                            BasePermission.TYPE_NORMAL);
7385                    permissionMap.put(p.info.name, bp);
7386                }
7387
7388                if (bp.perm == null) {
7389                    if (bp.sourcePackage == null
7390                            || bp.sourcePackage.equals(p.info.packageName)) {
7391                        BasePermission tree = findPermissionTreeLP(p.info.name);
7392                        if (tree == null
7393                                || tree.sourcePackage.equals(p.info.packageName)) {
7394                            bp.packageSetting = pkgSetting;
7395                            bp.perm = p;
7396                            bp.uid = pkg.applicationInfo.uid;
7397                            bp.sourcePackage = p.info.packageName;
7398                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7399                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7400                                if (r == null) {
7401                                    r = new StringBuilder(256);
7402                                } else {
7403                                    r.append(' ');
7404                                }
7405                                r.append(p.info.name);
7406                            }
7407                        } else {
7408                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7409                                    + p.info.packageName + " ignored: base tree "
7410                                    + tree.name + " is from package "
7411                                    + tree.sourcePackage);
7412                        }
7413                    } else {
7414                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7415                                + p.info.packageName + " ignored: original from "
7416                                + bp.sourcePackage);
7417                    }
7418                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7419                    if (r == null) {
7420                        r = new StringBuilder(256);
7421                    } else {
7422                        r.append(' ');
7423                    }
7424                    r.append("DUP:");
7425                    r.append(p.info.name);
7426                }
7427                if (bp.perm == p) {
7428                    bp.protectionLevel = p.info.protectionLevel;
7429                }
7430            }
7431
7432            if (r != null) {
7433                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7434            }
7435
7436            N = pkg.instrumentation.size();
7437            r = null;
7438            for (i=0; i<N; i++) {
7439                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7440                a.info.packageName = pkg.applicationInfo.packageName;
7441                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7442                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7443                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7444                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7445                a.info.dataDir = pkg.applicationInfo.dataDir;
7446
7447                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7448                // need other information about the application, like the ABI and what not ?
7449                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7450                mInstrumentation.put(a.getComponentName(), a);
7451                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7452                    if (r == null) {
7453                        r = new StringBuilder(256);
7454                    } else {
7455                        r.append(' ');
7456                    }
7457                    r.append(a.info.name);
7458                }
7459            }
7460            if (r != null) {
7461                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7462            }
7463
7464            if (pkg.protectedBroadcasts != null) {
7465                N = pkg.protectedBroadcasts.size();
7466                for (i=0; i<N; i++) {
7467                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7468                }
7469            }
7470
7471            pkgSetting.setTimeStamp(scanFileTime);
7472
7473            // Create idmap files for pairs of (packages, overlay packages).
7474            // Note: "android", ie framework-res.apk, is handled by native layers.
7475            if (pkg.mOverlayTarget != null) {
7476                // This is an overlay package.
7477                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7478                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7479                        mOverlays.put(pkg.mOverlayTarget,
7480                                new ArrayMap<String, PackageParser.Package>());
7481                    }
7482                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7483                    map.put(pkg.packageName, pkg);
7484                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7485                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7486                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7487                                "scanPackageLI failed to createIdmap");
7488                    }
7489                }
7490            } else if (mOverlays.containsKey(pkg.packageName) &&
7491                    !pkg.packageName.equals("android")) {
7492                // This is a regular package, with one or more known overlay packages.
7493                createIdmapsForPackageLI(pkg);
7494            }
7495        }
7496
7497        return pkg;
7498    }
7499
7500    /**
7501     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7502     * is derived purely on the basis of the contents of {@code scanFile} and
7503     * {@code cpuAbiOverride}.
7504     *
7505     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7506     */
7507    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7508                                 String cpuAbiOverride, boolean extractLibs)
7509            throws PackageManagerException {
7510        // TODO: We can probably be smarter about this stuff. For installed apps,
7511        // we can calculate this information at install time once and for all. For
7512        // system apps, we can probably assume that this information doesn't change
7513        // after the first boot scan. As things stand, we do lots of unnecessary work.
7514
7515        // Give ourselves some initial paths; we'll come back for another
7516        // pass once we've determined ABI below.
7517        setNativeLibraryPaths(pkg);
7518
7519        // We would never need to extract libs for forward-locked and external packages,
7520        // since the container service will do it for us. We shouldn't attempt to
7521        // extract libs from system app when it was not updated.
7522        if (pkg.isForwardLocked() || isExternal(pkg) ||
7523            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7524            extractLibs = false;
7525        }
7526
7527        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7528        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7529
7530        NativeLibraryHelper.Handle handle = null;
7531        try {
7532            handle = NativeLibraryHelper.Handle.create(scanFile);
7533            // TODO(multiArch): This can be null for apps that didn't go through the
7534            // usual installation process. We can calculate it again, like we
7535            // do during install time.
7536            //
7537            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7538            // unnecessary.
7539            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7540
7541            // Null out the abis so that they can be recalculated.
7542            pkg.applicationInfo.primaryCpuAbi = null;
7543            pkg.applicationInfo.secondaryCpuAbi = null;
7544            if (isMultiArch(pkg.applicationInfo)) {
7545                // Warn if we've set an abiOverride for multi-lib packages..
7546                // By definition, we need to copy both 32 and 64 bit libraries for
7547                // such packages.
7548                if (pkg.cpuAbiOverride != null
7549                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7550                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7551                }
7552
7553                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7554                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7555                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7556                    if (extractLibs) {
7557                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7558                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7559                                useIsaSpecificSubdirs);
7560                    } else {
7561                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7562                    }
7563                }
7564
7565                maybeThrowExceptionForMultiArchCopy(
7566                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7567
7568                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7569                    if (extractLibs) {
7570                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7571                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7572                                useIsaSpecificSubdirs);
7573                    } else {
7574                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7575                    }
7576                }
7577
7578                maybeThrowExceptionForMultiArchCopy(
7579                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7580
7581                if (abi64 >= 0) {
7582                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7583                }
7584
7585                if (abi32 >= 0) {
7586                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7587                    if (abi64 >= 0) {
7588                        pkg.applicationInfo.secondaryCpuAbi = abi;
7589                    } else {
7590                        pkg.applicationInfo.primaryCpuAbi = abi;
7591                    }
7592                }
7593            } else {
7594                String[] abiList = (cpuAbiOverride != null) ?
7595                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7596
7597                // Enable gross and lame hacks for apps that are built with old
7598                // SDK tools. We must scan their APKs for renderscript bitcode and
7599                // not launch them if it's present. Don't bother checking on devices
7600                // that don't have 64 bit support.
7601                boolean needsRenderScriptOverride = false;
7602                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7603                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7604                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7605                    needsRenderScriptOverride = true;
7606                }
7607
7608                final int copyRet;
7609                if (extractLibs) {
7610                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7611                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7612                } else {
7613                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7614                }
7615
7616                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7617                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7618                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7619                }
7620
7621                if (copyRet >= 0) {
7622                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7623                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7624                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7625                } else if (needsRenderScriptOverride) {
7626                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7627                }
7628            }
7629        } catch (IOException ioe) {
7630            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7631        } finally {
7632            IoUtils.closeQuietly(handle);
7633        }
7634
7635        // Now that we've calculated the ABIs and determined if it's an internal app,
7636        // we will go ahead and populate the nativeLibraryPath.
7637        setNativeLibraryPaths(pkg);
7638    }
7639
7640    /**
7641     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7642     * i.e, so that all packages can be run inside a single process if required.
7643     *
7644     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7645     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7646     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7647     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7648     * updating a package that belongs to a shared user.
7649     *
7650     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7651     * adds unnecessary complexity.
7652     */
7653    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7654            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7655        String requiredInstructionSet = null;
7656        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7657            requiredInstructionSet = VMRuntime.getInstructionSet(
7658                     scannedPackage.applicationInfo.primaryCpuAbi);
7659        }
7660
7661        PackageSetting requirer = null;
7662        for (PackageSetting ps : packagesForUser) {
7663            // If packagesForUser contains scannedPackage, we skip it. This will happen
7664            // when scannedPackage is an update of an existing package. Without this check,
7665            // we will never be able to change the ABI of any package belonging to a shared
7666            // user, even if it's compatible with other packages.
7667            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7668                if (ps.primaryCpuAbiString == null) {
7669                    continue;
7670                }
7671
7672                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7673                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7674                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7675                    // this but there's not much we can do.
7676                    String errorMessage = "Instruction set mismatch, "
7677                            + ((requirer == null) ? "[caller]" : requirer)
7678                            + " requires " + requiredInstructionSet + " whereas " + ps
7679                            + " requires " + instructionSet;
7680                    Slog.w(TAG, errorMessage);
7681                }
7682
7683                if (requiredInstructionSet == null) {
7684                    requiredInstructionSet = instructionSet;
7685                    requirer = ps;
7686                }
7687            }
7688        }
7689
7690        if (requiredInstructionSet != null) {
7691            String adjustedAbi;
7692            if (requirer != null) {
7693                // requirer != null implies that either scannedPackage was null or that scannedPackage
7694                // did not require an ABI, in which case we have to adjust scannedPackage to match
7695                // the ABI of the set (which is the same as requirer's ABI)
7696                adjustedAbi = requirer.primaryCpuAbiString;
7697                if (scannedPackage != null) {
7698                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7699                }
7700            } else {
7701                // requirer == null implies that we're updating all ABIs in the set to
7702                // match scannedPackage.
7703                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7704            }
7705
7706            for (PackageSetting ps : packagesForUser) {
7707                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7708                    if (ps.primaryCpuAbiString != null) {
7709                        continue;
7710                    }
7711
7712                    ps.primaryCpuAbiString = adjustedAbi;
7713                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7714                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7715                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7716
7717                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7718                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7719                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7720                            ps.primaryCpuAbiString = null;
7721                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7722                            return;
7723                        } else {
7724                            mInstaller.rmdex(ps.codePathString,
7725                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7726                        }
7727                    }
7728                }
7729            }
7730        }
7731    }
7732
7733    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7734        synchronized (mPackages) {
7735            mResolverReplaced = true;
7736            // Set up information for custom user intent resolution activity.
7737            mResolveActivity.applicationInfo = pkg.applicationInfo;
7738            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7739            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7740            mResolveActivity.processName = pkg.applicationInfo.packageName;
7741            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7742            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7743                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7744            mResolveActivity.theme = 0;
7745            mResolveActivity.exported = true;
7746            mResolveActivity.enabled = true;
7747            mResolveInfo.activityInfo = mResolveActivity;
7748            mResolveInfo.priority = 0;
7749            mResolveInfo.preferredOrder = 0;
7750            mResolveInfo.match = 0;
7751            mResolveComponentName = mCustomResolverComponentName;
7752            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7753                    mResolveComponentName);
7754        }
7755    }
7756
7757    private static String calculateBundledApkRoot(final String codePathString) {
7758        final File codePath = new File(codePathString);
7759        final File codeRoot;
7760        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7761            codeRoot = Environment.getRootDirectory();
7762        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7763            codeRoot = Environment.getOemDirectory();
7764        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7765            codeRoot = Environment.getVendorDirectory();
7766        } else {
7767            // Unrecognized code path; take its top real segment as the apk root:
7768            // e.g. /something/app/blah.apk => /something
7769            try {
7770                File f = codePath.getCanonicalFile();
7771                File parent = f.getParentFile();    // non-null because codePath is a file
7772                File tmp;
7773                while ((tmp = parent.getParentFile()) != null) {
7774                    f = parent;
7775                    parent = tmp;
7776                }
7777                codeRoot = f;
7778                Slog.w(TAG, "Unrecognized code path "
7779                        + codePath + " - using " + codeRoot);
7780            } catch (IOException e) {
7781                // Can't canonicalize the code path -- shenanigans?
7782                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7783                return Environment.getRootDirectory().getPath();
7784            }
7785        }
7786        return codeRoot.getPath();
7787    }
7788
7789    /**
7790     * Derive and set the location of native libraries for the given package,
7791     * which varies depending on where and how the package was installed.
7792     */
7793    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7794        final ApplicationInfo info = pkg.applicationInfo;
7795        final String codePath = pkg.codePath;
7796        final File codeFile = new File(codePath);
7797        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7798        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7799
7800        info.nativeLibraryRootDir = null;
7801        info.nativeLibraryRootRequiresIsa = false;
7802        info.nativeLibraryDir = null;
7803        info.secondaryNativeLibraryDir = null;
7804
7805        if (isApkFile(codeFile)) {
7806            // Monolithic install
7807            if (bundledApp) {
7808                // If "/system/lib64/apkname" exists, assume that is the per-package
7809                // native library directory to use; otherwise use "/system/lib/apkname".
7810                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7811                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7812                        getPrimaryInstructionSet(info));
7813
7814                // This is a bundled system app so choose the path based on the ABI.
7815                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7816                // is just the default path.
7817                final String apkName = deriveCodePathName(codePath);
7818                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7819                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7820                        apkName).getAbsolutePath();
7821
7822                if (info.secondaryCpuAbi != null) {
7823                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7824                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7825                            secondaryLibDir, apkName).getAbsolutePath();
7826                }
7827            } else if (asecApp) {
7828                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7829                        .getAbsolutePath();
7830            } else {
7831                final String apkName = deriveCodePathName(codePath);
7832                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7833                        .getAbsolutePath();
7834            }
7835
7836            info.nativeLibraryRootRequiresIsa = false;
7837            info.nativeLibraryDir = info.nativeLibraryRootDir;
7838        } else {
7839            // Cluster install
7840            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7841            info.nativeLibraryRootRequiresIsa = true;
7842
7843            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7844                    getPrimaryInstructionSet(info)).getAbsolutePath();
7845
7846            if (info.secondaryCpuAbi != null) {
7847                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7848                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7849            }
7850        }
7851    }
7852
7853    /**
7854     * Calculate the abis and roots for a bundled app. These can uniquely
7855     * be determined from the contents of the system partition, i.e whether
7856     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7857     * of this information, and instead assume that the system was built
7858     * sensibly.
7859     */
7860    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7861                                           PackageSetting pkgSetting) {
7862        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7863
7864        // If "/system/lib64/apkname" exists, assume that is the per-package
7865        // native library directory to use; otherwise use "/system/lib/apkname".
7866        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7867        setBundledAppAbi(pkg, apkRoot, apkName);
7868        // pkgSetting might be null during rescan following uninstall of updates
7869        // to a bundled app, so accommodate that possibility.  The settings in
7870        // that case will be established later from the parsed package.
7871        //
7872        // If the settings aren't null, sync them up with what we've just derived.
7873        // note that apkRoot isn't stored in the package settings.
7874        if (pkgSetting != null) {
7875            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7876            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7877        }
7878    }
7879
7880    /**
7881     * Deduces the ABI of a bundled app and sets the relevant fields on the
7882     * parsed pkg object.
7883     *
7884     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7885     *        under which system libraries are installed.
7886     * @param apkName the name of the installed package.
7887     */
7888    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7889        final File codeFile = new File(pkg.codePath);
7890
7891        final boolean has64BitLibs;
7892        final boolean has32BitLibs;
7893        if (isApkFile(codeFile)) {
7894            // Monolithic install
7895            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7896            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7897        } else {
7898            // Cluster install
7899            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7900            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7901                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7902                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7903                has64BitLibs = (new File(rootDir, isa)).exists();
7904            } else {
7905                has64BitLibs = false;
7906            }
7907            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7908                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7909                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7910                has32BitLibs = (new File(rootDir, isa)).exists();
7911            } else {
7912                has32BitLibs = false;
7913            }
7914        }
7915
7916        if (has64BitLibs && !has32BitLibs) {
7917            // The package has 64 bit libs, but not 32 bit libs. Its primary
7918            // ABI should be 64 bit. We can safely assume here that the bundled
7919            // native libraries correspond to the most preferred ABI in the list.
7920
7921            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7922            pkg.applicationInfo.secondaryCpuAbi = null;
7923        } else if (has32BitLibs && !has64BitLibs) {
7924            // The package has 32 bit libs but not 64 bit libs. Its primary
7925            // ABI should be 32 bit.
7926
7927            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7928            pkg.applicationInfo.secondaryCpuAbi = null;
7929        } else if (has32BitLibs && has64BitLibs) {
7930            // The application has both 64 and 32 bit bundled libraries. We check
7931            // here that the app declares multiArch support, and warn if it doesn't.
7932            //
7933            // We will be lenient here and record both ABIs. The primary will be the
7934            // ABI that's higher on the list, i.e, a device that's configured to prefer
7935            // 64 bit apps will see a 64 bit primary ABI,
7936
7937            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7938                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7939            }
7940
7941            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7942                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7943                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7944            } else {
7945                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7946                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7947            }
7948        } else {
7949            pkg.applicationInfo.primaryCpuAbi = null;
7950            pkg.applicationInfo.secondaryCpuAbi = null;
7951        }
7952    }
7953
7954    private void killApplication(String pkgName, int appId, String reason) {
7955        // Request the ActivityManager to kill the process(only for existing packages)
7956        // so that we do not end up in a confused state while the user is still using the older
7957        // version of the application while the new one gets installed.
7958        IActivityManager am = ActivityManagerNative.getDefault();
7959        if (am != null) {
7960            try {
7961                am.killApplicationWithAppId(pkgName, appId, reason);
7962            } catch (RemoteException e) {
7963            }
7964        }
7965    }
7966
7967    void removePackageLI(PackageSetting ps, boolean chatty) {
7968        if (DEBUG_INSTALL) {
7969            if (chatty)
7970                Log.d(TAG, "Removing package " + ps.name);
7971        }
7972
7973        // writer
7974        synchronized (mPackages) {
7975            mPackages.remove(ps.name);
7976            final PackageParser.Package pkg = ps.pkg;
7977            if (pkg != null) {
7978                cleanPackageDataStructuresLILPw(pkg, chatty);
7979            }
7980        }
7981    }
7982
7983    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7984        if (DEBUG_INSTALL) {
7985            if (chatty)
7986                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7987        }
7988
7989        // writer
7990        synchronized (mPackages) {
7991            mPackages.remove(pkg.applicationInfo.packageName);
7992            cleanPackageDataStructuresLILPw(pkg, chatty);
7993        }
7994    }
7995
7996    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7997        int N = pkg.providers.size();
7998        StringBuilder r = null;
7999        int i;
8000        for (i=0; i<N; i++) {
8001            PackageParser.Provider p = pkg.providers.get(i);
8002            mProviders.removeProvider(p);
8003            if (p.info.authority == null) {
8004
8005                /* There was another ContentProvider with this authority when
8006                 * this app was installed so this authority is null,
8007                 * Ignore it as we don't have to unregister the provider.
8008                 */
8009                continue;
8010            }
8011            String names[] = p.info.authority.split(";");
8012            for (int j = 0; j < names.length; j++) {
8013                if (mProvidersByAuthority.get(names[j]) == p) {
8014                    mProvidersByAuthority.remove(names[j]);
8015                    if (DEBUG_REMOVE) {
8016                        if (chatty)
8017                            Log.d(TAG, "Unregistered content provider: " + names[j]
8018                                    + ", className = " + p.info.name + ", isSyncable = "
8019                                    + p.info.isSyncable);
8020                    }
8021                }
8022            }
8023            if (DEBUG_REMOVE && chatty) {
8024                if (r == null) {
8025                    r = new StringBuilder(256);
8026                } else {
8027                    r.append(' ');
8028                }
8029                r.append(p.info.name);
8030            }
8031        }
8032        if (r != null) {
8033            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8034        }
8035
8036        N = pkg.services.size();
8037        r = null;
8038        for (i=0; i<N; i++) {
8039            PackageParser.Service s = pkg.services.get(i);
8040            mServices.removeService(s);
8041            if (chatty) {
8042                if (r == null) {
8043                    r = new StringBuilder(256);
8044                } else {
8045                    r.append(' ');
8046                }
8047                r.append(s.info.name);
8048            }
8049        }
8050        if (r != null) {
8051            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8052        }
8053
8054        N = pkg.receivers.size();
8055        r = null;
8056        for (i=0; i<N; i++) {
8057            PackageParser.Activity a = pkg.receivers.get(i);
8058            mReceivers.removeActivity(a, "receiver");
8059            if (DEBUG_REMOVE && chatty) {
8060                if (r == null) {
8061                    r = new StringBuilder(256);
8062                } else {
8063                    r.append(' ');
8064                }
8065                r.append(a.info.name);
8066            }
8067        }
8068        if (r != null) {
8069            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8070        }
8071
8072        N = pkg.activities.size();
8073        r = null;
8074        for (i=0; i<N; i++) {
8075            PackageParser.Activity a = pkg.activities.get(i);
8076            mActivities.removeActivity(a, "activity");
8077            if (DEBUG_REMOVE && chatty) {
8078                if (r == null) {
8079                    r = new StringBuilder(256);
8080                } else {
8081                    r.append(' ');
8082                }
8083                r.append(a.info.name);
8084            }
8085        }
8086        if (r != null) {
8087            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8088        }
8089
8090        N = pkg.permissions.size();
8091        r = null;
8092        for (i=0; i<N; i++) {
8093            PackageParser.Permission p = pkg.permissions.get(i);
8094            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8095            if (bp == null) {
8096                bp = mSettings.mPermissionTrees.get(p.info.name);
8097            }
8098            if (bp != null && bp.perm == p) {
8099                bp.perm = null;
8100                if (DEBUG_REMOVE && chatty) {
8101                    if (r == null) {
8102                        r = new StringBuilder(256);
8103                    } else {
8104                        r.append(' ');
8105                    }
8106                    r.append(p.info.name);
8107                }
8108            }
8109            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8110                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8111                if (appOpPerms != null) {
8112                    appOpPerms.remove(pkg.packageName);
8113                }
8114            }
8115        }
8116        if (r != null) {
8117            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8118        }
8119
8120        N = pkg.requestedPermissions.size();
8121        r = null;
8122        for (i=0; i<N; i++) {
8123            String perm = pkg.requestedPermissions.get(i);
8124            BasePermission bp = mSettings.mPermissions.get(perm);
8125            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8126                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8127                if (appOpPerms != null) {
8128                    appOpPerms.remove(pkg.packageName);
8129                    if (appOpPerms.isEmpty()) {
8130                        mAppOpPermissionPackages.remove(perm);
8131                    }
8132                }
8133            }
8134        }
8135        if (r != null) {
8136            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8137        }
8138
8139        N = pkg.instrumentation.size();
8140        r = null;
8141        for (i=0; i<N; i++) {
8142            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8143            mInstrumentation.remove(a.getComponentName());
8144            if (DEBUG_REMOVE && chatty) {
8145                if (r == null) {
8146                    r = new StringBuilder(256);
8147                } else {
8148                    r.append(' ');
8149                }
8150                r.append(a.info.name);
8151            }
8152        }
8153        if (r != null) {
8154            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8155        }
8156
8157        r = null;
8158        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8159            // Only system apps can hold shared libraries.
8160            if (pkg.libraryNames != null) {
8161                for (i=0; i<pkg.libraryNames.size(); i++) {
8162                    String name = pkg.libraryNames.get(i);
8163                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8164                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8165                        mSharedLibraries.remove(name);
8166                        if (DEBUG_REMOVE && chatty) {
8167                            if (r == null) {
8168                                r = new StringBuilder(256);
8169                            } else {
8170                                r.append(' ');
8171                            }
8172                            r.append(name);
8173                        }
8174                    }
8175                }
8176            }
8177        }
8178        if (r != null) {
8179            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8180        }
8181    }
8182
8183    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8184        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8185            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8186                return true;
8187            }
8188        }
8189        return false;
8190    }
8191
8192    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8193    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8194    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8195
8196    private void updatePermissionsLPw(String changingPkg,
8197            PackageParser.Package pkgInfo, int flags) {
8198        // Make sure there are no dangling permission trees.
8199        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8200        while (it.hasNext()) {
8201            final BasePermission bp = it.next();
8202            if (bp.packageSetting == null) {
8203                // We may not yet have parsed the package, so just see if
8204                // we still know about its settings.
8205                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8206            }
8207            if (bp.packageSetting == null) {
8208                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8209                        + " from package " + bp.sourcePackage);
8210                it.remove();
8211            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8212                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8213                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8214                            + " from package " + bp.sourcePackage);
8215                    flags |= UPDATE_PERMISSIONS_ALL;
8216                    it.remove();
8217                }
8218            }
8219        }
8220
8221        // Make sure all dynamic permissions have been assigned to a package,
8222        // and make sure there are no dangling permissions.
8223        it = mSettings.mPermissions.values().iterator();
8224        while (it.hasNext()) {
8225            final BasePermission bp = it.next();
8226            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8227                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8228                        + bp.name + " pkg=" + bp.sourcePackage
8229                        + " info=" + bp.pendingInfo);
8230                if (bp.packageSetting == null && bp.pendingInfo != null) {
8231                    final BasePermission tree = findPermissionTreeLP(bp.name);
8232                    if (tree != null && tree.perm != null) {
8233                        bp.packageSetting = tree.packageSetting;
8234                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8235                                new PermissionInfo(bp.pendingInfo));
8236                        bp.perm.info.packageName = tree.perm.info.packageName;
8237                        bp.perm.info.name = bp.name;
8238                        bp.uid = tree.uid;
8239                    }
8240                }
8241            }
8242            if (bp.packageSetting == null) {
8243                // We may not yet have parsed the package, so just see if
8244                // we still know about its settings.
8245                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8246            }
8247            if (bp.packageSetting == null) {
8248                Slog.w(TAG, "Removing dangling permission: " + bp.name
8249                        + " from package " + bp.sourcePackage);
8250                it.remove();
8251            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8252                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8253                    Slog.i(TAG, "Removing old permission: " + bp.name
8254                            + " from package " + bp.sourcePackage);
8255                    flags |= UPDATE_PERMISSIONS_ALL;
8256                    it.remove();
8257                }
8258            }
8259        }
8260
8261        // Now update the permissions for all packages, in particular
8262        // replace the granted permissions of the system packages.
8263        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8264            for (PackageParser.Package pkg : mPackages.values()) {
8265                if (pkg != pkgInfo) {
8266                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8267                            changingPkg);
8268                }
8269            }
8270        }
8271
8272        if (pkgInfo != null) {
8273            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8274        }
8275    }
8276
8277    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8278            String packageOfInterest) {
8279        // IMPORTANT: There are two types of permissions: install and runtime.
8280        // Install time permissions are granted when the app is installed to
8281        // all device users and users added in the future. Runtime permissions
8282        // are granted at runtime explicitly to specific users. Normal and signature
8283        // protected permissions are install time permissions. Dangerous permissions
8284        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8285        // otherwise they are runtime permissions. This function does not manage
8286        // runtime permissions except for the case an app targeting Lollipop MR1
8287        // being upgraded to target a newer SDK, in which case dangerous permissions
8288        // are transformed from install time to runtime ones.
8289
8290        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8291        if (ps == null) {
8292            return;
8293        }
8294
8295        PermissionsState permissionsState = ps.getPermissionsState();
8296        PermissionsState origPermissions = permissionsState;
8297
8298        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8299
8300        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8301
8302        boolean changedInstallPermission = false;
8303
8304        if (replace) {
8305            ps.installPermissionsFixed = false;
8306            if (!ps.isSharedUser()) {
8307                origPermissions = new PermissionsState(permissionsState);
8308                permissionsState.reset();
8309            }
8310        }
8311
8312        permissionsState.setGlobalGids(mGlobalGids);
8313
8314        final int N = pkg.requestedPermissions.size();
8315        for (int i=0; i<N; i++) {
8316            final String name = pkg.requestedPermissions.get(i);
8317            final BasePermission bp = mSettings.mPermissions.get(name);
8318
8319            if (DEBUG_INSTALL) {
8320                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8321            }
8322
8323            if (bp == null || bp.packageSetting == null) {
8324                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8325                    Slog.w(TAG, "Unknown permission " + name
8326                            + " in package " + pkg.packageName);
8327                }
8328                continue;
8329            }
8330
8331            final String perm = bp.name;
8332            boolean allowedSig = false;
8333            int grant = GRANT_DENIED;
8334
8335            // Keep track of app op permissions.
8336            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8337                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8338                if (pkgs == null) {
8339                    pkgs = new ArraySet<>();
8340                    mAppOpPermissionPackages.put(bp.name, pkgs);
8341                }
8342                pkgs.add(pkg.packageName);
8343            }
8344
8345            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8346            switch (level) {
8347                case PermissionInfo.PROTECTION_NORMAL: {
8348                    // For all apps normal permissions are install time ones.
8349                    grant = GRANT_INSTALL;
8350                } break;
8351
8352                case PermissionInfo.PROTECTION_DANGEROUS: {
8353                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8354                        // For legacy apps dangerous permissions are install time ones.
8355                        grant = GRANT_INSTALL_LEGACY;
8356                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8357                        // For legacy apps that became modern, install becomes runtime.
8358                        grant = GRANT_UPGRADE;
8359                    } else {
8360                        // For modern apps keep runtime permissions unchanged.
8361                        grant = GRANT_RUNTIME;
8362                    }
8363                } break;
8364
8365                case PermissionInfo.PROTECTION_SIGNATURE: {
8366                    // For all apps signature permissions are install time ones.
8367                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8368                    if (allowedSig) {
8369                        grant = GRANT_INSTALL;
8370                    }
8371                } break;
8372            }
8373
8374            if (DEBUG_INSTALL) {
8375                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8376            }
8377
8378            if (grant != GRANT_DENIED) {
8379                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8380                    // If this is an existing, non-system package, then
8381                    // we can't add any new permissions to it.
8382                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8383                        // Except...  if this is a permission that was added
8384                        // to the platform (note: need to only do this when
8385                        // updating the platform).
8386                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8387                            grant = GRANT_DENIED;
8388                        }
8389                    }
8390                }
8391
8392                switch (grant) {
8393                    case GRANT_INSTALL: {
8394                        // Revoke this as runtime permission to handle the case of
8395                        // a runtime permission being downgraded to an install one.
8396                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8397                            if (origPermissions.getRuntimePermissionState(
8398                                    bp.name, userId) != null) {
8399                                // Revoke the runtime permission and clear the flags.
8400                                origPermissions.revokeRuntimePermission(bp, userId);
8401                                origPermissions.updatePermissionFlags(bp, userId,
8402                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8403                                // If we revoked a permission permission, we have to write.
8404                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8405                                        changedRuntimePermissionUserIds, userId);
8406                            }
8407                        }
8408                        // Grant an install permission.
8409                        if (permissionsState.grantInstallPermission(bp) !=
8410                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8411                            changedInstallPermission = true;
8412                        }
8413                    } break;
8414
8415                    case GRANT_INSTALL_LEGACY: {
8416                        // Grant an install permission.
8417                        if (permissionsState.grantInstallPermission(bp) !=
8418                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8419                            changedInstallPermission = true;
8420                        }
8421                    } break;
8422
8423                    case GRANT_RUNTIME: {
8424                        // Grant previously granted runtime permissions.
8425                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8426                            PermissionState permissionState = origPermissions
8427                                    .getRuntimePermissionState(bp.name, userId);
8428                            final int flags = permissionState != null
8429                                    ? permissionState.getFlags() : 0;
8430                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8431                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8432                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8433                                    // If we cannot put the permission as it was, we have to write.
8434                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8435                                            changedRuntimePermissionUserIds, userId);
8436                                }
8437                            }
8438                            // Propagate the permission flags.
8439                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8440                        }
8441                    } break;
8442
8443                    case GRANT_UPGRADE: {
8444                        // Grant runtime permissions for a previously held install permission.
8445                        PermissionState permissionState = origPermissions
8446                                .getInstallPermissionState(bp.name);
8447                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8448
8449                        if (origPermissions.revokeInstallPermission(bp)
8450                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8451                            // We will be transferring the permission flags, so clear them.
8452                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8453                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8454                            changedInstallPermission = true;
8455                        }
8456
8457                        // If the permission is not to be promoted to runtime we ignore it and
8458                        // also its other flags as they are not applicable to install permissions.
8459                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8460                            for (int userId : currentUserIds) {
8461                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8462                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8463                                    // Transfer the permission flags.
8464                                    permissionsState.updatePermissionFlags(bp, userId,
8465                                            flags, flags);
8466                                    // If we granted the permission, we have to write.
8467                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8468                                            changedRuntimePermissionUserIds, userId);
8469                                }
8470                            }
8471                        }
8472                    } break;
8473
8474                    default: {
8475                        if (packageOfInterest == null
8476                                || packageOfInterest.equals(pkg.packageName)) {
8477                            Slog.w(TAG, "Not granting permission " + perm
8478                                    + " to package " + pkg.packageName
8479                                    + " because it was previously installed without");
8480                        }
8481                    } break;
8482                }
8483            } else {
8484                if (permissionsState.revokeInstallPermission(bp) !=
8485                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8486                    // Also drop the permission flags.
8487                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8488                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8489                    changedInstallPermission = true;
8490                    Slog.i(TAG, "Un-granting permission " + perm
8491                            + " from package " + pkg.packageName
8492                            + " (protectionLevel=" + bp.protectionLevel
8493                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8494                            + ")");
8495                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8496                    // Don't print warning for app op permissions, since it is fine for them
8497                    // not to be granted, there is a UI for the user to decide.
8498                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8499                        Slog.w(TAG, "Not granting permission " + perm
8500                                + " to package " + pkg.packageName
8501                                + " (protectionLevel=" + bp.protectionLevel
8502                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8503                                + ")");
8504                    }
8505                }
8506            }
8507        }
8508
8509        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8510                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8511            // This is the first that we have heard about this package, so the
8512            // permissions we have now selected are fixed until explicitly
8513            // changed.
8514            ps.installPermissionsFixed = true;
8515        }
8516
8517        // Persist the runtime permissions state for users with changes.
8518        for (int userId : changedRuntimePermissionUserIds) {
8519            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8520        }
8521    }
8522
8523    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8524        boolean allowed = false;
8525        final int NP = PackageParser.NEW_PERMISSIONS.length;
8526        for (int ip=0; ip<NP; ip++) {
8527            final PackageParser.NewPermissionInfo npi
8528                    = PackageParser.NEW_PERMISSIONS[ip];
8529            if (npi.name.equals(perm)
8530                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8531                allowed = true;
8532                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8533                        + pkg.packageName);
8534                break;
8535            }
8536        }
8537        return allowed;
8538    }
8539
8540    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8541            BasePermission bp, PermissionsState origPermissions) {
8542        boolean allowed;
8543        allowed = (compareSignatures(
8544                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8545                        == PackageManager.SIGNATURE_MATCH)
8546                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8547                        == PackageManager.SIGNATURE_MATCH);
8548        if (!allowed && (bp.protectionLevel
8549                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8550            if (isSystemApp(pkg)) {
8551                // For updated system applications, a system permission
8552                // is granted only if it had been defined by the original application.
8553                if (pkg.isUpdatedSystemApp()) {
8554                    final PackageSetting sysPs = mSettings
8555                            .getDisabledSystemPkgLPr(pkg.packageName);
8556                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8557                        // If the original was granted this permission, we take
8558                        // that grant decision as read and propagate it to the
8559                        // update.
8560                        if (sysPs.isPrivileged()) {
8561                            allowed = true;
8562                        }
8563                    } else {
8564                        // The system apk may have been updated with an older
8565                        // version of the one on the data partition, but which
8566                        // granted a new system permission that it didn't have
8567                        // before.  In this case we do want to allow the app to
8568                        // now get the new permission if the ancestral apk is
8569                        // privileged to get it.
8570                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8571                            for (int j=0;
8572                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8573                                if (perm.equals(
8574                                        sysPs.pkg.requestedPermissions.get(j))) {
8575                                    allowed = true;
8576                                    break;
8577                                }
8578                            }
8579                        }
8580                    }
8581                } else {
8582                    allowed = isPrivilegedApp(pkg);
8583                }
8584            }
8585        }
8586        if (!allowed) {
8587            if (!allowed && (bp.protectionLevel
8588                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8589                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8590                // If this was a previously normal/dangerous permission that got moved
8591                // to a system permission as part of the runtime permission redesign, then
8592                // we still want to blindly grant it to old apps.
8593                allowed = true;
8594            }
8595            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8596                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8597                // If this permission is to be granted to the system installer and
8598                // this app is an installer, then it gets the permission.
8599                allowed = true;
8600            }
8601            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8602                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8603                // If this permission is to be granted to the system verifier and
8604                // this app is a verifier, then it gets the permission.
8605                allowed = true;
8606            }
8607            if (!allowed && (bp.protectionLevel
8608                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8609                    && isSystemApp(pkg)) {
8610                // Any pre-installed system app is allowed to get this permission.
8611                allowed = true;
8612            }
8613            if (!allowed && (bp.protectionLevel
8614                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8615                // For development permissions, a development permission
8616                // is granted only if it was already granted.
8617                allowed = origPermissions.hasInstallPermission(perm);
8618            }
8619        }
8620        return allowed;
8621    }
8622
8623    final class ActivityIntentResolver
8624            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8625        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8626                boolean defaultOnly, int userId) {
8627            if (!sUserManager.exists(userId)) return null;
8628            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8629            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8630        }
8631
8632        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8633                int userId) {
8634            if (!sUserManager.exists(userId)) return null;
8635            mFlags = flags;
8636            return super.queryIntent(intent, resolvedType,
8637                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8638        }
8639
8640        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8641                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8642            if (!sUserManager.exists(userId)) return null;
8643            if (packageActivities == null) {
8644                return null;
8645            }
8646            mFlags = flags;
8647            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8648            final int N = packageActivities.size();
8649            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8650                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8651
8652            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8653            for (int i = 0; i < N; ++i) {
8654                intentFilters = packageActivities.get(i).intents;
8655                if (intentFilters != null && intentFilters.size() > 0) {
8656                    PackageParser.ActivityIntentInfo[] array =
8657                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8658                    intentFilters.toArray(array);
8659                    listCut.add(array);
8660                }
8661            }
8662            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8663        }
8664
8665        public final void addActivity(PackageParser.Activity a, String type) {
8666            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8667            mActivities.put(a.getComponentName(), a);
8668            if (DEBUG_SHOW_INFO)
8669                Log.v(
8670                TAG, "  " + type + " " +
8671                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8672            if (DEBUG_SHOW_INFO)
8673                Log.v(TAG, "    Class=" + a.info.name);
8674            final int NI = a.intents.size();
8675            for (int j=0; j<NI; j++) {
8676                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8677                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8678                    intent.setPriority(0);
8679                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8680                            + a.className + " with priority > 0, forcing to 0");
8681                }
8682                if (DEBUG_SHOW_INFO) {
8683                    Log.v(TAG, "    IntentFilter:");
8684                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8685                }
8686                if (!intent.debugCheck()) {
8687                    Log.w(TAG, "==> For Activity " + a.info.name);
8688                }
8689                addFilter(intent);
8690            }
8691        }
8692
8693        public final void removeActivity(PackageParser.Activity a, String type) {
8694            mActivities.remove(a.getComponentName());
8695            if (DEBUG_SHOW_INFO) {
8696                Log.v(TAG, "  " + type + " "
8697                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8698                                : a.info.name) + ":");
8699                Log.v(TAG, "    Class=" + a.info.name);
8700            }
8701            final int NI = a.intents.size();
8702            for (int j=0; j<NI; j++) {
8703                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8704                if (DEBUG_SHOW_INFO) {
8705                    Log.v(TAG, "    IntentFilter:");
8706                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8707                }
8708                removeFilter(intent);
8709            }
8710        }
8711
8712        @Override
8713        protected boolean allowFilterResult(
8714                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8715            ActivityInfo filterAi = filter.activity.info;
8716            for (int i=dest.size()-1; i>=0; i--) {
8717                ActivityInfo destAi = dest.get(i).activityInfo;
8718                if (destAi.name == filterAi.name
8719                        && destAi.packageName == filterAi.packageName) {
8720                    return false;
8721                }
8722            }
8723            return true;
8724        }
8725
8726        @Override
8727        protected ActivityIntentInfo[] newArray(int size) {
8728            return new ActivityIntentInfo[size];
8729        }
8730
8731        @Override
8732        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8733            if (!sUserManager.exists(userId)) return true;
8734            PackageParser.Package p = filter.activity.owner;
8735            if (p != null) {
8736                PackageSetting ps = (PackageSetting)p.mExtras;
8737                if (ps != null) {
8738                    // System apps are never considered stopped for purposes of
8739                    // filtering, because there may be no way for the user to
8740                    // actually re-launch them.
8741                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8742                            && ps.getStopped(userId);
8743                }
8744            }
8745            return false;
8746        }
8747
8748        @Override
8749        protected boolean isPackageForFilter(String packageName,
8750                PackageParser.ActivityIntentInfo info) {
8751            return packageName.equals(info.activity.owner.packageName);
8752        }
8753
8754        @Override
8755        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8756                int match, int userId) {
8757            if (!sUserManager.exists(userId)) return null;
8758            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8759                return null;
8760            }
8761            final PackageParser.Activity activity = info.activity;
8762            if (mSafeMode && (activity.info.applicationInfo.flags
8763                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8764                return null;
8765            }
8766            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8767            if (ps == null) {
8768                return null;
8769            }
8770            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8771                    ps.readUserState(userId), userId);
8772            if (ai == null) {
8773                return null;
8774            }
8775            final ResolveInfo res = new ResolveInfo();
8776            res.activityInfo = ai;
8777            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8778                res.filter = info;
8779            }
8780            if (info != null) {
8781                res.handleAllWebDataURI = info.handleAllWebDataURI();
8782            }
8783            res.priority = info.getPriority();
8784            res.preferredOrder = activity.owner.mPreferredOrder;
8785            //System.out.println("Result: " + res.activityInfo.className +
8786            //                   " = " + res.priority);
8787            res.match = match;
8788            res.isDefault = info.hasDefault;
8789            res.labelRes = info.labelRes;
8790            res.nonLocalizedLabel = info.nonLocalizedLabel;
8791            if (userNeedsBadging(userId)) {
8792                res.noResourceId = true;
8793            } else {
8794                res.icon = info.icon;
8795            }
8796            res.iconResourceId = info.icon;
8797            res.system = res.activityInfo.applicationInfo.isSystemApp();
8798            return res;
8799        }
8800
8801        @Override
8802        protected void sortResults(List<ResolveInfo> results) {
8803            Collections.sort(results, mResolvePrioritySorter);
8804        }
8805
8806        @Override
8807        protected void dumpFilter(PrintWriter out, String prefix,
8808                PackageParser.ActivityIntentInfo filter) {
8809            out.print(prefix); out.print(
8810                    Integer.toHexString(System.identityHashCode(filter.activity)));
8811                    out.print(' ');
8812                    filter.activity.printComponentShortName(out);
8813                    out.print(" filter ");
8814                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8815        }
8816
8817        @Override
8818        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8819            return filter.activity;
8820        }
8821
8822        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8823            PackageParser.Activity activity = (PackageParser.Activity)label;
8824            out.print(prefix); out.print(
8825                    Integer.toHexString(System.identityHashCode(activity)));
8826                    out.print(' ');
8827                    activity.printComponentShortName(out);
8828            if (count > 1) {
8829                out.print(" ("); out.print(count); out.print(" filters)");
8830            }
8831            out.println();
8832        }
8833
8834//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8835//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8836//            final List<ResolveInfo> retList = Lists.newArrayList();
8837//            while (i.hasNext()) {
8838//                final ResolveInfo resolveInfo = i.next();
8839//                if (isEnabledLP(resolveInfo.activityInfo)) {
8840//                    retList.add(resolveInfo);
8841//                }
8842//            }
8843//            return retList;
8844//        }
8845
8846        // Keys are String (activity class name), values are Activity.
8847        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8848                = new ArrayMap<ComponentName, PackageParser.Activity>();
8849        private int mFlags;
8850    }
8851
8852    private final class ServiceIntentResolver
8853            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8854        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8855                boolean defaultOnly, int userId) {
8856            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8857            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8858        }
8859
8860        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8861                int userId) {
8862            if (!sUserManager.exists(userId)) return null;
8863            mFlags = flags;
8864            return super.queryIntent(intent, resolvedType,
8865                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8866        }
8867
8868        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8869                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8870            if (!sUserManager.exists(userId)) return null;
8871            if (packageServices == null) {
8872                return null;
8873            }
8874            mFlags = flags;
8875            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8876            final int N = packageServices.size();
8877            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8878                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8879
8880            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8881            for (int i = 0; i < N; ++i) {
8882                intentFilters = packageServices.get(i).intents;
8883                if (intentFilters != null && intentFilters.size() > 0) {
8884                    PackageParser.ServiceIntentInfo[] array =
8885                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8886                    intentFilters.toArray(array);
8887                    listCut.add(array);
8888                }
8889            }
8890            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8891        }
8892
8893        public final void addService(PackageParser.Service s) {
8894            mServices.put(s.getComponentName(), s);
8895            if (DEBUG_SHOW_INFO) {
8896                Log.v(TAG, "  "
8897                        + (s.info.nonLocalizedLabel != null
8898                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8899                Log.v(TAG, "    Class=" + s.info.name);
8900            }
8901            final int NI = s.intents.size();
8902            int j;
8903            for (j=0; j<NI; j++) {
8904                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8905                if (DEBUG_SHOW_INFO) {
8906                    Log.v(TAG, "    IntentFilter:");
8907                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8908                }
8909                if (!intent.debugCheck()) {
8910                    Log.w(TAG, "==> For Service " + s.info.name);
8911                }
8912                addFilter(intent);
8913            }
8914        }
8915
8916        public final void removeService(PackageParser.Service s) {
8917            mServices.remove(s.getComponentName());
8918            if (DEBUG_SHOW_INFO) {
8919                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8920                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8921                Log.v(TAG, "    Class=" + s.info.name);
8922            }
8923            final int NI = s.intents.size();
8924            int j;
8925            for (j=0; j<NI; j++) {
8926                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8927                if (DEBUG_SHOW_INFO) {
8928                    Log.v(TAG, "    IntentFilter:");
8929                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8930                }
8931                removeFilter(intent);
8932            }
8933        }
8934
8935        @Override
8936        protected boolean allowFilterResult(
8937                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8938            ServiceInfo filterSi = filter.service.info;
8939            for (int i=dest.size()-1; i>=0; i--) {
8940                ServiceInfo destAi = dest.get(i).serviceInfo;
8941                if (destAi.name == filterSi.name
8942                        && destAi.packageName == filterSi.packageName) {
8943                    return false;
8944                }
8945            }
8946            return true;
8947        }
8948
8949        @Override
8950        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8951            return new PackageParser.ServiceIntentInfo[size];
8952        }
8953
8954        @Override
8955        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8956            if (!sUserManager.exists(userId)) return true;
8957            PackageParser.Package p = filter.service.owner;
8958            if (p != null) {
8959                PackageSetting ps = (PackageSetting)p.mExtras;
8960                if (ps != null) {
8961                    // System apps are never considered stopped for purposes of
8962                    // filtering, because there may be no way for the user to
8963                    // actually re-launch them.
8964                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8965                            && ps.getStopped(userId);
8966                }
8967            }
8968            return false;
8969        }
8970
8971        @Override
8972        protected boolean isPackageForFilter(String packageName,
8973                PackageParser.ServiceIntentInfo info) {
8974            return packageName.equals(info.service.owner.packageName);
8975        }
8976
8977        @Override
8978        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8979                int match, int userId) {
8980            if (!sUserManager.exists(userId)) return null;
8981            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8982            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8983                return null;
8984            }
8985            final PackageParser.Service service = info.service;
8986            if (mSafeMode && (service.info.applicationInfo.flags
8987                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8988                return null;
8989            }
8990            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8991            if (ps == null) {
8992                return null;
8993            }
8994            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8995                    ps.readUserState(userId), userId);
8996            if (si == null) {
8997                return null;
8998            }
8999            final ResolveInfo res = new ResolveInfo();
9000            res.serviceInfo = si;
9001            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9002                res.filter = filter;
9003            }
9004            res.priority = info.getPriority();
9005            res.preferredOrder = service.owner.mPreferredOrder;
9006            res.match = match;
9007            res.isDefault = info.hasDefault;
9008            res.labelRes = info.labelRes;
9009            res.nonLocalizedLabel = info.nonLocalizedLabel;
9010            res.icon = info.icon;
9011            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9012            return res;
9013        }
9014
9015        @Override
9016        protected void sortResults(List<ResolveInfo> results) {
9017            Collections.sort(results, mResolvePrioritySorter);
9018        }
9019
9020        @Override
9021        protected void dumpFilter(PrintWriter out, String prefix,
9022                PackageParser.ServiceIntentInfo filter) {
9023            out.print(prefix); out.print(
9024                    Integer.toHexString(System.identityHashCode(filter.service)));
9025                    out.print(' ');
9026                    filter.service.printComponentShortName(out);
9027                    out.print(" filter ");
9028                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9029        }
9030
9031        @Override
9032        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9033            return filter.service;
9034        }
9035
9036        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9037            PackageParser.Service service = (PackageParser.Service)label;
9038            out.print(prefix); out.print(
9039                    Integer.toHexString(System.identityHashCode(service)));
9040                    out.print(' ');
9041                    service.printComponentShortName(out);
9042            if (count > 1) {
9043                out.print(" ("); out.print(count); out.print(" filters)");
9044            }
9045            out.println();
9046        }
9047
9048//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9049//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9050//            final List<ResolveInfo> retList = Lists.newArrayList();
9051//            while (i.hasNext()) {
9052//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9053//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9054//                    retList.add(resolveInfo);
9055//                }
9056//            }
9057//            return retList;
9058//        }
9059
9060        // Keys are String (activity class name), values are Activity.
9061        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9062                = new ArrayMap<ComponentName, PackageParser.Service>();
9063        private int mFlags;
9064    };
9065
9066    private final class ProviderIntentResolver
9067            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9068        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9069                boolean defaultOnly, int userId) {
9070            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9071            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9072        }
9073
9074        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9075                int userId) {
9076            if (!sUserManager.exists(userId))
9077                return null;
9078            mFlags = flags;
9079            return super.queryIntent(intent, resolvedType,
9080                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9081        }
9082
9083        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9084                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9085            if (!sUserManager.exists(userId))
9086                return null;
9087            if (packageProviders == null) {
9088                return null;
9089            }
9090            mFlags = flags;
9091            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9092            final int N = packageProviders.size();
9093            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9094                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9095
9096            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9097            for (int i = 0; i < N; ++i) {
9098                intentFilters = packageProviders.get(i).intents;
9099                if (intentFilters != null && intentFilters.size() > 0) {
9100                    PackageParser.ProviderIntentInfo[] array =
9101                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9102                    intentFilters.toArray(array);
9103                    listCut.add(array);
9104                }
9105            }
9106            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9107        }
9108
9109        public final void addProvider(PackageParser.Provider p) {
9110            if (mProviders.containsKey(p.getComponentName())) {
9111                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9112                return;
9113            }
9114
9115            mProviders.put(p.getComponentName(), p);
9116            if (DEBUG_SHOW_INFO) {
9117                Log.v(TAG, "  "
9118                        + (p.info.nonLocalizedLabel != null
9119                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9120                Log.v(TAG, "    Class=" + p.info.name);
9121            }
9122            final int NI = p.intents.size();
9123            int j;
9124            for (j = 0; j < NI; j++) {
9125                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9126                if (DEBUG_SHOW_INFO) {
9127                    Log.v(TAG, "    IntentFilter:");
9128                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9129                }
9130                if (!intent.debugCheck()) {
9131                    Log.w(TAG, "==> For Provider " + p.info.name);
9132                }
9133                addFilter(intent);
9134            }
9135        }
9136
9137        public final void removeProvider(PackageParser.Provider p) {
9138            mProviders.remove(p.getComponentName());
9139            if (DEBUG_SHOW_INFO) {
9140                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9141                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9142                Log.v(TAG, "    Class=" + p.info.name);
9143            }
9144            final int NI = p.intents.size();
9145            int j;
9146            for (j = 0; j < NI; j++) {
9147                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9148                if (DEBUG_SHOW_INFO) {
9149                    Log.v(TAG, "    IntentFilter:");
9150                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9151                }
9152                removeFilter(intent);
9153            }
9154        }
9155
9156        @Override
9157        protected boolean allowFilterResult(
9158                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9159            ProviderInfo filterPi = filter.provider.info;
9160            for (int i = dest.size() - 1; i >= 0; i--) {
9161                ProviderInfo destPi = dest.get(i).providerInfo;
9162                if (destPi.name == filterPi.name
9163                        && destPi.packageName == filterPi.packageName) {
9164                    return false;
9165                }
9166            }
9167            return true;
9168        }
9169
9170        @Override
9171        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9172            return new PackageParser.ProviderIntentInfo[size];
9173        }
9174
9175        @Override
9176        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9177            if (!sUserManager.exists(userId))
9178                return true;
9179            PackageParser.Package p = filter.provider.owner;
9180            if (p != null) {
9181                PackageSetting ps = (PackageSetting) p.mExtras;
9182                if (ps != null) {
9183                    // System apps are never considered stopped for purposes of
9184                    // filtering, because there may be no way for the user to
9185                    // actually re-launch them.
9186                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9187                            && ps.getStopped(userId);
9188                }
9189            }
9190            return false;
9191        }
9192
9193        @Override
9194        protected boolean isPackageForFilter(String packageName,
9195                PackageParser.ProviderIntentInfo info) {
9196            return packageName.equals(info.provider.owner.packageName);
9197        }
9198
9199        @Override
9200        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9201                int match, int userId) {
9202            if (!sUserManager.exists(userId))
9203                return null;
9204            final PackageParser.ProviderIntentInfo info = filter;
9205            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9206                return null;
9207            }
9208            final PackageParser.Provider provider = info.provider;
9209            if (mSafeMode && (provider.info.applicationInfo.flags
9210                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9211                return null;
9212            }
9213            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9214            if (ps == null) {
9215                return null;
9216            }
9217            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9218                    ps.readUserState(userId), userId);
9219            if (pi == null) {
9220                return null;
9221            }
9222            final ResolveInfo res = new ResolveInfo();
9223            res.providerInfo = pi;
9224            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9225                res.filter = filter;
9226            }
9227            res.priority = info.getPriority();
9228            res.preferredOrder = provider.owner.mPreferredOrder;
9229            res.match = match;
9230            res.isDefault = info.hasDefault;
9231            res.labelRes = info.labelRes;
9232            res.nonLocalizedLabel = info.nonLocalizedLabel;
9233            res.icon = info.icon;
9234            res.system = res.providerInfo.applicationInfo.isSystemApp();
9235            return res;
9236        }
9237
9238        @Override
9239        protected void sortResults(List<ResolveInfo> results) {
9240            Collections.sort(results, mResolvePrioritySorter);
9241        }
9242
9243        @Override
9244        protected void dumpFilter(PrintWriter out, String prefix,
9245                PackageParser.ProviderIntentInfo filter) {
9246            out.print(prefix);
9247            out.print(
9248                    Integer.toHexString(System.identityHashCode(filter.provider)));
9249            out.print(' ');
9250            filter.provider.printComponentShortName(out);
9251            out.print(" filter ");
9252            out.println(Integer.toHexString(System.identityHashCode(filter)));
9253        }
9254
9255        @Override
9256        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9257            return filter.provider;
9258        }
9259
9260        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9261            PackageParser.Provider provider = (PackageParser.Provider)label;
9262            out.print(prefix); out.print(
9263                    Integer.toHexString(System.identityHashCode(provider)));
9264                    out.print(' ');
9265                    provider.printComponentShortName(out);
9266            if (count > 1) {
9267                out.print(" ("); out.print(count); out.print(" filters)");
9268            }
9269            out.println();
9270        }
9271
9272        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9273                = new ArrayMap<ComponentName, PackageParser.Provider>();
9274        private int mFlags;
9275    };
9276
9277    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9278            new Comparator<ResolveInfo>() {
9279        public int compare(ResolveInfo r1, ResolveInfo r2) {
9280            int v1 = r1.priority;
9281            int v2 = r2.priority;
9282            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9283            if (v1 != v2) {
9284                return (v1 > v2) ? -1 : 1;
9285            }
9286            v1 = r1.preferredOrder;
9287            v2 = r2.preferredOrder;
9288            if (v1 != v2) {
9289                return (v1 > v2) ? -1 : 1;
9290            }
9291            if (r1.isDefault != r2.isDefault) {
9292                return r1.isDefault ? -1 : 1;
9293            }
9294            v1 = r1.match;
9295            v2 = r2.match;
9296            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9297            if (v1 != v2) {
9298                return (v1 > v2) ? -1 : 1;
9299            }
9300            if (r1.system != r2.system) {
9301                return r1.system ? -1 : 1;
9302            }
9303            return 0;
9304        }
9305    };
9306
9307    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9308            new Comparator<ProviderInfo>() {
9309        public int compare(ProviderInfo p1, ProviderInfo p2) {
9310            final int v1 = p1.initOrder;
9311            final int v2 = p2.initOrder;
9312            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9313        }
9314    };
9315
9316    final void sendPackageBroadcast(final String action, final String pkg,
9317            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9318            final int[] userIds) {
9319        mHandler.post(new Runnable() {
9320            @Override
9321            public void run() {
9322                try {
9323                    final IActivityManager am = ActivityManagerNative.getDefault();
9324                    if (am == null) return;
9325                    final int[] resolvedUserIds;
9326                    if (userIds == null) {
9327                        resolvedUserIds = am.getRunningUserIds();
9328                    } else {
9329                        resolvedUserIds = userIds;
9330                    }
9331                    for (int id : resolvedUserIds) {
9332                        final Intent intent = new Intent(action,
9333                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9334                        if (extras != null) {
9335                            intent.putExtras(extras);
9336                        }
9337                        if (targetPkg != null) {
9338                            intent.setPackage(targetPkg);
9339                        }
9340                        // Modify the UID when posting to other users
9341                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9342                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9343                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9344                            intent.putExtra(Intent.EXTRA_UID, uid);
9345                        }
9346                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9347                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9348                        if (DEBUG_BROADCASTS) {
9349                            RuntimeException here = new RuntimeException("here");
9350                            here.fillInStackTrace();
9351                            Slog.d(TAG, "Sending to user " + id + ": "
9352                                    + intent.toShortString(false, true, false, false)
9353                                    + " " + intent.getExtras(), here);
9354                        }
9355                        am.broadcastIntent(null, intent, null, finishedReceiver,
9356                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9357                                null, finishedReceiver != null, false, id);
9358                    }
9359                } catch (RemoteException ex) {
9360                }
9361            }
9362        });
9363    }
9364
9365    /**
9366     * Check if the external storage media is available. This is true if there
9367     * is a mounted external storage medium or if the external storage is
9368     * emulated.
9369     */
9370    private boolean isExternalMediaAvailable() {
9371        return mMediaMounted || Environment.isExternalStorageEmulated();
9372    }
9373
9374    @Override
9375    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9376        // writer
9377        synchronized (mPackages) {
9378            if (!isExternalMediaAvailable()) {
9379                // If the external storage is no longer mounted at this point,
9380                // the caller may not have been able to delete all of this
9381                // packages files and can not delete any more.  Bail.
9382                return null;
9383            }
9384            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9385            if (lastPackage != null) {
9386                pkgs.remove(lastPackage);
9387            }
9388            if (pkgs.size() > 0) {
9389                return pkgs.get(0);
9390            }
9391        }
9392        return null;
9393    }
9394
9395    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9396        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9397                userId, andCode ? 1 : 0, packageName);
9398        if (mSystemReady) {
9399            msg.sendToTarget();
9400        } else {
9401            if (mPostSystemReadyMessages == null) {
9402                mPostSystemReadyMessages = new ArrayList<>();
9403            }
9404            mPostSystemReadyMessages.add(msg);
9405        }
9406    }
9407
9408    void startCleaningPackages() {
9409        // reader
9410        synchronized (mPackages) {
9411            if (!isExternalMediaAvailable()) {
9412                return;
9413            }
9414            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9415                return;
9416            }
9417        }
9418        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9419        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9420        IActivityManager am = ActivityManagerNative.getDefault();
9421        if (am != null) {
9422            try {
9423                am.startService(null, intent, null, mContext.getOpPackageName(),
9424                        UserHandle.USER_OWNER);
9425            } catch (RemoteException e) {
9426            }
9427        }
9428    }
9429
9430    @Override
9431    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9432            int installFlags, String installerPackageName, VerificationParams verificationParams,
9433            String packageAbiOverride) {
9434        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9435                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9436    }
9437
9438    @Override
9439    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9440            int installFlags, String installerPackageName, VerificationParams verificationParams,
9441            String packageAbiOverride, int userId) {
9442        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9443
9444        final int callingUid = Binder.getCallingUid();
9445        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9446
9447        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9448            try {
9449                if (observer != null) {
9450                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9451                }
9452            } catch (RemoteException re) {
9453            }
9454            return;
9455        }
9456
9457        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9458            installFlags |= PackageManager.INSTALL_FROM_ADB;
9459
9460        } else {
9461            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9462            // about installerPackageName.
9463
9464            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9465            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9466        }
9467
9468        UserHandle user;
9469        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9470            user = UserHandle.ALL;
9471        } else {
9472            user = new UserHandle(userId);
9473        }
9474
9475        // Only system components can circumvent runtime permissions when installing.
9476        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9477                && mContext.checkCallingOrSelfPermission(Manifest.permission
9478                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9479            throw new SecurityException("You need the "
9480                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9481                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9482        }
9483
9484        verificationParams.setInstallerUid(callingUid);
9485
9486        final File originFile = new File(originPath);
9487        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9488
9489        final Message msg = mHandler.obtainMessage(INIT_COPY);
9490        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9491                null, verificationParams, user, packageAbiOverride, null);
9492        mHandler.sendMessage(msg);
9493    }
9494
9495    void installStage(String packageName, File stagedDir, String stagedCid,
9496            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9497            String installerPackageName, int installerUid, UserHandle user) {
9498        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9499                params.referrerUri, installerUid, null);
9500        verifParams.setInstallerUid(installerUid);
9501
9502        final OriginInfo origin;
9503        if (stagedDir != null) {
9504            origin = OriginInfo.fromStagedFile(stagedDir);
9505        } else {
9506            origin = OriginInfo.fromStagedContainer(stagedCid);
9507        }
9508
9509        final Message msg = mHandler.obtainMessage(INIT_COPY);
9510        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9511                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9512                params.grantedRuntimePermissions);
9513        mHandler.sendMessage(msg);
9514    }
9515
9516    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9517        Bundle extras = new Bundle(1);
9518        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9519
9520        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9521                packageName, extras, null, null, new int[] {userId});
9522        try {
9523            IActivityManager am = ActivityManagerNative.getDefault();
9524            final boolean isSystem =
9525                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9526            if (isSystem && am.isUserRunning(userId, false)) {
9527                // The just-installed/enabled app is bundled on the system, so presumed
9528                // to be able to run automatically without needing an explicit launch.
9529                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9530                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9531                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9532                        .setPackage(packageName);
9533                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9534                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9535            }
9536        } catch (RemoteException e) {
9537            // shouldn't happen
9538            Slog.w(TAG, "Unable to bootstrap installed package", e);
9539        }
9540    }
9541
9542    @Override
9543    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9544            int userId) {
9545        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9546        PackageSetting pkgSetting;
9547        final int uid = Binder.getCallingUid();
9548        enforceCrossUserPermission(uid, userId, true, true,
9549                "setApplicationHiddenSetting for user " + userId);
9550
9551        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9552            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9553            return false;
9554        }
9555
9556        long callingId = Binder.clearCallingIdentity();
9557        try {
9558            boolean sendAdded = false;
9559            boolean sendRemoved = false;
9560            // writer
9561            synchronized (mPackages) {
9562                pkgSetting = mSettings.mPackages.get(packageName);
9563                if (pkgSetting == null) {
9564                    return false;
9565                }
9566                if (pkgSetting.getHidden(userId) != hidden) {
9567                    pkgSetting.setHidden(hidden, userId);
9568                    mSettings.writePackageRestrictionsLPr(userId);
9569                    if (hidden) {
9570                        sendRemoved = true;
9571                    } else {
9572                        sendAdded = true;
9573                    }
9574                }
9575            }
9576            if (sendAdded) {
9577                sendPackageAddedForUser(packageName, pkgSetting, userId);
9578                return true;
9579            }
9580            if (sendRemoved) {
9581                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9582                        "hiding pkg");
9583                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9584                return true;
9585            }
9586        } finally {
9587            Binder.restoreCallingIdentity(callingId);
9588        }
9589        return false;
9590    }
9591
9592    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9593            int userId) {
9594        final PackageRemovedInfo info = new PackageRemovedInfo();
9595        info.removedPackage = packageName;
9596        info.removedUsers = new int[] {userId};
9597        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9598        info.sendBroadcast(false, false, false);
9599    }
9600
9601    /**
9602     * Returns true if application is not found or there was an error. Otherwise it returns
9603     * the hidden state of the package for the given user.
9604     */
9605    @Override
9606    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9607        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9608        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9609                false, "getApplicationHidden for user " + userId);
9610        PackageSetting pkgSetting;
9611        long callingId = Binder.clearCallingIdentity();
9612        try {
9613            // writer
9614            synchronized (mPackages) {
9615                pkgSetting = mSettings.mPackages.get(packageName);
9616                if (pkgSetting == null) {
9617                    return true;
9618                }
9619                return pkgSetting.getHidden(userId);
9620            }
9621        } finally {
9622            Binder.restoreCallingIdentity(callingId);
9623        }
9624    }
9625
9626    /**
9627     * @hide
9628     */
9629    @Override
9630    public int installExistingPackageAsUser(String packageName, int userId) {
9631        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9632                null);
9633        PackageSetting pkgSetting;
9634        final int uid = Binder.getCallingUid();
9635        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9636                + userId);
9637        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9638            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9639        }
9640
9641        long callingId = Binder.clearCallingIdentity();
9642        try {
9643            boolean sendAdded = false;
9644
9645            // writer
9646            synchronized (mPackages) {
9647                pkgSetting = mSettings.mPackages.get(packageName);
9648                if (pkgSetting == null) {
9649                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9650                }
9651                if (!pkgSetting.getInstalled(userId)) {
9652                    pkgSetting.setInstalled(true, userId);
9653                    pkgSetting.setHidden(false, userId);
9654                    mSettings.writePackageRestrictionsLPr(userId);
9655                    sendAdded = true;
9656                }
9657            }
9658
9659            if (sendAdded) {
9660                sendPackageAddedForUser(packageName, pkgSetting, userId);
9661            }
9662        } finally {
9663            Binder.restoreCallingIdentity(callingId);
9664        }
9665
9666        return PackageManager.INSTALL_SUCCEEDED;
9667    }
9668
9669    boolean isUserRestricted(int userId, String restrictionKey) {
9670        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9671        if (restrictions.getBoolean(restrictionKey, false)) {
9672            Log.w(TAG, "User is restricted: " + restrictionKey);
9673            return true;
9674        }
9675        return false;
9676    }
9677
9678    @Override
9679    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9680        mContext.enforceCallingOrSelfPermission(
9681                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9682                "Only package verification agents can verify applications");
9683
9684        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9685        final PackageVerificationResponse response = new PackageVerificationResponse(
9686                verificationCode, Binder.getCallingUid());
9687        msg.arg1 = id;
9688        msg.obj = response;
9689        mHandler.sendMessage(msg);
9690    }
9691
9692    @Override
9693    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9694            long millisecondsToDelay) {
9695        mContext.enforceCallingOrSelfPermission(
9696                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9697                "Only package verification agents can extend verification timeouts");
9698
9699        final PackageVerificationState state = mPendingVerification.get(id);
9700        final PackageVerificationResponse response = new PackageVerificationResponse(
9701                verificationCodeAtTimeout, Binder.getCallingUid());
9702
9703        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9704            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9705        }
9706        if (millisecondsToDelay < 0) {
9707            millisecondsToDelay = 0;
9708        }
9709        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9710                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9711            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9712        }
9713
9714        if ((state != null) && !state.timeoutExtended()) {
9715            state.extendTimeout();
9716
9717            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9718            msg.arg1 = id;
9719            msg.obj = response;
9720            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9721        }
9722    }
9723
9724    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9725            int verificationCode, UserHandle user) {
9726        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9727        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9728        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9729        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9730        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9731
9732        mContext.sendBroadcastAsUser(intent, user,
9733                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9734    }
9735
9736    private ComponentName matchComponentForVerifier(String packageName,
9737            List<ResolveInfo> receivers) {
9738        ActivityInfo targetReceiver = null;
9739
9740        final int NR = receivers.size();
9741        for (int i = 0; i < NR; i++) {
9742            final ResolveInfo info = receivers.get(i);
9743            if (info.activityInfo == null) {
9744                continue;
9745            }
9746
9747            if (packageName.equals(info.activityInfo.packageName)) {
9748                targetReceiver = info.activityInfo;
9749                break;
9750            }
9751        }
9752
9753        if (targetReceiver == null) {
9754            return null;
9755        }
9756
9757        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9758    }
9759
9760    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9761            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9762        if (pkgInfo.verifiers.length == 0) {
9763            return null;
9764        }
9765
9766        final int N = pkgInfo.verifiers.length;
9767        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9768        for (int i = 0; i < N; i++) {
9769            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9770
9771            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9772                    receivers);
9773            if (comp == null) {
9774                continue;
9775            }
9776
9777            final int verifierUid = getUidForVerifier(verifierInfo);
9778            if (verifierUid == -1) {
9779                continue;
9780            }
9781
9782            if (DEBUG_VERIFY) {
9783                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9784                        + " with the correct signature");
9785            }
9786            sufficientVerifiers.add(comp);
9787            verificationState.addSufficientVerifier(verifierUid);
9788        }
9789
9790        return sufficientVerifiers;
9791    }
9792
9793    private int getUidForVerifier(VerifierInfo verifierInfo) {
9794        synchronized (mPackages) {
9795            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9796            if (pkg == null) {
9797                return -1;
9798            } else if (pkg.mSignatures.length != 1) {
9799                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9800                        + " has more than one signature; ignoring");
9801                return -1;
9802            }
9803
9804            /*
9805             * If the public key of the package's signature does not match
9806             * our expected public key, then this is a different package and
9807             * we should skip.
9808             */
9809
9810            final byte[] expectedPublicKey;
9811            try {
9812                final Signature verifierSig = pkg.mSignatures[0];
9813                final PublicKey publicKey = verifierSig.getPublicKey();
9814                expectedPublicKey = publicKey.getEncoded();
9815            } catch (CertificateException e) {
9816                return -1;
9817            }
9818
9819            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9820
9821            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9822                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9823                        + " does not have the expected public key; ignoring");
9824                return -1;
9825            }
9826
9827            return pkg.applicationInfo.uid;
9828        }
9829    }
9830
9831    @Override
9832    public void finishPackageInstall(int token) {
9833        enforceSystemOrRoot("Only the system is allowed to finish installs");
9834
9835        if (DEBUG_INSTALL) {
9836            Slog.v(TAG, "BM finishing package install for " + token);
9837        }
9838
9839        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9840        mHandler.sendMessage(msg);
9841    }
9842
9843    /**
9844     * Get the verification agent timeout.
9845     *
9846     * @return verification timeout in milliseconds
9847     */
9848    private long getVerificationTimeout() {
9849        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9850                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9851                DEFAULT_VERIFICATION_TIMEOUT);
9852    }
9853
9854    /**
9855     * Get the default verification agent response code.
9856     *
9857     * @return default verification response code
9858     */
9859    private int getDefaultVerificationResponse() {
9860        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9861                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9862                DEFAULT_VERIFICATION_RESPONSE);
9863    }
9864
9865    /**
9866     * Check whether or not package verification has been enabled.
9867     *
9868     * @return true if verification should be performed
9869     */
9870    private boolean isVerificationEnabled(int userId, int installFlags) {
9871        if (!DEFAULT_VERIFY_ENABLE) {
9872            return false;
9873        }
9874
9875        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9876
9877        // Check if installing from ADB
9878        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9879            // Do not run verification in a test harness environment
9880            if (ActivityManager.isRunningInTestHarness()) {
9881                return false;
9882            }
9883            if (ensureVerifyAppsEnabled) {
9884                return true;
9885            }
9886            // Check if the developer does not want package verification for ADB installs
9887            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9888                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9889                return false;
9890            }
9891        }
9892
9893        if (ensureVerifyAppsEnabled) {
9894            return true;
9895        }
9896
9897        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9898                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9899    }
9900
9901    @Override
9902    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9903            throws RemoteException {
9904        mContext.enforceCallingOrSelfPermission(
9905                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9906                "Only intentfilter verification agents can verify applications");
9907
9908        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9909        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9910                Binder.getCallingUid(), verificationCode, failedDomains);
9911        msg.arg1 = id;
9912        msg.obj = response;
9913        mHandler.sendMessage(msg);
9914    }
9915
9916    @Override
9917    public int getIntentVerificationStatus(String packageName, int userId) {
9918        synchronized (mPackages) {
9919            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9920        }
9921    }
9922
9923    @Override
9924    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9925        mContext.enforceCallingOrSelfPermission(
9926                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9927
9928        boolean result = false;
9929        synchronized (mPackages) {
9930            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9931        }
9932        if (result) {
9933            scheduleWritePackageRestrictionsLocked(userId);
9934        }
9935        return result;
9936    }
9937
9938    @Override
9939    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9940        synchronized (mPackages) {
9941            return mSettings.getIntentFilterVerificationsLPr(packageName);
9942        }
9943    }
9944
9945    @Override
9946    public List<IntentFilter> getAllIntentFilters(String packageName) {
9947        if (TextUtils.isEmpty(packageName)) {
9948            return Collections.<IntentFilter>emptyList();
9949        }
9950        synchronized (mPackages) {
9951            PackageParser.Package pkg = mPackages.get(packageName);
9952            if (pkg == null || pkg.activities == null) {
9953                return Collections.<IntentFilter>emptyList();
9954            }
9955            final int count = pkg.activities.size();
9956            ArrayList<IntentFilter> result = new ArrayList<>();
9957            for (int n=0; n<count; n++) {
9958                PackageParser.Activity activity = pkg.activities.get(n);
9959                if (activity.intents != null || activity.intents.size() > 0) {
9960                    result.addAll(activity.intents);
9961                }
9962            }
9963            return result;
9964        }
9965    }
9966
9967    @Override
9968    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9969        mContext.enforceCallingOrSelfPermission(
9970                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9971
9972        synchronized (mPackages) {
9973            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9974            if (packageName != null) {
9975                result |= updateIntentVerificationStatus(packageName,
9976                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9977                        userId);
9978                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9979                        packageName, userId);
9980            }
9981            return result;
9982        }
9983    }
9984
9985    @Override
9986    public String getDefaultBrowserPackageName(int userId) {
9987        synchronized (mPackages) {
9988            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9989        }
9990    }
9991
9992    /**
9993     * Get the "allow unknown sources" setting.
9994     *
9995     * @return the current "allow unknown sources" setting
9996     */
9997    private int getUnknownSourcesSettings() {
9998        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9999                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10000                -1);
10001    }
10002
10003    @Override
10004    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10005        final int uid = Binder.getCallingUid();
10006        // writer
10007        synchronized (mPackages) {
10008            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10009            if (targetPackageSetting == null) {
10010                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10011            }
10012
10013            PackageSetting installerPackageSetting;
10014            if (installerPackageName != null) {
10015                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10016                if (installerPackageSetting == null) {
10017                    throw new IllegalArgumentException("Unknown installer package: "
10018                            + installerPackageName);
10019                }
10020            } else {
10021                installerPackageSetting = null;
10022            }
10023
10024            Signature[] callerSignature;
10025            Object obj = mSettings.getUserIdLPr(uid);
10026            if (obj != null) {
10027                if (obj instanceof SharedUserSetting) {
10028                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10029                } else if (obj instanceof PackageSetting) {
10030                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10031                } else {
10032                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10033                }
10034            } else {
10035                throw new SecurityException("Unknown calling uid " + uid);
10036            }
10037
10038            // Verify: can't set installerPackageName to a package that is
10039            // not signed with the same cert as the caller.
10040            if (installerPackageSetting != null) {
10041                if (compareSignatures(callerSignature,
10042                        installerPackageSetting.signatures.mSignatures)
10043                        != PackageManager.SIGNATURE_MATCH) {
10044                    throw new SecurityException(
10045                            "Caller does not have same cert as new installer package "
10046                            + installerPackageName);
10047                }
10048            }
10049
10050            // Verify: if target already has an installer package, it must
10051            // be signed with the same cert as the caller.
10052            if (targetPackageSetting.installerPackageName != null) {
10053                PackageSetting setting = mSettings.mPackages.get(
10054                        targetPackageSetting.installerPackageName);
10055                // If the currently set package isn't valid, then it's always
10056                // okay to change it.
10057                if (setting != null) {
10058                    if (compareSignatures(callerSignature,
10059                            setting.signatures.mSignatures)
10060                            != PackageManager.SIGNATURE_MATCH) {
10061                        throw new SecurityException(
10062                                "Caller does not have same cert as old installer package "
10063                                + targetPackageSetting.installerPackageName);
10064                    }
10065                }
10066            }
10067
10068            // Okay!
10069            targetPackageSetting.installerPackageName = installerPackageName;
10070            scheduleWriteSettingsLocked();
10071        }
10072    }
10073
10074    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10075        // Queue up an async operation since the package installation may take a little while.
10076        mHandler.post(new Runnable() {
10077            public void run() {
10078                mHandler.removeCallbacks(this);
10079                 // Result object to be returned
10080                PackageInstalledInfo res = new PackageInstalledInfo();
10081                res.returnCode = currentStatus;
10082                res.uid = -1;
10083                res.pkg = null;
10084                res.removedInfo = new PackageRemovedInfo();
10085                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10086                    args.doPreInstall(res.returnCode);
10087                    synchronized (mInstallLock) {
10088                        installPackageLI(args, res);
10089                    }
10090                    args.doPostInstall(res.returnCode, res.uid);
10091                }
10092
10093                // A restore should be performed at this point if (a) the install
10094                // succeeded, (b) the operation is not an update, and (c) the new
10095                // package has not opted out of backup participation.
10096                final boolean update = res.removedInfo.removedPackage != null;
10097                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10098                boolean doRestore = !update
10099                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10100
10101                // Set up the post-install work request bookkeeping.  This will be used
10102                // and cleaned up by the post-install event handling regardless of whether
10103                // there's a restore pass performed.  Token values are >= 1.
10104                int token;
10105                if (mNextInstallToken < 0) mNextInstallToken = 1;
10106                token = mNextInstallToken++;
10107
10108                PostInstallData data = new PostInstallData(args, res);
10109                mRunningInstalls.put(token, data);
10110                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10111
10112                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10113                    // Pass responsibility to the Backup Manager.  It will perform a
10114                    // restore if appropriate, then pass responsibility back to the
10115                    // Package Manager to run the post-install observer callbacks
10116                    // and broadcasts.
10117                    IBackupManager bm = IBackupManager.Stub.asInterface(
10118                            ServiceManager.getService(Context.BACKUP_SERVICE));
10119                    if (bm != null) {
10120                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10121                                + " to BM for possible restore");
10122                        try {
10123                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10124                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10125                            } else {
10126                                doRestore = false;
10127                            }
10128                        } catch (RemoteException e) {
10129                            // can't happen; the backup manager is local
10130                        } catch (Exception e) {
10131                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10132                            doRestore = false;
10133                        }
10134                    } else {
10135                        Slog.e(TAG, "Backup Manager not found!");
10136                        doRestore = false;
10137                    }
10138                }
10139
10140                if (!doRestore) {
10141                    // No restore possible, or the Backup Manager was mysteriously not
10142                    // available -- just fire the post-install work request directly.
10143                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10144                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10145                    mHandler.sendMessage(msg);
10146                }
10147            }
10148        });
10149    }
10150
10151    private abstract class HandlerParams {
10152        private static final int MAX_RETRIES = 4;
10153
10154        /**
10155         * Number of times startCopy() has been attempted and had a non-fatal
10156         * error.
10157         */
10158        private int mRetries = 0;
10159
10160        /** User handle for the user requesting the information or installation. */
10161        private final UserHandle mUser;
10162
10163        HandlerParams(UserHandle user) {
10164            mUser = user;
10165        }
10166
10167        UserHandle getUser() {
10168            return mUser;
10169        }
10170
10171        final boolean startCopy() {
10172            boolean res;
10173            try {
10174                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10175
10176                if (++mRetries > MAX_RETRIES) {
10177                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10178                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10179                    handleServiceError();
10180                    return false;
10181                } else {
10182                    handleStartCopy();
10183                    res = true;
10184                }
10185            } catch (RemoteException e) {
10186                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10187                mHandler.sendEmptyMessage(MCS_RECONNECT);
10188                res = false;
10189            }
10190            handleReturnCode();
10191            return res;
10192        }
10193
10194        final void serviceError() {
10195            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10196            handleServiceError();
10197            handleReturnCode();
10198        }
10199
10200        abstract void handleStartCopy() throws RemoteException;
10201        abstract void handleServiceError();
10202        abstract void handleReturnCode();
10203    }
10204
10205    class MeasureParams extends HandlerParams {
10206        private final PackageStats mStats;
10207        private boolean mSuccess;
10208
10209        private final IPackageStatsObserver mObserver;
10210
10211        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10212            super(new UserHandle(stats.userHandle));
10213            mObserver = observer;
10214            mStats = stats;
10215        }
10216
10217        @Override
10218        public String toString() {
10219            return "MeasureParams{"
10220                + Integer.toHexString(System.identityHashCode(this))
10221                + " " + mStats.packageName + "}";
10222        }
10223
10224        @Override
10225        void handleStartCopy() throws RemoteException {
10226            synchronized (mInstallLock) {
10227                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10228            }
10229
10230            if (mSuccess) {
10231                final boolean mounted;
10232                if (Environment.isExternalStorageEmulated()) {
10233                    mounted = true;
10234                } else {
10235                    final String status = Environment.getExternalStorageState();
10236                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10237                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10238                }
10239
10240                if (mounted) {
10241                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10242
10243                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10244                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10245
10246                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10247                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10248
10249                    // Always subtract cache size, since it's a subdirectory
10250                    mStats.externalDataSize -= mStats.externalCacheSize;
10251
10252                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10253                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10254
10255                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10256                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10257                }
10258            }
10259        }
10260
10261        @Override
10262        void handleReturnCode() {
10263            if (mObserver != null) {
10264                try {
10265                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10266                } catch (RemoteException e) {
10267                    Slog.i(TAG, "Observer no longer exists.");
10268                }
10269            }
10270        }
10271
10272        @Override
10273        void handleServiceError() {
10274            Slog.e(TAG, "Could not measure application " + mStats.packageName
10275                            + " external storage");
10276        }
10277    }
10278
10279    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10280            throws RemoteException {
10281        long result = 0;
10282        for (File path : paths) {
10283            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10284        }
10285        return result;
10286    }
10287
10288    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10289        for (File path : paths) {
10290            try {
10291                mcs.clearDirectory(path.getAbsolutePath());
10292            } catch (RemoteException e) {
10293            }
10294        }
10295    }
10296
10297    static class OriginInfo {
10298        /**
10299         * Location where install is coming from, before it has been
10300         * copied/renamed into place. This could be a single monolithic APK
10301         * file, or a cluster directory. This location may be untrusted.
10302         */
10303        final File file;
10304        final String cid;
10305
10306        /**
10307         * Flag indicating that {@link #file} or {@link #cid} has already been
10308         * staged, meaning downstream users don't need to defensively copy the
10309         * contents.
10310         */
10311        final boolean staged;
10312
10313        /**
10314         * Flag indicating that {@link #file} or {@link #cid} is an already
10315         * installed app that is being moved.
10316         */
10317        final boolean existing;
10318
10319        final String resolvedPath;
10320        final File resolvedFile;
10321
10322        static OriginInfo fromNothing() {
10323            return new OriginInfo(null, null, false, false);
10324        }
10325
10326        static OriginInfo fromUntrustedFile(File file) {
10327            return new OriginInfo(file, null, false, false);
10328        }
10329
10330        static OriginInfo fromExistingFile(File file) {
10331            return new OriginInfo(file, null, false, true);
10332        }
10333
10334        static OriginInfo fromStagedFile(File file) {
10335            return new OriginInfo(file, null, true, false);
10336        }
10337
10338        static OriginInfo fromStagedContainer(String cid) {
10339            return new OriginInfo(null, cid, true, false);
10340        }
10341
10342        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10343            this.file = file;
10344            this.cid = cid;
10345            this.staged = staged;
10346            this.existing = existing;
10347
10348            if (cid != null) {
10349                resolvedPath = PackageHelper.getSdDir(cid);
10350                resolvedFile = new File(resolvedPath);
10351            } else if (file != null) {
10352                resolvedPath = file.getAbsolutePath();
10353                resolvedFile = file;
10354            } else {
10355                resolvedPath = null;
10356                resolvedFile = null;
10357            }
10358        }
10359    }
10360
10361    class MoveInfo {
10362        final int moveId;
10363        final String fromUuid;
10364        final String toUuid;
10365        final String packageName;
10366        final String dataAppName;
10367        final int appId;
10368        final String seinfo;
10369
10370        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10371                String dataAppName, int appId, String seinfo) {
10372            this.moveId = moveId;
10373            this.fromUuid = fromUuid;
10374            this.toUuid = toUuid;
10375            this.packageName = packageName;
10376            this.dataAppName = dataAppName;
10377            this.appId = appId;
10378            this.seinfo = seinfo;
10379        }
10380    }
10381
10382    class InstallParams extends HandlerParams {
10383        final OriginInfo origin;
10384        final MoveInfo move;
10385        final IPackageInstallObserver2 observer;
10386        int installFlags;
10387        final String installerPackageName;
10388        final String volumeUuid;
10389        final VerificationParams verificationParams;
10390        private InstallArgs mArgs;
10391        private int mRet;
10392        final String packageAbiOverride;
10393        final String[] grantedRuntimePermissions;
10394
10395
10396        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10397                int installFlags, String installerPackageName, String volumeUuid,
10398                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10399                String[] grantedPermissions) {
10400            super(user);
10401            this.origin = origin;
10402            this.move = move;
10403            this.observer = observer;
10404            this.installFlags = installFlags;
10405            this.installerPackageName = installerPackageName;
10406            this.volumeUuid = volumeUuid;
10407            this.verificationParams = verificationParams;
10408            this.packageAbiOverride = packageAbiOverride;
10409            this.grantedRuntimePermissions = grantedPermissions;
10410        }
10411
10412        @Override
10413        public String toString() {
10414            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10415                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10416        }
10417
10418        public ManifestDigest getManifestDigest() {
10419            if (verificationParams == null) {
10420                return null;
10421            }
10422            return verificationParams.getManifestDigest();
10423        }
10424
10425        private int installLocationPolicy(PackageInfoLite pkgLite) {
10426            String packageName = pkgLite.packageName;
10427            int installLocation = pkgLite.installLocation;
10428            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10429            // reader
10430            synchronized (mPackages) {
10431                PackageParser.Package pkg = mPackages.get(packageName);
10432                if (pkg != null) {
10433                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10434                        // Check for downgrading.
10435                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10436                            try {
10437                                checkDowngrade(pkg, pkgLite);
10438                            } catch (PackageManagerException e) {
10439                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10440                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10441                            }
10442                        }
10443                        // Check for updated system application.
10444                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10445                            if (onSd) {
10446                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10447                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10448                            }
10449                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10450                        } else {
10451                            if (onSd) {
10452                                // Install flag overrides everything.
10453                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10454                            }
10455                            // If current upgrade specifies particular preference
10456                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10457                                // Application explicitly specified internal.
10458                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10459                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10460                                // App explictly prefers external. Let policy decide
10461                            } else {
10462                                // Prefer previous location
10463                                if (isExternal(pkg)) {
10464                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10465                                }
10466                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10467                            }
10468                        }
10469                    } else {
10470                        // Invalid install. Return error code
10471                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10472                    }
10473                }
10474            }
10475            // All the special cases have been taken care of.
10476            // Return result based on recommended install location.
10477            if (onSd) {
10478                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10479            }
10480            return pkgLite.recommendedInstallLocation;
10481        }
10482
10483        /*
10484         * Invoke remote method to get package information and install
10485         * location values. Override install location based on default
10486         * policy if needed and then create install arguments based
10487         * on the install location.
10488         */
10489        public void handleStartCopy() throws RemoteException {
10490            int ret = PackageManager.INSTALL_SUCCEEDED;
10491
10492            // If we're already staged, we've firmly committed to an install location
10493            if (origin.staged) {
10494                if (origin.file != null) {
10495                    installFlags |= PackageManager.INSTALL_INTERNAL;
10496                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10497                } else if (origin.cid != null) {
10498                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10499                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10500                } else {
10501                    throw new IllegalStateException("Invalid stage location");
10502                }
10503            }
10504
10505            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10506            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10507
10508            PackageInfoLite pkgLite = null;
10509
10510            if (onInt && onSd) {
10511                // Check if both bits are set.
10512                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10513                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10514            } else {
10515                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10516                        packageAbiOverride);
10517
10518                /*
10519                 * If we have too little free space, try to free cache
10520                 * before giving up.
10521                 */
10522                if (!origin.staged && pkgLite.recommendedInstallLocation
10523                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10524                    // TODO: focus freeing disk space on the target device
10525                    final StorageManager storage = StorageManager.from(mContext);
10526                    final long lowThreshold = storage.getStorageLowBytes(
10527                            Environment.getDataDirectory());
10528
10529                    final long sizeBytes = mContainerService.calculateInstalledSize(
10530                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10531
10532                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10533                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10534                                installFlags, packageAbiOverride);
10535                    }
10536
10537                    /*
10538                     * The cache free must have deleted the file we
10539                     * downloaded to install.
10540                     *
10541                     * TODO: fix the "freeCache" call to not delete
10542                     *       the file we care about.
10543                     */
10544                    if (pkgLite.recommendedInstallLocation
10545                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10546                        pkgLite.recommendedInstallLocation
10547                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10548                    }
10549                }
10550            }
10551
10552            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10553                int loc = pkgLite.recommendedInstallLocation;
10554                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10555                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10556                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10557                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10558                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10559                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10560                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10561                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10562                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10563                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10564                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10565                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10566                } else {
10567                    // Override with defaults if needed.
10568                    loc = installLocationPolicy(pkgLite);
10569                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10570                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10571                    } else if (!onSd && !onInt) {
10572                        // Override install location with flags
10573                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10574                            // Set the flag to install on external media.
10575                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10576                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10577                        } else {
10578                            // Make sure the flag for installing on external
10579                            // media is unset
10580                            installFlags |= PackageManager.INSTALL_INTERNAL;
10581                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10582                        }
10583                    }
10584                }
10585            }
10586
10587            final InstallArgs args = createInstallArgs(this);
10588            mArgs = args;
10589
10590            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10591                 /*
10592                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10593                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10594                 */
10595                int userIdentifier = getUser().getIdentifier();
10596                if (userIdentifier == UserHandle.USER_ALL
10597                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10598                    userIdentifier = UserHandle.USER_OWNER;
10599                }
10600
10601                /*
10602                 * Determine if we have any installed package verifiers. If we
10603                 * do, then we'll defer to them to verify the packages.
10604                 */
10605                final int requiredUid = mRequiredVerifierPackage == null ? -1
10606                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10607                if (!origin.existing && requiredUid != -1
10608                        && isVerificationEnabled(userIdentifier, installFlags)) {
10609                    final Intent verification = new Intent(
10610                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10611                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10612                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10613                            PACKAGE_MIME_TYPE);
10614                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10615
10616                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10617                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10618                            0 /* TODO: Which userId? */);
10619
10620                    if (DEBUG_VERIFY) {
10621                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10622                                + verification.toString() + " with " + pkgLite.verifiers.length
10623                                + " optional verifiers");
10624                    }
10625
10626                    final int verificationId = mPendingVerificationToken++;
10627
10628                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10629
10630                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10631                            installerPackageName);
10632
10633                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10634                            installFlags);
10635
10636                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10637                            pkgLite.packageName);
10638
10639                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10640                            pkgLite.versionCode);
10641
10642                    if (verificationParams != null) {
10643                        if (verificationParams.getVerificationURI() != null) {
10644                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10645                                 verificationParams.getVerificationURI());
10646                        }
10647                        if (verificationParams.getOriginatingURI() != null) {
10648                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10649                                  verificationParams.getOriginatingURI());
10650                        }
10651                        if (verificationParams.getReferrer() != null) {
10652                            verification.putExtra(Intent.EXTRA_REFERRER,
10653                                  verificationParams.getReferrer());
10654                        }
10655                        if (verificationParams.getOriginatingUid() >= 0) {
10656                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10657                                  verificationParams.getOriginatingUid());
10658                        }
10659                        if (verificationParams.getInstallerUid() >= 0) {
10660                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10661                                  verificationParams.getInstallerUid());
10662                        }
10663                    }
10664
10665                    final PackageVerificationState verificationState = new PackageVerificationState(
10666                            requiredUid, args);
10667
10668                    mPendingVerification.append(verificationId, verificationState);
10669
10670                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10671                            receivers, verificationState);
10672
10673                    // Apps installed for "all" users use the device owner to verify the app
10674                    UserHandle verifierUser = getUser();
10675                    if (verifierUser == UserHandle.ALL) {
10676                        verifierUser = UserHandle.OWNER;
10677                    }
10678
10679                    /*
10680                     * If any sufficient verifiers were listed in the package
10681                     * manifest, attempt to ask them.
10682                     */
10683                    if (sufficientVerifiers != null) {
10684                        final int N = sufficientVerifiers.size();
10685                        if (N == 0) {
10686                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10687                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10688                        } else {
10689                            for (int i = 0; i < N; i++) {
10690                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10691
10692                                final Intent sufficientIntent = new Intent(verification);
10693                                sufficientIntent.setComponent(verifierComponent);
10694                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10695                            }
10696                        }
10697                    }
10698
10699                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10700                            mRequiredVerifierPackage, receivers);
10701                    if (ret == PackageManager.INSTALL_SUCCEEDED
10702                            && mRequiredVerifierPackage != null) {
10703                        /*
10704                         * Send the intent to the required verification agent,
10705                         * but only start the verification timeout after the
10706                         * target BroadcastReceivers have run.
10707                         */
10708                        verification.setComponent(requiredVerifierComponent);
10709                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10710                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10711                                new BroadcastReceiver() {
10712                                    @Override
10713                                    public void onReceive(Context context, Intent intent) {
10714                                        final Message msg = mHandler
10715                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10716                                        msg.arg1 = verificationId;
10717                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10718                                    }
10719                                }, null, 0, null, null);
10720
10721                        /*
10722                         * We don't want the copy to proceed until verification
10723                         * succeeds, so null out this field.
10724                         */
10725                        mArgs = null;
10726                    }
10727                } else {
10728                    /*
10729                     * No package verification is enabled, so immediately start
10730                     * the remote call to initiate copy using temporary file.
10731                     */
10732                    ret = args.copyApk(mContainerService, true);
10733                }
10734            }
10735
10736            mRet = ret;
10737        }
10738
10739        @Override
10740        void handleReturnCode() {
10741            // If mArgs is null, then MCS couldn't be reached. When it
10742            // reconnects, it will try again to install. At that point, this
10743            // will succeed.
10744            if (mArgs != null) {
10745                processPendingInstall(mArgs, mRet);
10746            }
10747        }
10748
10749        @Override
10750        void handleServiceError() {
10751            mArgs = createInstallArgs(this);
10752            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10753        }
10754
10755        public boolean isForwardLocked() {
10756            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10757        }
10758    }
10759
10760    /**
10761     * Used during creation of InstallArgs
10762     *
10763     * @param installFlags package installation flags
10764     * @return true if should be installed on external storage
10765     */
10766    private static boolean installOnExternalAsec(int installFlags) {
10767        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10768            return false;
10769        }
10770        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10771            return true;
10772        }
10773        return false;
10774    }
10775
10776    /**
10777     * Used during creation of InstallArgs
10778     *
10779     * @param installFlags package installation flags
10780     * @return true if should be installed as forward locked
10781     */
10782    private static boolean installForwardLocked(int installFlags) {
10783        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10784    }
10785
10786    private InstallArgs createInstallArgs(InstallParams params) {
10787        if (params.move != null) {
10788            return new MoveInstallArgs(params);
10789        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10790            return new AsecInstallArgs(params);
10791        } else {
10792            return new FileInstallArgs(params);
10793        }
10794    }
10795
10796    /**
10797     * Create args that describe an existing installed package. Typically used
10798     * when cleaning up old installs, or used as a move source.
10799     */
10800    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10801            String resourcePath, String[] instructionSets) {
10802        final boolean isInAsec;
10803        if (installOnExternalAsec(installFlags)) {
10804            /* Apps on SD card are always in ASEC containers. */
10805            isInAsec = true;
10806        } else if (installForwardLocked(installFlags)
10807                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10808            /*
10809             * Forward-locked apps are only in ASEC containers if they're the
10810             * new style
10811             */
10812            isInAsec = true;
10813        } else {
10814            isInAsec = false;
10815        }
10816
10817        if (isInAsec) {
10818            return new AsecInstallArgs(codePath, instructionSets,
10819                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10820        } else {
10821            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10822        }
10823    }
10824
10825    static abstract class InstallArgs {
10826        /** @see InstallParams#origin */
10827        final OriginInfo origin;
10828        /** @see InstallParams#move */
10829        final MoveInfo move;
10830
10831        final IPackageInstallObserver2 observer;
10832        // Always refers to PackageManager flags only
10833        final int installFlags;
10834        final String installerPackageName;
10835        final String volumeUuid;
10836        final ManifestDigest manifestDigest;
10837        final UserHandle user;
10838        final String abiOverride;
10839        final String[] installGrantPermissions;
10840
10841        // The list of instruction sets supported by this app. This is currently
10842        // only used during the rmdex() phase to clean up resources. We can get rid of this
10843        // if we move dex files under the common app path.
10844        /* nullable */ String[] instructionSets;
10845
10846        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10847                int installFlags, String installerPackageName, String volumeUuid,
10848                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10849                String abiOverride, String[] installGrantPermissions) {
10850            this.origin = origin;
10851            this.move = move;
10852            this.installFlags = installFlags;
10853            this.observer = observer;
10854            this.installerPackageName = installerPackageName;
10855            this.volumeUuid = volumeUuid;
10856            this.manifestDigest = manifestDigest;
10857            this.user = user;
10858            this.instructionSets = instructionSets;
10859            this.abiOverride = abiOverride;
10860            this.installGrantPermissions = installGrantPermissions;
10861        }
10862
10863        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10864        abstract int doPreInstall(int status);
10865
10866        /**
10867         * Rename package into final resting place. All paths on the given
10868         * scanned package should be updated to reflect the rename.
10869         */
10870        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10871        abstract int doPostInstall(int status, int uid);
10872
10873        /** @see PackageSettingBase#codePathString */
10874        abstract String getCodePath();
10875        /** @see PackageSettingBase#resourcePathString */
10876        abstract String getResourcePath();
10877
10878        // Need installer lock especially for dex file removal.
10879        abstract void cleanUpResourcesLI();
10880        abstract boolean doPostDeleteLI(boolean delete);
10881
10882        /**
10883         * Called before the source arguments are copied. This is used mostly
10884         * for MoveParams when it needs to read the source file to put it in the
10885         * destination.
10886         */
10887        int doPreCopy() {
10888            return PackageManager.INSTALL_SUCCEEDED;
10889        }
10890
10891        /**
10892         * Called after the source arguments are copied. This is used mostly for
10893         * MoveParams when it needs to read the source file to put it in the
10894         * destination.
10895         *
10896         * @return
10897         */
10898        int doPostCopy(int uid) {
10899            return PackageManager.INSTALL_SUCCEEDED;
10900        }
10901
10902        protected boolean isFwdLocked() {
10903            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10904        }
10905
10906        protected boolean isExternalAsec() {
10907            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10908        }
10909
10910        UserHandle getUser() {
10911            return user;
10912        }
10913    }
10914
10915    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10916        if (!allCodePaths.isEmpty()) {
10917            if (instructionSets == null) {
10918                throw new IllegalStateException("instructionSet == null");
10919            }
10920            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10921            for (String codePath : allCodePaths) {
10922                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10923                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10924                    if (retCode < 0) {
10925                        Slog.w(TAG, "Couldn't remove dex file for package: "
10926                                + " at location " + codePath + ", retcode=" + retCode);
10927                        // we don't consider this to be a failure of the core package deletion
10928                    }
10929                }
10930            }
10931        }
10932    }
10933
10934    /**
10935     * Logic to handle installation of non-ASEC applications, including copying
10936     * and renaming logic.
10937     */
10938    class FileInstallArgs extends InstallArgs {
10939        private File codeFile;
10940        private File resourceFile;
10941
10942        // Example topology:
10943        // /data/app/com.example/base.apk
10944        // /data/app/com.example/split_foo.apk
10945        // /data/app/com.example/lib/arm/libfoo.so
10946        // /data/app/com.example/lib/arm64/libfoo.so
10947        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10948
10949        /** New install */
10950        FileInstallArgs(InstallParams params) {
10951            super(params.origin, params.move, params.observer, params.installFlags,
10952                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10953                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10954                    params.grantedRuntimePermissions);
10955            if (isFwdLocked()) {
10956                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10957            }
10958        }
10959
10960        /** Existing install */
10961        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10962            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10963                    null, null);
10964            this.codeFile = (codePath != null) ? new File(codePath) : null;
10965            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10966        }
10967
10968        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10969            if (origin.staged) {
10970                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10971                codeFile = origin.file;
10972                resourceFile = origin.file;
10973                return PackageManager.INSTALL_SUCCEEDED;
10974            }
10975
10976            try {
10977                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10978                codeFile = tempDir;
10979                resourceFile = tempDir;
10980            } catch (IOException e) {
10981                Slog.w(TAG, "Failed to create copy file: " + e);
10982                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10983            }
10984
10985            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10986                @Override
10987                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10988                    if (!FileUtils.isValidExtFilename(name)) {
10989                        throw new IllegalArgumentException("Invalid filename: " + name);
10990                    }
10991                    try {
10992                        final File file = new File(codeFile, name);
10993                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10994                                O_RDWR | O_CREAT, 0644);
10995                        Os.chmod(file.getAbsolutePath(), 0644);
10996                        return new ParcelFileDescriptor(fd);
10997                    } catch (ErrnoException e) {
10998                        throw new RemoteException("Failed to open: " + e.getMessage());
10999                    }
11000                }
11001            };
11002
11003            int ret = PackageManager.INSTALL_SUCCEEDED;
11004            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11005            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11006                Slog.e(TAG, "Failed to copy package");
11007                return ret;
11008            }
11009
11010            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11011            NativeLibraryHelper.Handle handle = null;
11012            try {
11013                handle = NativeLibraryHelper.Handle.create(codeFile);
11014                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11015                        abiOverride);
11016            } catch (IOException e) {
11017                Slog.e(TAG, "Copying native libraries failed", e);
11018                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11019            } finally {
11020                IoUtils.closeQuietly(handle);
11021            }
11022
11023            return ret;
11024        }
11025
11026        int doPreInstall(int status) {
11027            if (status != PackageManager.INSTALL_SUCCEEDED) {
11028                cleanUp();
11029            }
11030            return status;
11031        }
11032
11033        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11034            if (status != PackageManager.INSTALL_SUCCEEDED) {
11035                cleanUp();
11036                return false;
11037            }
11038
11039            final File targetDir = codeFile.getParentFile();
11040            final File beforeCodeFile = codeFile;
11041            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11042
11043            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11044            try {
11045                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11046            } catch (ErrnoException e) {
11047                Slog.w(TAG, "Failed to rename", e);
11048                return false;
11049            }
11050
11051            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11052                Slog.w(TAG, "Failed to restorecon");
11053                return false;
11054            }
11055
11056            // Reflect the rename internally
11057            codeFile = afterCodeFile;
11058            resourceFile = afterCodeFile;
11059
11060            // Reflect the rename in scanned details
11061            pkg.codePath = afterCodeFile.getAbsolutePath();
11062            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11063                    pkg.baseCodePath);
11064            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11065                    pkg.splitCodePaths);
11066
11067            // Reflect the rename in app info
11068            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11069            pkg.applicationInfo.setCodePath(pkg.codePath);
11070            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11071            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11072            pkg.applicationInfo.setResourcePath(pkg.codePath);
11073            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11074            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11075
11076            return true;
11077        }
11078
11079        int doPostInstall(int status, int uid) {
11080            if (status != PackageManager.INSTALL_SUCCEEDED) {
11081                cleanUp();
11082            }
11083            return status;
11084        }
11085
11086        @Override
11087        String getCodePath() {
11088            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11089        }
11090
11091        @Override
11092        String getResourcePath() {
11093            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11094        }
11095
11096        private boolean cleanUp() {
11097            if (codeFile == null || !codeFile.exists()) {
11098                return false;
11099            }
11100
11101            if (codeFile.isDirectory()) {
11102                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11103            } else {
11104                codeFile.delete();
11105            }
11106
11107            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11108                resourceFile.delete();
11109            }
11110
11111            return true;
11112        }
11113
11114        void cleanUpResourcesLI() {
11115            // Try enumerating all code paths before deleting
11116            List<String> allCodePaths = Collections.EMPTY_LIST;
11117            if (codeFile != null && codeFile.exists()) {
11118                try {
11119                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11120                    allCodePaths = pkg.getAllCodePaths();
11121                } catch (PackageParserException e) {
11122                    // Ignored; we tried our best
11123                }
11124            }
11125
11126            cleanUp();
11127            removeDexFiles(allCodePaths, instructionSets);
11128        }
11129
11130        boolean doPostDeleteLI(boolean delete) {
11131            // XXX err, shouldn't we respect the delete flag?
11132            cleanUpResourcesLI();
11133            return true;
11134        }
11135    }
11136
11137    private boolean isAsecExternal(String cid) {
11138        final String asecPath = PackageHelper.getSdFilesystem(cid);
11139        return !asecPath.startsWith(mAsecInternalPath);
11140    }
11141
11142    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11143            PackageManagerException {
11144        if (copyRet < 0) {
11145            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11146                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11147                throw new PackageManagerException(copyRet, message);
11148            }
11149        }
11150    }
11151
11152    /**
11153     * Extract the MountService "container ID" from the full code path of an
11154     * .apk.
11155     */
11156    static String cidFromCodePath(String fullCodePath) {
11157        int eidx = fullCodePath.lastIndexOf("/");
11158        String subStr1 = fullCodePath.substring(0, eidx);
11159        int sidx = subStr1.lastIndexOf("/");
11160        return subStr1.substring(sidx+1, eidx);
11161    }
11162
11163    /**
11164     * Logic to handle installation of ASEC applications, including copying and
11165     * renaming logic.
11166     */
11167    class AsecInstallArgs extends InstallArgs {
11168        static final String RES_FILE_NAME = "pkg.apk";
11169        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11170
11171        String cid;
11172        String packagePath;
11173        String resourcePath;
11174
11175        /** New install */
11176        AsecInstallArgs(InstallParams params) {
11177            super(params.origin, params.move, params.observer, params.installFlags,
11178                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11179                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11180                    params.grantedRuntimePermissions);
11181        }
11182
11183        /** Existing install */
11184        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11185                        boolean isExternal, boolean isForwardLocked) {
11186            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11187                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11188                    instructionSets, null, null);
11189            // Hackily pretend we're still looking at a full code path
11190            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11191                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11192            }
11193
11194            // Extract cid from fullCodePath
11195            int eidx = fullCodePath.lastIndexOf("/");
11196            String subStr1 = fullCodePath.substring(0, eidx);
11197            int sidx = subStr1.lastIndexOf("/");
11198            cid = subStr1.substring(sidx+1, eidx);
11199            setMountPath(subStr1);
11200        }
11201
11202        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11203            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11204                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11205                    instructionSets, null, null);
11206            this.cid = cid;
11207            setMountPath(PackageHelper.getSdDir(cid));
11208        }
11209
11210        void createCopyFile() {
11211            cid = mInstallerService.allocateExternalStageCidLegacy();
11212        }
11213
11214        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11215            if (origin.staged) {
11216                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11217                cid = origin.cid;
11218                setMountPath(PackageHelper.getSdDir(cid));
11219                return PackageManager.INSTALL_SUCCEEDED;
11220            }
11221
11222            if (temp) {
11223                createCopyFile();
11224            } else {
11225                /*
11226                 * Pre-emptively destroy the container since it's destroyed if
11227                 * copying fails due to it existing anyway.
11228                 */
11229                PackageHelper.destroySdDir(cid);
11230            }
11231
11232            final String newMountPath = imcs.copyPackageToContainer(
11233                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11234                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11235
11236            if (newMountPath != null) {
11237                setMountPath(newMountPath);
11238                return PackageManager.INSTALL_SUCCEEDED;
11239            } else {
11240                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11241            }
11242        }
11243
11244        @Override
11245        String getCodePath() {
11246            return packagePath;
11247        }
11248
11249        @Override
11250        String getResourcePath() {
11251            return resourcePath;
11252        }
11253
11254        int doPreInstall(int status) {
11255            if (status != PackageManager.INSTALL_SUCCEEDED) {
11256                // Destroy container
11257                PackageHelper.destroySdDir(cid);
11258            } else {
11259                boolean mounted = PackageHelper.isContainerMounted(cid);
11260                if (!mounted) {
11261                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11262                            Process.SYSTEM_UID);
11263                    if (newMountPath != null) {
11264                        setMountPath(newMountPath);
11265                    } else {
11266                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11267                    }
11268                }
11269            }
11270            return status;
11271        }
11272
11273        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11274            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11275            String newMountPath = null;
11276            if (PackageHelper.isContainerMounted(cid)) {
11277                // Unmount the container
11278                if (!PackageHelper.unMountSdDir(cid)) {
11279                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11280                    return false;
11281                }
11282            }
11283            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11284                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11285                        " which might be stale. Will try to clean up.");
11286                // Clean up the stale container and proceed to recreate.
11287                if (!PackageHelper.destroySdDir(newCacheId)) {
11288                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11289                    return false;
11290                }
11291                // Successfully cleaned up stale container. Try to rename again.
11292                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11293                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11294                            + " inspite of cleaning it up.");
11295                    return false;
11296                }
11297            }
11298            if (!PackageHelper.isContainerMounted(newCacheId)) {
11299                Slog.w(TAG, "Mounting container " + newCacheId);
11300                newMountPath = PackageHelper.mountSdDir(newCacheId,
11301                        getEncryptKey(), Process.SYSTEM_UID);
11302            } else {
11303                newMountPath = PackageHelper.getSdDir(newCacheId);
11304            }
11305            if (newMountPath == null) {
11306                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11307                return false;
11308            }
11309            Log.i(TAG, "Succesfully renamed " + cid +
11310                    " to " + newCacheId +
11311                    " at new path: " + newMountPath);
11312            cid = newCacheId;
11313
11314            final File beforeCodeFile = new File(packagePath);
11315            setMountPath(newMountPath);
11316            final File afterCodeFile = new File(packagePath);
11317
11318            // Reflect the rename in scanned details
11319            pkg.codePath = afterCodeFile.getAbsolutePath();
11320            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11321                    pkg.baseCodePath);
11322            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11323                    pkg.splitCodePaths);
11324
11325            // Reflect the rename in app info
11326            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11327            pkg.applicationInfo.setCodePath(pkg.codePath);
11328            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11329            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11330            pkg.applicationInfo.setResourcePath(pkg.codePath);
11331            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11332            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11333
11334            return true;
11335        }
11336
11337        private void setMountPath(String mountPath) {
11338            final File mountFile = new File(mountPath);
11339
11340            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11341            if (monolithicFile.exists()) {
11342                packagePath = monolithicFile.getAbsolutePath();
11343                if (isFwdLocked()) {
11344                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11345                } else {
11346                    resourcePath = packagePath;
11347                }
11348            } else {
11349                packagePath = mountFile.getAbsolutePath();
11350                resourcePath = packagePath;
11351            }
11352        }
11353
11354        int doPostInstall(int status, int uid) {
11355            if (status != PackageManager.INSTALL_SUCCEEDED) {
11356                cleanUp();
11357            } else {
11358                final int groupOwner;
11359                final String protectedFile;
11360                if (isFwdLocked()) {
11361                    groupOwner = UserHandle.getSharedAppGid(uid);
11362                    protectedFile = RES_FILE_NAME;
11363                } else {
11364                    groupOwner = -1;
11365                    protectedFile = null;
11366                }
11367
11368                if (uid < Process.FIRST_APPLICATION_UID
11369                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11370                    Slog.e(TAG, "Failed to finalize " + cid);
11371                    PackageHelper.destroySdDir(cid);
11372                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11373                }
11374
11375                boolean mounted = PackageHelper.isContainerMounted(cid);
11376                if (!mounted) {
11377                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11378                }
11379            }
11380            return status;
11381        }
11382
11383        private void cleanUp() {
11384            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11385
11386            // Destroy secure container
11387            PackageHelper.destroySdDir(cid);
11388        }
11389
11390        private List<String> getAllCodePaths() {
11391            final File codeFile = new File(getCodePath());
11392            if (codeFile != null && codeFile.exists()) {
11393                try {
11394                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11395                    return pkg.getAllCodePaths();
11396                } catch (PackageParserException e) {
11397                    // Ignored; we tried our best
11398                }
11399            }
11400            return Collections.EMPTY_LIST;
11401        }
11402
11403        void cleanUpResourcesLI() {
11404            // Enumerate all code paths before deleting
11405            cleanUpResourcesLI(getAllCodePaths());
11406        }
11407
11408        private void cleanUpResourcesLI(List<String> allCodePaths) {
11409            cleanUp();
11410            removeDexFiles(allCodePaths, instructionSets);
11411        }
11412
11413        String getPackageName() {
11414            return getAsecPackageName(cid);
11415        }
11416
11417        boolean doPostDeleteLI(boolean delete) {
11418            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11419            final List<String> allCodePaths = getAllCodePaths();
11420            boolean mounted = PackageHelper.isContainerMounted(cid);
11421            if (mounted) {
11422                // Unmount first
11423                if (PackageHelper.unMountSdDir(cid)) {
11424                    mounted = false;
11425                }
11426            }
11427            if (!mounted && delete) {
11428                cleanUpResourcesLI(allCodePaths);
11429            }
11430            return !mounted;
11431        }
11432
11433        @Override
11434        int doPreCopy() {
11435            if (isFwdLocked()) {
11436                if (!PackageHelper.fixSdPermissions(cid,
11437                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11438                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11439                }
11440            }
11441
11442            return PackageManager.INSTALL_SUCCEEDED;
11443        }
11444
11445        @Override
11446        int doPostCopy(int uid) {
11447            if (isFwdLocked()) {
11448                if (uid < Process.FIRST_APPLICATION_UID
11449                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11450                                RES_FILE_NAME)) {
11451                    Slog.e(TAG, "Failed to finalize " + cid);
11452                    PackageHelper.destroySdDir(cid);
11453                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11454                }
11455            }
11456
11457            return PackageManager.INSTALL_SUCCEEDED;
11458        }
11459    }
11460
11461    /**
11462     * Logic to handle movement of existing installed applications.
11463     */
11464    class MoveInstallArgs extends InstallArgs {
11465        private File codeFile;
11466        private File resourceFile;
11467
11468        /** New install */
11469        MoveInstallArgs(InstallParams params) {
11470            super(params.origin, params.move, params.observer, params.installFlags,
11471                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11472                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11473                    params.grantedRuntimePermissions);
11474        }
11475
11476        int copyApk(IMediaContainerService imcs, boolean temp) {
11477            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11478                    + move.fromUuid + " to " + move.toUuid);
11479            synchronized (mInstaller) {
11480                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11481                        move.dataAppName, move.appId, move.seinfo) != 0) {
11482                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11483                }
11484            }
11485
11486            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11487            resourceFile = codeFile;
11488            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11489
11490            return PackageManager.INSTALL_SUCCEEDED;
11491        }
11492
11493        int doPreInstall(int status) {
11494            if (status != PackageManager.INSTALL_SUCCEEDED) {
11495                cleanUp(move.toUuid);
11496            }
11497            return status;
11498        }
11499
11500        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11501            if (status != PackageManager.INSTALL_SUCCEEDED) {
11502                cleanUp(move.toUuid);
11503                return false;
11504            }
11505
11506            // Reflect the move in app info
11507            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11508            pkg.applicationInfo.setCodePath(pkg.codePath);
11509            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11510            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11511            pkg.applicationInfo.setResourcePath(pkg.codePath);
11512            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11513            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11514
11515            return true;
11516        }
11517
11518        int doPostInstall(int status, int uid) {
11519            if (status == PackageManager.INSTALL_SUCCEEDED) {
11520                cleanUp(move.fromUuid);
11521            } else {
11522                cleanUp(move.toUuid);
11523            }
11524            return status;
11525        }
11526
11527        @Override
11528        String getCodePath() {
11529            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11530        }
11531
11532        @Override
11533        String getResourcePath() {
11534            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11535        }
11536
11537        private boolean cleanUp(String volumeUuid) {
11538            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11539                    move.dataAppName);
11540            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11541            synchronized (mInstallLock) {
11542                // Clean up both app data and code
11543                removeDataDirsLI(volumeUuid, move.packageName);
11544                if (codeFile.isDirectory()) {
11545                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11546                } else {
11547                    codeFile.delete();
11548                }
11549            }
11550            return true;
11551        }
11552
11553        void cleanUpResourcesLI() {
11554            throw new UnsupportedOperationException();
11555        }
11556
11557        boolean doPostDeleteLI(boolean delete) {
11558            throw new UnsupportedOperationException();
11559        }
11560    }
11561
11562    static String getAsecPackageName(String packageCid) {
11563        int idx = packageCid.lastIndexOf("-");
11564        if (idx == -1) {
11565            return packageCid;
11566        }
11567        return packageCid.substring(0, idx);
11568    }
11569
11570    // Utility method used to create code paths based on package name and available index.
11571    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11572        String idxStr = "";
11573        int idx = 1;
11574        // Fall back to default value of idx=1 if prefix is not
11575        // part of oldCodePath
11576        if (oldCodePath != null) {
11577            String subStr = oldCodePath;
11578            // Drop the suffix right away
11579            if (suffix != null && subStr.endsWith(suffix)) {
11580                subStr = subStr.substring(0, subStr.length() - suffix.length());
11581            }
11582            // If oldCodePath already contains prefix find out the
11583            // ending index to either increment or decrement.
11584            int sidx = subStr.lastIndexOf(prefix);
11585            if (sidx != -1) {
11586                subStr = subStr.substring(sidx + prefix.length());
11587                if (subStr != null) {
11588                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11589                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11590                    }
11591                    try {
11592                        idx = Integer.parseInt(subStr);
11593                        if (idx <= 1) {
11594                            idx++;
11595                        } else {
11596                            idx--;
11597                        }
11598                    } catch(NumberFormatException e) {
11599                    }
11600                }
11601            }
11602        }
11603        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11604        return prefix + idxStr;
11605    }
11606
11607    private File getNextCodePath(File targetDir, String packageName) {
11608        int suffix = 1;
11609        File result;
11610        do {
11611            result = new File(targetDir, packageName + "-" + suffix);
11612            suffix++;
11613        } while (result.exists());
11614        return result;
11615    }
11616
11617    // Utility method that returns the relative package path with respect
11618    // to the installation directory. Like say for /data/data/com.test-1.apk
11619    // string com.test-1 is returned.
11620    static String deriveCodePathName(String codePath) {
11621        if (codePath == null) {
11622            return null;
11623        }
11624        final File codeFile = new File(codePath);
11625        final String name = codeFile.getName();
11626        if (codeFile.isDirectory()) {
11627            return name;
11628        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11629            final int lastDot = name.lastIndexOf('.');
11630            return name.substring(0, lastDot);
11631        } else {
11632            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11633            return null;
11634        }
11635    }
11636
11637    class PackageInstalledInfo {
11638        String name;
11639        int uid;
11640        // The set of users that originally had this package installed.
11641        int[] origUsers;
11642        // The set of users that now have this package installed.
11643        int[] newUsers;
11644        PackageParser.Package pkg;
11645        int returnCode;
11646        String returnMsg;
11647        PackageRemovedInfo removedInfo;
11648
11649        public void setError(int code, String msg) {
11650            returnCode = code;
11651            returnMsg = msg;
11652            Slog.w(TAG, msg);
11653        }
11654
11655        public void setError(String msg, PackageParserException e) {
11656            returnCode = e.error;
11657            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11658            Slog.w(TAG, msg, e);
11659        }
11660
11661        public void setError(String msg, PackageManagerException e) {
11662            returnCode = e.error;
11663            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11664            Slog.w(TAG, msg, e);
11665        }
11666
11667        // In some error cases we want to convey more info back to the observer
11668        String origPackage;
11669        String origPermission;
11670    }
11671
11672    /*
11673     * Install a non-existing package.
11674     */
11675    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11676            UserHandle user, String installerPackageName, String volumeUuid,
11677            PackageInstalledInfo res) {
11678        // Remember this for later, in case we need to rollback this install
11679        String pkgName = pkg.packageName;
11680
11681        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11682        final boolean dataDirExists = Environment
11683                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11684        synchronized(mPackages) {
11685            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11686                // A package with the same name is already installed, though
11687                // it has been renamed to an older name.  The package we
11688                // are trying to install should be installed as an update to
11689                // the existing one, but that has not been requested, so bail.
11690                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11691                        + " without first uninstalling package running as "
11692                        + mSettings.mRenamedPackages.get(pkgName));
11693                return;
11694            }
11695            if (mPackages.containsKey(pkgName)) {
11696                // Don't allow installation over an existing package with the same name.
11697                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11698                        + " without first uninstalling.");
11699                return;
11700            }
11701        }
11702
11703        try {
11704            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11705                    System.currentTimeMillis(), user);
11706
11707            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11708            // delete the partially installed application. the data directory will have to be
11709            // restored if it was already existing
11710            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11711                // remove package from internal structures.  Note that we want deletePackageX to
11712                // delete the package data and cache directories that it created in
11713                // scanPackageLocked, unless those directories existed before we even tried to
11714                // install.
11715                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11716                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11717                                res.removedInfo, true);
11718            }
11719
11720        } catch (PackageManagerException e) {
11721            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11722        }
11723    }
11724
11725    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11726        // Can't rotate keys during boot or if sharedUser.
11727        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11728                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11729            return false;
11730        }
11731        // app is using upgradeKeySets; make sure all are valid
11732        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11733        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11734        for (int i = 0; i < upgradeKeySets.length; i++) {
11735            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11736                Slog.wtf(TAG, "Package "
11737                         + (oldPs.name != null ? oldPs.name : "<null>")
11738                         + " contains upgrade-key-set reference to unknown key-set: "
11739                         + upgradeKeySets[i]
11740                         + " reverting to signatures check.");
11741                return false;
11742            }
11743        }
11744        return true;
11745    }
11746
11747    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11748        // Upgrade keysets are being used.  Determine if new package has a superset of the
11749        // required keys.
11750        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11751        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11752        for (int i = 0; i < upgradeKeySets.length; i++) {
11753            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11754            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11755                return true;
11756            }
11757        }
11758        return false;
11759    }
11760
11761    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11762            UserHandle user, String installerPackageName, String volumeUuid,
11763            PackageInstalledInfo res) {
11764        final PackageParser.Package oldPackage;
11765        final String pkgName = pkg.packageName;
11766        final int[] allUsers;
11767        final boolean[] perUserInstalled;
11768
11769        // First find the old package info and check signatures
11770        synchronized(mPackages) {
11771            oldPackage = mPackages.get(pkgName);
11772            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11773            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11774            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11775                if(!checkUpgradeKeySetLP(ps, pkg)) {
11776                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11777                            "New package not signed by keys specified by upgrade-keysets: "
11778                            + pkgName);
11779                    return;
11780                }
11781            } else {
11782                // default to original signature matching
11783                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11784                    != PackageManager.SIGNATURE_MATCH) {
11785                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11786                            "New package has a different signature: " + pkgName);
11787                    return;
11788                }
11789            }
11790
11791            // In case of rollback, remember per-user/profile install state
11792            allUsers = sUserManager.getUserIds();
11793            perUserInstalled = new boolean[allUsers.length];
11794            for (int i = 0; i < allUsers.length; i++) {
11795                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11796            }
11797        }
11798
11799        boolean sysPkg = (isSystemApp(oldPackage));
11800        if (sysPkg) {
11801            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11802                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11803        } else {
11804            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11805                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11806        }
11807    }
11808
11809    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11810            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11811            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11812            String volumeUuid, PackageInstalledInfo res) {
11813        String pkgName = deletedPackage.packageName;
11814        boolean deletedPkg = true;
11815        boolean updatedSettings = false;
11816
11817        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11818                + deletedPackage);
11819        long origUpdateTime;
11820        if (pkg.mExtras != null) {
11821            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11822        } else {
11823            origUpdateTime = 0;
11824        }
11825
11826        // First delete the existing package while retaining the data directory
11827        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11828                res.removedInfo, true)) {
11829            // If the existing package wasn't successfully deleted
11830            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11831            deletedPkg = false;
11832        } else {
11833            // Successfully deleted the old package; proceed with replace.
11834
11835            // If deleted package lived in a container, give users a chance to
11836            // relinquish resources before killing.
11837            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11838                if (DEBUG_INSTALL) {
11839                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11840                }
11841                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11842                final ArrayList<String> pkgList = new ArrayList<String>(1);
11843                pkgList.add(deletedPackage.applicationInfo.packageName);
11844                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11845            }
11846
11847            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11848            try {
11849                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11850                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11851                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11852                        perUserInstalled, res, user);
11853                updatedSettings = true;
11854            } catch (PackageManagerException e) {
11855                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11856            }
11857        }
11858
11859        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11860            // remove package from internal structures.  Note that we want deletePackageX to
11861            // delete the package data and cache directories that it created in
11862            // scanPackageLocked, unless those directories existed before we even tried to
11863            // install.
11864            if(updatedSettings) {
11865                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11866                deletePackageLI(
11867                        pkgName, null, true, allUsers, perUserInstalled,
11868                        PackageManager.DELETE_KEEP_DATA,
11869                                res.removedInfo, true);
11870            }
11871            // Since we failed to install the new package we need to restore the old
11872            // package that we deleted.
11873            if (deletedPkg) {
11874                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11875                File restoreFile = new File(deletedPackage.codePath);
11876                // Parse old package
11877                boolean oldExternal = isExternal(deletedPackage);
11878                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11879                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11880                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11881                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11882                try {
11883                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11884                } catch (PackageManagerException e) {
11885                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11886                            + e.getMessage());
11887                    return;
11888                }
11889                // Restore of old package succeeded. Update permissions.
11890                // writer
11891                synchronized (mPackages) {
11892                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11893                            UPDATE_PERMISSIONS_ALL);
11894                    // can downgrade to reader
11895                    mSettings.writeLPr();
11896                }
11897                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11898            }
11899        }
11900    }
11901
11902    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11903            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11904            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11905            String volumeUuid, PackageInstalledInfo res) {
11906        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11907                + ", old=" + deletedPackage);
11908        boolean disabledSystem = false;
11909        boolean updatedSettings = false;
11910        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11911        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11912                != 0) {
11913            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11914        }
11915        String packageName = deletedPackage.packageName;
11916        if (packageName == null) {
11917            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11918                    "Attempt to delete null packageName.");
11919            return;
11920        }
11921        PackageParser.Package oldPkg;
11922        PackageSetting oldPkgSetting;
11923        // reader
11924        synchronized (mPackages) {
11925            oldPkg = mPackages.get(packageName);
11926            oldPkgSetting = mSettings.mPackages.get(packageName);
11927            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11928                    (oldPkgSetting == null)) {
11929                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11930                        "Couldn't find package:" + packageName + " information");
11931                return;
11932            }
11933        }
11934
11935        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11936
11937        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11938        res.removedInfo.removedPackage = packageName;
11939        // Remove existing system package
11940        removePackageLI(oldPkgSetting, true);
11941        // writer
11942        synchronized (mPackages) {
11943            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11944            if (!disabledSystem && deletedPackage != null) {
11945                // We didn't need to disable the .apk as a current system package,
11946                // which means we are replacing another update that is already
11947                // installed.  We need to make sure to delete the older one's .apk.
11948                res.removedInfo.args = createInstallArgsForExisting(0,
11949                        deletedPackage.applicationInfo.getCodePath(),
11950                        deletedPackage.applicationInfo.getResourcePath(),
11951                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11952            } else {
11953                res.removedInfo.args = null;
11954            }
11955        }
11956
11957        // Successfully disabled the old package. Now proceed with re-installation
11958        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11959
11960        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11961        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11962
11963        PackageParser.Package newPackage = null;
11964        try {
11965            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11966            if (newPackage.mExtras != null) {
11967                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11968                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11969                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11970
11971                // is the update attempting to change shared user? that isn't going to work...
11972                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11973                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11974                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11975                            + " to " + newPkgSetting.sharedUser);
11976                    updatedSettings = true;
11977                }
11978            }
11979
11980            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11981                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11982                        perUserInstalled, res, user);
11983                updatedSettings = true;
11984            }
11985
11986        } catch (PackageManagerException e) {
11987            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11988        }
11989
11990        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11991            // Re installation failed. Restore old information
11992            // Remove new pkg information
11993            if (newPackage != null) {
11994                removeInstalledPackageLI(newPackage, true);
11995            }
11996            // Add back the old system package
11997            try {
11998                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11999            } catch (PackageManagerException e) {
12000                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12001            }
12002            // Restore the old system information in Settings
12003            synchronized (mPackages) {
12004                if (disabledSystem) {
12005                    mSettings.enableSystemPackageLPw(packageName);
12006                }
12007                if (updatedSettings) {
12008                    mSettings.setInstallerPackageName(packageName,
12009                            oldPkgSetting.installerPackageName);
12010                }
12011                mSettings.writeLPr();
12012            }
12013        }
12014    }
12015
12016    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12017            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12018            UserHandle user) {
12019        String pkgName = newPackage.packageName;
12020        synchronized (mPackages) {
12021            //write settings. the installStatus will be incomplete at this stage.
12022            //note that the new package setting would have already been
12023            //added to mPackages. It hasn't been persisted yet.
12024            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12025            mSettings.writeLPr();
12026        }
12027
12028        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12029
12030        synchronized (mPackages) {
12031            updatePermissionsLPw(newPackage.packageName, newPackage,
12032                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12033                            ? UPDATE_PERMISSIONS_ALL : 0));
12034            // For system-bundled packages, we assume that installing an upgraded version
12035            // of the package implies that the user actually wants to run that new code,
12036            // so we enable the package.
12037            PackageSetting ps = mSettings.mPackages.get(pkgName);
12038            if (ps != null) {
12039                if (isSystemApp(newPackage)) {
12040                    // NB: implicit assumption that system package upgrades apply to all users
12041                    if (DEBUG_INSTALL) {
12042                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12043                    }
12044                    if (res.origUsers != null) {
12045                        for (int userHandle : res.origUsers) {
12046                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12047                                    userHandle, installerPackageName);
12048                        }
12049                    }
12050                    // Also convey the prior install/uninstall state
12051                    if (allUsers != null && perUserInstalled != null) {
12052                        for (int i = 0; i < allUsers.length; i++) {
12053                            if (DEBUG_INSTALL) {
12054                                Slog.d(TAG, "    user " + allUsers[i]
12055                                        + " => " + perUserInstalled[i]);
12056                            }
12057                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12058                        }
12059                        // these install state changes will be persisted in the
12060                        // upcoming call to mSettings.writeLPr().
12061                    }
12062                }
12063                // It's implied that when a user requests installation, they want the app to be
12064                // installed and enabled.
12065                int userId = user.getIdentifier();
12066                if (userId != UserHandle.USER_ALL) {
12067                    ps.setInstalled(true, userId);
12068                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12069                }
12070            }
12071            res.name = pkgName;
12072            res.uid = newPackage.applicationInfo.uid;
12073            res.pkg = newPackage;
12074            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12075            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12076            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12077            //to update install status
12078            mSettings.writeLPr();
12079        }
12080    }
12081
12082    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12083        final int installFlags = args.installFlags;
12084        final String installerPackageName = args.installerPackageName;
12085        final String volumeUuid = args.volumeUuid;
12086        final File tmpPackageFile = new File(args.getCodePath());
12087        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12088        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12089                || (args.volumeUuid != null));
12090        boolean replace = false;
12091        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12092        if (args.move != null) {
12093            // moving a complete application; perfom an initial scan on the new install location
12094            scanFlags |= SCAN_INITIAL;
12095        }
12096        // Result object to be returned
12097        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12098
12099        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12100        // Retrieve PackageSettings and parse package
12101        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12102                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12103                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12104        PackageParser pp = new PackageParser();
12105        pp.setSeparateProcesses(mSeparateProcesses);
12106        pp.setDisplayMetrics(mMetrics);
12107
12108        final PackageParser.Package pkg;
12109        try {
12110            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12111        } catch (PackageParserException e) {
12112            res.setError("Failed parse during installPackageLI", e);
12113            return;
12114        }
12115
12116        // Mark that we have an install time CPU ABI override.
12117        pkg.cpuAbiOverride = args.abiOverride;
12118
12119        String pkgName = res.name = pkg.packageName;
12120        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12121            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12122                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12123                return;
12124            }
12125        }
12126
12127        try {
12128            pp.collectCertificates(pkg, parseFlags);
12129            pp.collectManifestDigest(pkg);
12130        } catch (PackageParserException e) {
12131            res.setError("Failed collect during installPackageLI", e);
12132            return;
12133        }
12134
12135        /* If the installer passed in a manifest digest, compare it now. */
12136        if (args.manifestDigest != null) {
12137            if (DEBUG_INSTALL) {
12138                final String parsedManifest = pkg.manifestDigest == null ? "null"
12139                        : pkg.manifestDigest.toString();
12140                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12141                        + parsedManifest);
12142            }
12143
12144            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12145                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12146                return;
12147            }
12148        } else if (DEBUG_INSTALL) {
12149            final String parsedManifest = pkg.manifestDigest == null
12150                    ? "null" : pkg.manifestDigest.toString();
12151            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12152        }
12153
12154        // Get rid of all references to package scan path via parser.
12155        pp = null;
12156        String oldCodePath = null;
12157        boolean systemApp = false;
12158        synchronized (mPackages) {
12159            // Check if installing already existing package
12160            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12161                String oldName = mSettings.mRenamedPackages.get(pkgName);
12162                if (pkg.mOriginalPackages != null
12163                        && pkg.mOriginalPackages.contains(oldName)
12164                        && mPackages.containsKey(oldName)) {
12165                    // This package is derived from an original package,
12166                    // and this device has been updating from that original
12167                    // name.  We must continue using the original name, so
12168                    // rename the new package here.
12169                    pkg.setPackageName(oldName);
12170                    pkgName = pkg.packageName;
12171                    replace = true;
12172                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12173                            + oldName + " pkgName=" + pkgName);
12174                } else if (mPackages.containsKey(pkgName)) {
12175                    // This package, under its official name, already exists
12176                    // on the device; we should replace it.
12177                    replace = true;
12178                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12179                }
12180
12181                // Prevent apps opting out from runtime permissions
12182                if (replace) {
12183                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12184                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12185                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12186                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12187                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12188                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12189                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12190                                        + " doesn't support runtime permissions but the old"
12191                                        + " target SDK " + oldTargetSdk + " does.");
12192                        return;
12193                    }
12194                }
12195            }
12196
12197            PackageSetting ps = mSettings.mPackages.get(pkgName);
12198            if (ps != null) {
12199                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12200
12201                // Quick sanity check that we're signed correctly if updating;
12202                // we'll check this again later when scanning, but we want to
12203                // bail early here before tripping over redefined permissions.
12204                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12205                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12206                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12207                                + pkg.packageName + " upgrade keys do not match the "
12208                                + "previously installed version");
12209                        return;
12210                    }
12211                } else {
12212                    try {
12213                        verifySignaturesLP(ps, pkg);
12214                    } catch (PackageManagerException e) {
12215                        res.setError(e.error, e.getMessage());
12216                        return;
12217                    }
12218                }
12219
12220                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12221                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12222                    systemApp = (ps.pkg.applicationInfo.flags &
12223                            ApplicationInfo.FLAG_SYSTEM) != 0;
12224                }
12225                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12226            }
12227
12228            // Check whether the newly-scanned package wants to define an already-defined perm
12229            int N = pkg.permissions.size();
12230            for (int i = N-1; i >= 0; i--) {
12231                PackageParser.Permission perm = pkg.permissions.get(i);
12232                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12233                if (bp != null) {
12234                    // If the defining package is signed with our cert, it's okay.  This
12235                    // also includes the "updating the same package" case, of course.
12236                    // "updating same package" could also involve key-rotation.
12237                    final boolean sigsOk;
12238                    if (bp.sourcePackage.equals(pkg.packageName)
12239                            && (bp.packageSetting instanceof PackageSetting)
12240                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12241                                    scanFlags))) {
12242                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12243                    } else {
12244                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12245                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12246                    }
12247                    if (!sigsOk) {
12248                        // If the owning package is the system itself, we log but allow
12249                        // install to proceed; we fail the install on all other permission
12250                        // redefinitions.
12251                        if (!bp.sourcePackage.equals("android")) {
12252                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12253                                    + pkg.packageName + " attempting to redeclare permission "
12254                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12255                            res.origPermission = perm.info.name;
12256                            res.origPackage = bp.sourcePackage;
12257                            return;
12258                        } else {
12259                            Slog.w(TAG, "Package " + pkg.packageName
12260                                    + " attempting to redeclare system permission "
12261                                    + perm.info.name + "; ignoring new declaration");
12262                            pkg.permissions.remove(i);
12263                        }
12264                    }
12265                }
12266            }
12267
12268        }
12269
12270        if (systemApp && onExternal) {
12271            // Disable updates to system apps on sdcard
12272            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12273                    "Cannot install updates to system apps on sdcard");
12274            return;
12275        }
12276
12277        if (args.move != null) {
12278            // We did an in-place move, so dex is ready to roll
12279            scanFlags |= SCAN_NO_DEX;
12280            scanFlags |= SCAN_MOVE;
12281
12282            synchronized (mPackages) {
12283                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12284                if (ps == null) {
12285                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12286                            "Missing settings for moved package " + pkgName);
12287                }
12288
12289                // We moved the entire application as-is, so bring over the
12290                // previously derived ABI information.
12291                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12292                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12293            }
12294
12295        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12296            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12297            scanFlags |= SCAN_NO_DEX;
12298
12299            try {
12300                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12301                        true /* extract libs */);
12302            } catch (PackageManagerException pme) {
12303                Slog.e(TAG, "Error deriving application ABI", pme);
12304                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12305                return;
12306            }
12307
12308            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12309            int result = mPackageDexOptimizer
12310                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12311                            false /* defer */, false /* inclDependencies */);
12312            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12313                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12314                return;
12315            }
12316        }
12317
12318        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12319            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12320            return;
12321        }
12322
12323        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12324
12325        if (replace) {
12326            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12327                    installerPackageName, volumeUuid, res);
12328        } else {
12329            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12330                    args.user, installerPackageName, volumeUuid, res);
12331        }
12332        synchronized (mPackages) {
12333            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12334            if (ps != null) {
12335                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12336            }
12337        }
12338    }
12339
12340    private void startIntentFilterVerifications(int userId, boolean replacing,
12341            PackageParser.Package pkg) {
12342        if (mIntentFilterVerifierComponent == null) {
12343            Slog.w(TAG, "No IntentFilter verification will not be done as "
12344                    + "there is no IntentFilterVerifier available!");
12345            return;
12346        }
12347
12348        final int verifierUid = getPackageUid(
12349                mIntentFilterVerifierComponent.getPackageName(),
12350                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12351
12352        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12353        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12354        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12355        mHandler.sendMessage(msg);
12356    }
12357
12358    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12359            PackageParser.Package pkg) {
12360        int size = pkg.activities.size();
12361        if (size == 0) {
12362            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12363                    "No activity, so no need to verify any IntentFilter!");
12364            return;
12365        }
12366
12367        final boolean hasDomainURLs = hasDomainURLs(pkg);
12368        if (!hasDomainURLs) {
12369            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12370                    "No domain URLs, so no need to verify any IntentFilter!");
12371            return;
12372        }
12373
12374        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12375                + " if any IntentFilter from the " + size
12376                + " Activities needs verification ...");
12377
12378        int count = 0;
12379        final String packageName = pkg.packageName;
12380
12381        synchronized (mPackages) {
12382            // If this is a new install and we see that we've already run verification for this
12383            // package, we have nothing to do: it means the state was restored from backup.
12384            if (!replacing) {
12385                IntentFilterVerificationInfo ivi =
12386                        mSettings.getIntentFilterVerificationLPr(packageName);
12387                if (ivi != null) {
12388                    if (DEBUG_DOMAIN_VERIFICATION) {
12389                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12390                                + ivi.getStatusString());
12391                    }
12392                    return;
12393                }
12394            }
12395
12396            // If any filters need to be verified, then all need to be.
12397            boolean needToVerify = false;
12398            for (PackageParser.Activity a : pkg.activities) {
12399                for (ActivityIntentInfo filter : a.intents) {
12400                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12401                        if (DEBUG_DOMAIN_VERIFICATION) {
12402                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12403                        }
12404                        needToVerify = true;
12405                        break;
12406                    }
12407                }
12408            }
12409
12410            if (needToVerify) {
12411                final int verificationId = mIntentFilterVerificationToken++;
12412                for (PackageParser.Activity a : pkg.activities) {
12413                    for (ActivityIntentInfo filter : a.intents) {
12414                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12415                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12416                                    "Verification needed for IntentFilter:" + filter.toString());
12417                            mIntentFilterVerifier.addOneIntentFilterVerification(
12418                                    verifierUid, userId, verificationId, filter, packageName);
12419                            count++;
12420                        }
12421                    }
12422                }
12423            }
12424        }
12425
12426        if (count > 0) {
12427            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12428                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12429                    +  " for userId:" + userId);
12430            mIntentFilterVerifier.startVerifications(userId);
12431        } else {
12432            if (DEBUG_DOMAIN_VERIFICATION) {
12433                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12434            }
12435        }
12436    }
12437
12438    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12439        final ComponentName cn  = filter.activity.getComponentName();
12440        final String packageName = cn.getPackageName();
12441
12442        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12443                packageName);
12444        if (ivi == null) {
12445            return true;
12446        }
12447        int status = ivi.getStatus();
12448        switch (status) {
12449            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12450            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12451                return true;
12452
12453            default:
12454                // Nothing to do
12455                return false;
12456        }
12457    }
12458
12459    private static boolean isMultiArch(PackageSetting ps) {
12460        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12461    }
12462
12463    private static boolean isMultiArch(ApplicationInfo info) {
12464        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12465    }
12466
12467    private static boolean isExternal(PackageParser.Package pkg) {
12468        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12469    }
12470
12471    private static boolean isExternal(PackageSetting ps) {
12472        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12473    }
12474
12475    private static boolean isExternal(ApplicationInfo info) {
12476        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12477    }
12478
12479    private static boolean isSystemApp(PackageParser.Package pkg) {
12480        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12481    }
12482
12483    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12484        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12485    }
12486
12487    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12488        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12489    }
12490
12491    private static boolean isSystemApp(PackageSetting ps) {
12492        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12493    }
12494
12495    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12496        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12497    }
12498
12499    private int packageFlagsToInstallFlags(PackageSetting ps) {
12500        int installFlags = 0;
12501        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12502            // This existing package was an external ASEC install when we have
12503            // the external flag without a UUID
12504            installFlags |= PackageManager.INSTALL_EXTERNAL;
12505        }
12506        if (ps.isForwardLocked()) {
12507            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12508        }
12509        return installFlags;
12510    }
12511
12512    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12513        if (isExternal(pkg)) {
12514            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12515                return mSettings.getExternalVersion();
12516            } else {
12517                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12518            }
12519        } else {
12520            return mSettings.getInternalVersion();
12521        }
12522    }
12523
12524    private void deleteTempPackageFiles() {
12525        final FilenameFilter filter = new FilenameFilter() {
12526            public boolean accept(File dir, String name) {
12527                return name.startsWith("vmdl") && name.endsWith(".tmp");
12528            }
12529        };
12530        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12531            file.delete();
12532        }
12533    }
12534
12535    @Override
12536    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12537            int flags) {
12538        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12539                flags);
12540    }
12541
12542    @Override
12543    public void deletePackage(final String packageName,
12544            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12545        mContext.enforceCallingOrSelfPermission(
12546                android.Manifest.permission.DELETE_PACKAGES, null);
12547        Preconditions.checkNotNull(packageName);
12548        Preconditions.checkNotNull(observer);
12549        final int uid = Binder.getCallingUid();
12550        if (UserHandle.getUserId(uid) != userId) {
12551            mContext.enforceCallingPermission(
12552                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12553                    "deletePackage for user " + userId);
12554        }
12555        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12556            try {
12557                observer.onPackageDeleted(packageName,
12558                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12559            } catch (RemoteException re) {
12560            }
12561            return;
12562        }
12563
12564        boolean uninstallBlocked = false;
12565        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12566            int[] users = sUserManager.getUserIds();
12567            for (int i = 0; i < users.length; ++i) {
12568                if (getBlockUninstallForUser(packageName, users[i])) {
12569                    uninstallBlocked = true;
12570                    break;
12571                }
12572            }
12573        } else {
12574            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12575        }
12576        if (uninstallBlocked) {
12577            try {
12578                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12579                        null);
12580            } catch (RemoteException re) {
12581            }
12582            return;
12583        }
12584
12585        if (DEBUG_REMOVE) {
12586            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12587        }
12588        // Queue up an async operation since the package deletion may take a little while.
12589        mHandler.post(new Runnable() {
12590            public void run() {
12591                mHandler.removeCallbacks(this);
12592                final int returnCode = deletePackageX(packageName, userId, flags);
12593                if (observer != null) {
12594                    try {
12595                        observer.onPackageDeleted(packageName, returnCode, null);
12596                    } catch (RemoteException e) {
12597                        Log.i(TAG, "Observer no longer exists.");
12598                    } //end catch
12599                } //end if
12600            } //end run
12601        });
12602    }
12603
12604    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12605        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12606                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12607        try {
12608            if (dpm != null) {
12609                if (dpm.isDeviceOwner(packageName)) {
12610                    return true;
12611                }
12612                int[] users;
12613                if (userId == UserHandle.USER_ALL) {
12614                    users = sUserManager.getUserIds();
12615                } else {
12616                    users = new int[]{userId};
12617                }
12618                for (int i = 0; i < users.length; ++i) {
12619                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12620                        return true;
12621                    }
12622                }
12623            }
12624        } catch (RemoteException e) {
12625        }
12626        return false;
12627    }
12628
12629    /**
12630     *  This method is an internal method that could be get invoked either
12631     *  to delete an installed package or to clean up a failed installation.
12632     *  After deleting an installed package, a broadcast is sent to notify any
12633     *  listeners that the package has been installed. For cleaning up a failed
12634     *  installation, the broadcast is not necessary since the package's
12635     *  installation wouldn't have sent the initial broadcast either
12636     *  The key steps in deleting a package are
12637     *  deleting the package information in internal structures like mPackages,
12638     *  deleting the packages base directories through installd
12639     *  updating mSettings to reflect current status
12640     *  persisting settings for later use
12641     *  sending a broadcast if necessary
12642     */
12643    private int deletePackageX(String packageName, int userId, int flags) {
12644        final PackageRemovedInfo info = new PackageRemovedInfo();
12645        final boolean res;
12646
12647        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12648                ? UserHandle.ALL : new UserHandle(userId);
12649
12650        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12651            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12652            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12653        }
12654
12655        boolean removedForAllUsers = false;
12656        boolean systemUpdate = false;
12657
12658        // for the uninstall-updates case and restricted profiles, remember the per-
12659        // userhandle installed state
12660        int[] allUsers;
12661        boolean[] perUserInstalled;
12662        synchronized (mPackages) {
12663            PackageSetting ps = mSettings.mPackages.get(packageName);
12664            allUsers = sUserManager.getUserIds();
12665            perUserInstalled = new boolean[allUsers.length];
12666            for (int i = 0; i < allUsers.length; i++) {
12667                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12668            }
12669        }
12670
12671        synchronized (mInstallLock) {
12672            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12673            res = deletePackageLI(packageName, removeForUser,
12674                    true, allUsers, perUserInstalled,
12675                    flags | REMOVE_CHATTY, info, true);
12676            systemUpdate = info.isRemovedPackageSystemUpdate;
12677            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12678                removedForAllUsers = true;
12679            }
12680            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12681                    + " removedForAllUsers=" + removedForAllUsers);
12682        }
12683
12684        if (res) {
12685            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12686
12687            // If the removed package was a system update, the old system package
12688            // was re-enabled; we need to broadcast this information
12689            if (systemUpdate) {
12690                Bundle extras = new Bundle(1);
12691                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12692                        ? info.removedAppId : info.uid);
12693                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12694
12695                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12696                        extras, null, null, null);
12697                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12698                        extras, null, null, null);
12699                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12700                        null, packageName, null, null);
12701            }
12702        }
12703        // Force a gc here.
12704        Runtime.getRuntime().gc();
12705        // Delete the resources here after sending the broadcast to let
12706        // other processes clean up before deleting resources.
12707        if (info.args != null) {
12708            synchronized (mInstallLock) {
12709                info.args.doPostDeleteLI(true);
12710            }
12711        }
12712
12713        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12714    }
12715
12716    class PackageRemovedInfo {
12717        String removedPackage;
12718        int uid = -1;
12719        int removedAppId = -1;
12720        int[] removedUsers = null;
12721        boolean isRemovedPackageSystemUpdate = false;
12722        // Clean up resources deleted packages.
12723        InstallArgs args = null;
12724
12725        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12726            Bundle extras = new Bundle(1);
12727            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12728            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12729            if (replacing) {
12730                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12731            }
12732            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12733            if (removedPackage != null) {
12734                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12735                        extras, null, null, removedUsers);
12736                if (fullRemove && !replacing) {
12737                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12738                            extras, null, null, removedUsers);
12739                }
12740            }
12741            if (removedAppId >= 0) {
12742                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12743                        removedUsers);
12744            }
12745        }
12746    }
12747
12748    /*
12749     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12750     * flag is not set, the data directory is removed as well.
12751     * make sure this flag is set for partially installed apps. If not its meaningless to
12752     * delete a partially installed application.
12753     */
12754    private void removePackageDataLI(PackageSetting ps,
12755            int[] allUserHandles, boolean[] perUserInstalled,
12756            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12757        String packageName = ps.name;
12758        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12759        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12760        // Retrieve object to delete permissions for shared user later on
12761        final PackageSetting deletedPs;
12762        // reader
12763        synchronized (mPackages) {
12764            deletedPs = mSettings.mPackages.get(packageName);
12765            if (outInfo != null) {
12766                outInfo.removedPackage = packageName;
12767                outInfo.removedUsers = deletedPs != null
12768                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12769                        : null;
12770            }
12771        }
12772        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12773            removeDataDirsLI(ps.volumeUuid, packageName);
12774            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12775        }
12776        // writer
12777        synchronized (mPackages) {
12778            if (deletedPs != null) {
12779                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12780                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12781                    clearDefaultBrowserIfNeeded(packageName);
12782                    if (outInfo != null) {
12783                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12784                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12785                    }
12786                    updatePermissionsLPw(deletedPs.name, null, 0);
12787                    if (deletedPs.sharedUser != null) {
12788                        // Remove permissions associated with package. Since runtime
12789                        // permissions are per user we have to kill the removed package
12790                        // or packages running under the shared user of the removed
12791                        // package if revoking the permissions requested only by the removed
12792                        // package is successful and this causes a change in gids.
12793                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12794                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12795                                    userId);
12796                            if (userIdToKill == UserHandle.USER_ALL
12797                                    || userIdToKill >= UserHandle.USER_OWNER) {
12798                                // If gids changed for this user, kill all affected packages.
12799                                mHandler.post(new Runnable() {
12800                                    @Override
12801                                    public void run() {
12802                                        // This has to happen with no lock held.
12803                                        killApplication(deletedPs.name, deletedPs.appId,
12804                                                KILL_APP_REASON_GIDS_CHANGED);
12805                                    }
12806                                });
12807                                break;
12808                            }
12809                        }
12810                    }
12811                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12812                }
12813                // make sure to preserve per-user disabled state if this removal was just
12814                // a downgrade of a system app to the factory package
12815                if (allUserHandles != null && perUserInstalled != null) {
12816                    if (DEBUG_REMOVE) {
12817                        Slog.d(TAG, "Propagating install state across downgrade");
12818                    }
12819                    for (int i = 0; i < allUserHandles.length; i++) {
12820                        if (DEBUG_REMOVE) {
12821                            Slog.d(TAG, "    user " + allUserHandles[i]
12822                                    + " => " + perUserInstalled[i]);
12823                        }
12824                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12825                    }
12826                }
12827            }
12828            // can downgrade to reader
12829            if (writeSettings) {
12830                // Save settings now
12831                mSettings.writeLPr();
12832            }
12833        }
12834        if (outInfo != null) {
12835            // A user ID was deleted here. Go through all users and remove it
12836            // from KeyStore.
12837            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12838        }
12839    }
12840
12841    static boolean locationIsPrivileged(File path) {
12842        try {
12843            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12844                    .getCanonicalPath();
12845            return path.getCanonicalPath().startsWith(privilegedAppDir);
12846        } catch (IOException e) {
12847            Slog.e(TAG, "Unable to access code path " + path);
12848        }
12849        return false;
12850    }
12851
12852    /*
12853     * Tries to delete system package.
12854     */
12855    private boolean deleteSystemPackageLI(PackageSetting newPs,
12856            int[] allUserHandles, boolean[] perUserInstalled,
12857            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12858        final boolean applyUserRestrictions
12859                = (allUserHandles != null) && (perUserInstalled != null);
12860        PackageSetting disabledPs = null;
12861        // Confirm if the system package has been updated
12862        // An updated system app can be deleted. This will also have to restore
12863        // the system pkg from system partition
12864        // reader
12865        synchronized (mPackages) {
12866            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12867        }
12868        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12869                + " disabledPs=" + disabledPs);
12870        if (disabledPs == null) {
12871            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12872            return false;
12873        } else if (DEBUG_REMOVE) {
12874            Slog.d(TAG, "Deleting system pkg from data partition");
12875        }
12876        if (DEBUG_REMOVE) {
12877            if (applyUserRestrictions) {
12878                Slog.d(TAG, "Remembering install states:");
12879                for (int i = 0; i < allUserHandles.length; i++) {
12880                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12881                }
12882            }
12883        }
12884        // Delete the updated package
12885        outInfo.isRemovedPackageSystemUpdate = true;
12886        if (disabledPs.versionCode < newPs.versionCode) {
12887            // Delete data for downgrades
12888            flags &= ~PackageManager.DELETE_KEEP_DATA;
12889        } else {
12890            // Preserve data by setting flag
12891            flags |= PackageManager.DELETE_KEEP_DATA;
12892        }
12893        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12894                allUserHandles, perUserInstalled, outInfo, writeSettings);
12895        if (!ret) {
12896            return false;
12897        }
12898        // writer
12899        synchronized (mPackages) {
12900            // Reinstate the old system package
12901            mSettings.enableSystemPackageLPw(newPs.name);
12902            // Remove any native libraries from the upgraded package.
12903            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12904        }
12905        // Install the system package
12906        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12907        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12908        if (locationIsPrivileged(disabledPs.codePath)) {
12909            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12910        }
12911
12912        final PackageParser.Package newPkg;
12913        try {
12914            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12915        } catch (PackageManagerException e) {
12916            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12917            return false;
12918        }
12919
12920        // writer
12921        synchronized (mPackages) {
12922            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12923
12924            // Propagate the permissions state as we do not want to drop on the floor
12925            // runtime permissions. The update permissions method below will take
12926            // care of removing obsolete permissions and grant install permissions.
12927            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
12928            updatePermissionsLPw(newPkg.packageName, newPkg,
12929                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12930
12931            if (applyUserRestrictions) {
12932                if (DEBUG_REMOVE) {
12933                    Slog.d(TAG, "Propagating install state across reinstall");
12934                }
12935                for (int i = 0; i < allUserHandles.length; i++) {
12936                    if (DEBUG_REMOVE) {
12937                        Slog.d(TAG, "    user " + allUserHandles[i]
12938                                + " => " + perUserInstalled[i]);
12939                    }
12940                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12941
12942                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12943                }
12944                // Regardless of writeSettings we need to ensure that this restriction
12945                // state propagation is persisted
12946                mSettings.writeAllUsersPackageRestrictionsLPr();
12947            }
12948            // can downgrade to reader here
12949            if (writeSettings) {
12950                mSettings.writeLPr();
12951            }
12952        }
12953        return true;
12954    }
12955
12956    private boolean deleteInstalledPackageLI(PackageSetting ps,
12957            boolean deleteCodeAndResources, int flags,
12958            int[] allUserHandles, boolean[] perUserInstalled,
12959            PackageRemovedInfo outInfo, boolean writeSettings) {
12960        if (outInfo != null) {
12961            outInfo.uid = ps.appId;
12962        }
12963
12964        // Delete package data from internal structures and also remove data if flag is set
12965        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12966
12967        // Delete application code and resources
12968        if (deleteCodeAndResources && (outInfo != null)) {
12969            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12970                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12971            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12972        }
12973        return true;
12974    }
12975
12976    @Override
12977    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12978            int userId) {
12979        mContext.enforceCallingOrSelfPermission(
12980                android.Manifest.permission.DELETE_PACKAGES, null);
12981        synchronized (mPackages) {
12982            PackageSetting ps = mSettings.mPackages.get(packageName);
12983            if (ps == null) {
12984                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12985                return false;
12986            }
12987            if (!ps.getInstalled(userId)) {
12988                // Can't block uninstall for an app that is not installed or enabled.
12989                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12990                return false;
12991            }
12992            ps.setBlockUninstall(blockUninstall, userId);
12993            mSettings.writePackageRestrictionsLPr(userId);
12994        }
12995        return true;
12996    }
12997
12998    @Override
12999    public boolean getBlockUninstallForUser(String packageName, int userId) {
13000        synchronized (mPackages) {
13001            PackageSetting ps = mSettings.mPackages.get(packageName);
13002            if (ps == null) {
13003                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13004                return false;
13005            }
13006            return ps.getBlockUninstall(userId);
13007        }
13008    }
13009
13010    /*
13011     * This method handles package deletion in general
13012     */
13013    private boolean deletePackageLI(String packageName, UserHandle user,
13014            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13015            int flags, PackageRemovedInfo outInfo,
13016            boolean writeSettings) {
13017        if (packageName == null) {
13018            Slog.w(TAG, "Attempt to delete null packageName.");
13019            return false;
13020        }
13021        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13022        PackageSetting ps;
13023        boolean dataOnly = false;
13024        int removeUser = -1;
13025        int appId = -1;
13026        synchronized (mPackages) {
13027            ps = mSettings.mPackages.get(packageName);
13028            if (ps == null) {
13029                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13030                return false;
13031            }
13032            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13033                    && user.getIdentifier() != UserHandle.USER_ALL) {
13034                // The caller is asking that the package only be deleted for a single
13035                // user.  To do this, we just mark its uninstalled state and delete
13036                // its data.  If this is a system app, we only allow this to happen if
13037                // they have set the special DELETE_SYSTEM_APP which requests different
13038                // semantics than normal for uninstalling system apps.
13039                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13040                ps.setUserState(user.getIdentifier(),
13041                        COMPONENT_ENABLED_STATE_DEFAULT,
13042                        false, //installed
13043                        true,  //stopped
13044                        true,  //notLaunched
13045                        false, //hidden
13046                        null, null, null,
13047                        false, // blockUninstall
13048                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13049                if (!isSystemApp(ps)) {
13050                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13051                        // Other user still have this package installed, so all
13052                        // we need to do is clear this user's data and save that
13053                        // it is uninstalled.
13054                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13055                        removeUser = user.getIdentifier();
13056                        appId = ps.appId;
13057                        scheduleWritePackageRestrictionsLocked(removeUser);
13058                    } else {
13059                        // We need to set it back to 'installed' so the uninstall
13060                        // broadcasts will be sent correctly.
13061                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13062                        ps.setInstalled(true, user.getIdentifier());
13063                    }
13064                } else {
13065                    // This is a system app, so we assume that the
13066                    // other users still have this package installed, so all
13067                    // we need to do is clear this user's data and save that
13068                    // it is uninstalled.
13069                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13070                    removeUser = user.getIdentifier();
13071                    appId = ps.appId;
13072                    scheduleWritePackageRestrictionsLocked(removeUser);
13073                }
13074            }
13075        }
13076
13077        if (removeUser >= 0) {
13078            // From above, we determined that we are deleting this only
13079            // for a single user.  Continue the work here.
13080            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13081            if (outInfo != null) {
13082                outInfo.removedPackage = packageName;
13083                outInfo.removedAppId = appId;
13084                outInfo.removedUsers = new int[] {removeUser};
13085            }
13086            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13087            removeKeystoreDataIfNeeded(removeUser, appId);
13088            schedulePackageCleaning(packageName, removeUser, false);
13089            synchronized (mPackages) {
13090                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13091                    scheduleWritePackageRestrictionsLocked(removeUser);
13092                }
13093                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13094            }
13095            return true;
13096        }
13097
13098        if (dataOnly) {
13099            // Delete application data first
13100            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13101            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13102            return true;
13103        }
13104
13105        boolean ret = false;
13106        if (isSystemApp(ps)) {
13107            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13108            // When an updated system application is deleted we delete the existing resources as well and
13109            // fall back to existing code in system partition
13110            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13111                    flags, outInfo, writeSettings);
13112        } else {
13113            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13114            // Kill application pre-emptively especially for apps on sd.
13115            killApplication(packageName, ps.appId, "uninstall pkg");
13116            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13117                    allUserHandles, perUserInstalled,
13118                    outInfo, writeSettings);
13119        }
13120
13121        return ret;
13122    }
13123
13124    private final class ClearStorageConnection implements ServiceConnection {
13125        IMediaContainerService mContainerService;
13126
13127        @Override
13128        public void onServiceConnected(ComponentName name, IBinder service) {
13129            synchronized (this) {
13130                mContainerService = IMediaContainerService.Stub.asInterface(service);
13131                notifyAll();
13132            }
13133        }
13134
13135        @Override
13136        public void onServiceDisconnected(ComponentName name) {
13137        }
13138    }
13139
13140    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13141        final boolean mounted;
13142        if (Environment.isExternalStorageEmulated()) {
13143            mounted = true;
13144        } else {
13145            final String status = Environment.getExternalStorageState();
13146
13147            mounted = status.equals(Environment.MEDIA_MOUNTED)
13148                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13149        }
13150
13151        if (!mounted) {
13152            return;
13153        }
13154
13155        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13156        int[] users;
13157        if (userId == UserHandle.USER_ALL) {
13158            users = sUserManager.getUserIds();
13159        } else {
13160            users = new int[] { userId };
13161        }
13162        final ClearStorageConnection conn = new ClearStorageConnection();
13163        if (mContext.bindServiceAsUser(
13164                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13165            try {
13166                for (int curUser : users) {
13167                    long timeout = SystemClock.uptimeMillis() + 5000;
13168                    synchronized (conn) {
13169                        long now = SystemClock.uptimeMillis();
13170                        while (conn.mContainerService == null && now < timeout) {
13171                            try {
13172                                conn.wait(timeout - now);
13173                            } catch (InterruptedException e) {
13174                            }
13175                        }
13176                    }
13177                    if (conn.mContainerService == null) {
13178                        return;
13179                    }
13180
13181                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13182                    clearDirectory(conn.mContainerService,
13183                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13184                    if (allData) {
13185                        clearDirectory(conn.mContainerService,
13186                                userEnv.buildExternalStorageAppDataDirs(packageName));
13187                        clearDirectory(conn.mContainerService,
13188                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13189                    }
13190                }
13191            } finally {
13192                mContext.unbindService(conn);
13193            }
13194        }
13195    }
13196
13197    @Override
13198    public void clearApplicationUserData(final String packageName,
13199            final IPackageDataObserver observer, final int userId) {
13200        mContext.enforceCallingOrSelfPermission(
13201                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13202        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13203        // Queue up an async operation since the package deletion may take a little while.
13204        mHandler.post(new Runnable() {
13205            public void run() {
13206                mHandler.removeCallbacks(this);
13207                final boolean succeeded;
13208                synchronized (mInstallLock) {
13209                    succeeded = clearApplicationUserDataLI(packageName, userId);
13210                }
13211                clearExternalStorageDataSync(packageName, userId, true);
13212                if (succeeded) {
13213                    // invoke DeviceStorageMonitor's update method to clear any notifications
13214                    DeviceStorageMonitorInternal
13215                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13216                    if (dsm != null) {
13217                        dsm.checkMemory();
13218                    }
13219                }
13220                if(observer != null) {
13221                    try {
13222                        observer.onRemoveCompleted(packageName, succeeded);
13223                    } catch (RemoteException e) {
13224                        Log.i(TAG, "Observer no longer exists.");
13225                    }
13226                } //end if observer
13227            } //end run
13228        });
13229    }
13230
13231    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13232        if (packageName == null) {
13233            Slog.w(TAG, "Attempt to delete null packageName.");
13234            return false;
13235        }
13236
13237        // Try finding details about the requested package
13238        PackageParser.Package pkg;
13239        synchronized (mPackages) {
13240            pkg = mPackages.get(packageName);
13241            if (pkg == null) {
13242                final PackageSetting ps = mSettings.mPackages.get(packageName);
13243                if (ps != null) {
13244                    pkg = ps.pkg;
13245                }
13246            }
13247
13248            if (pkg == null) {
13249                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13250                return false;
13251            }
13252
13253            PackageSetting ps = (PackageSetting) pkg.mExtras;
13254            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13255        }
13256
13257        // Always delete data directories for package, even if we found no other
13258        // record of app. This helps users recover from UID mismatches without
13259        // resorting to a full data wipe.
13260        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13261        if (retCode < 0) {
13262            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13263            return false;
13264        }
13265
13266        final int appId = pkg.applicationInfo.uid;
13267        removeKeystoreDataIfNeeded(userId, appId);
13268
13269        // Create a native library symlink only if we have native libraries
13270        // and if the native libraries are 32 bit libraries. We do not provide
13271        // this symlink for 64 bit libraries.
13272        if (pkg.applicationInfo.primaryCpuAbi != null &&
13273                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13274            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13275            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13276                    nativeLibPath, userId) < 0) {
13277                Slog.w(TAG, "Failed linking native library dir");
13278                return false;
13279            }
13280        }
13281
13282        return true;
13283    }
13284
13285    /**
13286     * Reverts user permission state changes (permissions and flags) in
13287     * all packages for a given user.
13288     *
13289     * @param userId The device user for which to do a reset.
13290     */
13291    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13292        final int packageCount = mPackages.size();
13293        for (int i = 0; i < packageCount; i++) {
13294            PackageParser.Package pkg = mPackages.valueAt(i);
13295            PackageSetting ps = (PackageSetting) pkg.mExtras;
13296            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13297        }
13298    }
13299
13300    /**
13301     * Reverts user permission state changes (permissions and flags).
13302     *
13303     * @param ps The package for which to reset.
13304     * @param userId The device user for which to do a reset.
13305     */
13306    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13307            final PackageSetting ps, final int userId) {
13308        if (ps.pkg == null) {
13309            return;
13310        }
13311
13312        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13313                | FLAG_PERMISSION_USER_FIXED
13314                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13315
13316        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13317                | FLAG_PERMISSION_POLICY_FIXED;
13318
13319        boolean writeInstallPermissions = false;
13320        boolean writeRuntimePermissions = false;
13321
13322        final int permissionCount = ps.pkg.requestedPermissions.size();
13323        for (int i = 0; i < permissionCount; i++) {
13324            String permission = ps.pkg.requestedPermissions.get(i);
13325
13326            BasePermission bp = mSettings.mPermissions.get(permission);
13327            if (bp == null) {
13328                continue;
13329            }
13330
13331            // If shared user we just reset the state to which only this app contributed.
13332            if (ps.sharedUser != null) {
13333                boolean used = false;
13334                final int packageCount = ps.sharedUser.packages.size();
13335                for (int j = 0; j < packageCount; j++) {
13336                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13337                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13338                            && pkg.pkg.requestedPermissions.contains(permission)) {
13339                        used = true;
13340                        break;
13341                    }
13342                }
13343                if (used) {
13344                    continue;
13345                }
13346            }
13347
13348            PermissionsState permissionsState = ps.getPermissionsState();
13349
13350            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13351
13352            // Always clear the user settable flags.
13353            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13354                    bp.name) != null;
13355            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13356                if (hasInstallState) {
13357                    writeInstallPermissions = true;
13358                } else {
13359                    writeRuntimePermissions = true;
13360                }
13361            }
13362
13363            // Below is only runtime permission handling.
13364            if (!bp.isRuntime()) {
13365                continue;
13366            }
13367
13368            // Never clobber system or policy.
13369            if ((oldFlags & policyOrSystemFlags) != 0) {
13370                continue;
13371            }
13372
13373            // If this permission was granted by default, make sure it is.
13374            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13375                if (permissionsState.grantRuntimePermission(bp, userId)
13376                        != PERMISSION_OPERATION_FAILURE) {
13377                    writeRuntimePermissions = true;
13378                }
13379            } else {
13380                // Otherwise, reset the permission.
13381                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13382                switch (revokeResult) {
13383                    case PERMISSION_OPERATION_SUCCESS: {
13384                        writeRuntimePermissions = true;
13385                    } break;
13386
13387                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13388                        writeRuntimePermissions = true;
13389                        final int appId = ps.appId;
13390                        mHandler.post(new Runnable() {
13391                            @Override
13392                            public void run() {
13393                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13394                            }
13395                        });
13396                    } break;
13397                }
13398            }
13399        }
13400
13401        // Synchronously write as we are taking permissions away.
13402        if (writeRuntimePermissions) {
13403            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13404        }
13405
13406        // Synchronously write as we are taking permissions away.
13407        if (writeInstallPermissions) {
13408            mSettings.writeLPr();
13409        }
13410    }
13411
13412    /**
13413     * Remove entries from the keystore daemon. Will only remove it if the
13414     * {@code appId} is valid.
13415     */
13416    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13417        if (appId < 0) {
13418            return;
13419        }
13420
13421        final KeyStore keyStore = KeyStore.getInstance();
13422        if (keyStore != null) {
13423            if (userId == UserHandle.USER_ALL) {
13424                for (final int individual : sUserManager.getUserIds()) {
13425                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13426                }
13427            } else {
13428                keyStore.clearUid(UserHandle.getUid(userId, appId));
13429            }
13430        } else {
13431            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13432        }
13433    }
13434
13435    @Override
13436    public void deleteApplicationCacheFiles(final String packageName,
13437            final IPackageDataObserver observer) {
13438        mContext.enforceCallingOrSelfPermission(
13439                android.Manifest.permission.DELETE_CACHE_FILES, null);
13440        // Queue up an async operation since the package deletion may take a little while.
13441        final int userId = UserHandle.getCallingUserId();
13442        mHandler.post(new Runnable() {
13443            public void run() {
13444                mHandler.removeCallbacks(this);
13445                final boolean succeded;
13446                synchronized (mInstallLock) {
13447                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13448                }
13449                clearExternalStorageDataSync(packageName, userId, false);
13450                if (observer != null) {
13451                    try {
13452                        observer.onRemoveCompleted(packageName, succeded);
13453                    } catch (RemoteException e) {
13454                        Log.i(TAG, "Observer no longer exists.");
13455                    }
13456                } //end if observer
13457            } //end run
13458        });
13459    }
13460
13461    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13462        if (packageName == null) {
13463            Slog.w(TAG, "Attempt to delete null packageName.");
13464            return false;
13465        }
13466        PackageParser.Package p;
13467        synchronized (mPackages) {
13468            p = mPackages.get(packageName);
13469        }
13470        if (p == null) {
13471            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13472            return false;
13473        }
13474        final ApplicationInfo applicationInfo = p.applicationInfo;
13475        if (applicationInfo == null) {
13476            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13477            return false;
13478        }
13479        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13480        if (retCode < 0) {
13481            Slog.w(TAG, "Couldn't remove cache files for package: "
13482                       + packageName + " u" + userId);
13483            return false;
13484        }
13485        return true;
13486    }
13487
13488    @Override
13489    public void getPackageSizeInfo(final String packageName, int userHandle,
13490            final IPackageStatsObserver observer) {
13491        mContext.enforceCallingOrSelfPermission(
13492                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13493        if (packageName == null) {
13494            throw new IllegalArgumentException("Attempt to get size of null packageName");
13495        }
13496
13497        PackageStats stats = new PackageStats(packageName, userHandle);
13498
13499        /*
13500         * Queue up an async operation since the package measurement may take a
13501         * little while.
13502         */
13503        Message msg = mHandler.obtainMessage(INIT_COPY);
13504        msg.obj = new MeasureParams(stats, observer);
13505        mHandler.sendMessage(msg);
13506    }
13507
13508    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13509            PackageStats pStats) {
13510        if (packageName == null) {
13511            Slog.w(TAG, "Attempt to get size of null packageName.");
13512            return false;
13513        }
13514        PackageParser.Package p;
13515        boolean dataOnly = false;
13516        String libDirRoot = null;
13517        String asecPath = null;
13518        PackageSetting ps = null;
13519        synchronized (mPackages) {
13520            p = mPackages.get(packageName);
13521            ps = mSettings.mPackages.get(packageName);
13522            if(p == null) {
13523                dataOnly = true;
13524                if((ps == null) || (ps.pkg == null)) {
13525                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13526                    return false;
13527                }
13528                p = ps.pkg;
13529            }
13530            if (ps != null) {
13531                libDirRoot = ps.legacyNativeLibraryPathString;
13532            }
13533            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13534                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13535                if (secureContainerId != null) {
13536                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13537                }
13538            }
13539        }
13540        String publicSrcDir = null;
13541        if(!dataOnly) {
13542            final ApplicationInfo applicationInfo = p.applicationInfo;
13543            if (applicationInfo == null) {
13544                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13545                return false;
13546            }
13547            if (p.isForwardLocked()) {
13548                publicSrcDir = applicationInfo.getBaseResourcePath();
13549            }
13550        }
13551        // TODO: extend to measure size of split APKs
13552        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13553        // not just the first level.
13554        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13555        // just the primary.
13556        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13557        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13558                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13559        if (res < 0) {
13560            return false;
13561        }
13562
13563        // Fix-up for forward-locked applications in ASEC containers.
13564        if (!isExternal(p)) {
13565            pStats.codeSize += pStats.externalCodeSize;
13566            pStats.externalCodeSize = 0L;
13567        }
13568
13569        return true;
13570    }
13571
13572
13573    @Override
13574    public void addPackageToPreferred(String packageName) {
13575        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13576    }
13577
13578    @Override
13579    public void removePackageFromPreferred(String packageName) {
13580        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13581    }
13582
13583    @Override
13584    public List<PackageInfo> getPreferredPackages(int flags) {
13585        return new ArrayList<PackageInfo>();
13586    }
13587
13588    private int getUidTargetSdkVersionLockedLPr(int uid) {
13589        Object obj = mSettings.getUserIdLPr(uid);
13590        if (obj instanceof SharedUserSetting) {
13591            final SharedUserSetting sus = (SharedUserSetting) obj;
13592            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13593            final Iterator<PackageSetting> it = sus.packages.iterator();
13594            while (it.hasNext()) {
13595                final PackageSetting ps = it.next();
13596                if (ps.pkg != null) {
13597                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13598                    if (v < vers) vers = v;
13599                }
13600            }
13601            return vers;
13602        } else if (obj instanceof PackageSetting) {
13603            final PackageSetting ps = (PackageSetting) obj;
13604            if (ps.pkg != null) {
13605                return ps.pkg.applicationInfo.targetSdkVersion;
13606            }
13607        }
13608        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13609    }
13610
13611    @Override
13612    public void addPreferredActivity(IntentFilter filter, int match,
13613            ComponentName[] set, ComponentName activity, int userId) {
13614        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13615                "Adding preferred");
13616    }
13617
13618    private void addPreferredActivityInternal(IntentFilter filter, int match,
13619            ComponentName[] set, ComponentName activity, boolean always, int userId,
13620            String opname) {
13621        // writer
13622        int callingUid = Binder.getCallingUid();
13623        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13624        if (filter.countActions() == 0) {
13625            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13626            return;
13627        }
13628        synchronized (mPackages) {
13629            if (mContext.checkCallingOrSelfPermission(
13630                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13631                    != PackageManager.PERMISSION_GRANTED) {
13632                if (getUidTargetSdkVersionLockedLPr(callingUid)
13633                        < Build.VERSION_CODES.FROYO) {
13634                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13635                            + callingUid);
13636                    return;
13637                }
13638                mContext.enforceCallingOrSelfPermission(
13639                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13640            }
13641
13642            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13643            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13644                    + userId + ":");
13645            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13646            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13647            scheduleWritePackageRestrictionsLocked(userId);
13648        }
13649    }
13650
13651    @Override
13652    public void replacePreferredActivity(IntentFilter filter, int match,
13653            ComponentName[] set, ComponentName activity, int userId) {
13654        if (filter.countActions() != 1) {
13655            throw new IllegalArgumentException(
13656                    "replacePreferredActivity expects filter to have only 1 action.");
13657        }
13658        if (filter.countDataAuthorities() != 0
13659                || filter.countDataPaths() != 0
13660                || filter.countDataSchemes() > 1
13661                || filter.countDataTypes() != 0) {
13662            throw new IllegalArgumentException(
13663                    "replacePreferredActivity expects filter to have no data authorities, " +
13664                    "paths, or types; and at most one scheme.");
13665        }
13666
13667        final int callingUid = Binder.getCallingUid();
13668        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13669        synchronized (mPackages) {
13670            if (mContext.checkCallingOrSelfPermission(
13671                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13672                    != PackageManager.PERMISSION_GRANTED) {
13673                if (getUidTargetSdkVersionLockedLPr(callingUid)
13674                        < Build.VERSION_CODES.FROYO) {
13675                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13676                            + Binder.getCallingUid());
13677                    return;
13678                }
13679                mContext.enforceCallingOrSelfPermission(
13680                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13681            }
13682
13683            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13684            if (pir != null) {
13685                // Get all of the existing entries that exactly match this filter.
13686                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13687                if (existing != null && existing.size() == 1) {
13688                    PreferredActivity cur = existing.get(0);
13689                    if (DEBUG_PREFERRED) {
13690                        Slog.i(TAG, "Checking replace of preferred:");
13691                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13692                        if (!cur.mPref.mAlways) {
13693                            Slog.i(TAG, "  -- CUR; not mAlways!");
13694                        } else {
13695                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13696                            Slog.i(TAG, "  -- CUR: mSet="
13697                                    + Arrays.toString(cur.mPref.mSetComponents));
13698                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13699                            Slog.i(TAG, "  -- NEW: mMatch="
13700                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13701                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13702                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13703                        }
13704                    }
13705                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13706                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13707                            && cur.mPref.sameSet(set)) {
13708                        // Setting the preferred activity to what it happens to be already
13709                        if (DEBUG_PREFERRED) {
13710                            Slog.i(TAG, "Replacing with same preferred activity "
13711                                    + cur.mPref.mShortComponent + " for user "
13712                                    + userId + ":");
13713                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13714                        }
13715                        return;
13716                    }
13717                }
13718
13719                if (existing != null) {
13720                    if (DEBUG_PREFERRED) {
13721                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13722                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13723                    }
13724                    for (int i = 0; i < existing.size(); i++) {
13725                        PreferredActivity pa = existing.get(i);
13726                        if (DEBUG_PREFERRED) {
13727                            Slog.i(TAG, "Removing existing preferred activity "
13728                                    + pa.mPref.mComponent + ":");
13729                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13730                        }
13731                        pir.removeFilter(pa);
13732                    }
13733                }
13734            }
13735            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13736                    "Replacing preferred");
13737        }
13738    }
13739
13740    @Override
13741    public void clearPackagePreferredActivities(String packageName) {
13742        final int uid = Binder.getCallingUid();
13743        // writer
13744        synchronized (mPackages) {
13745            PackageParser.Package pkg = mPackages.get(packageName);
13746            if (pkg == null || pkg.applicationInfo.uid != uid) {
13747                if (mContext.checkCallingOrSelfPermission(
13748                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13749                        != PackageManager.PERMISSION_GRANTED) {
13750                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13751                            < Build.VERSION_CODES.FROYO) {
13752                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13753                                + Binder.getCallingUid());
13754                        return;
13755                    }
13756                    mContext.enforceCallingOrSelfPermission(
13757                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13758                }
13759            }
13760
13761            int user = UserHandle.getCallingUserId();
13762            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13763                scheduleWritePackageRestrictionsLocked(user);
13764            }
13765        }
13766    }
13767
13768    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13769    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13770        ArrayList<PreferredActivity> removed = null;
13771        boolean changed = false;
13772        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13773            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13774            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13775            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13776                continue;
13777            }
13778            Iterator<PreferredActivity> it = pir.filterIterator();
13779            while (it.hasNext()) {
13780                PreferredActivity pa = it.next();
13781                // Mark entry for removal only if it matches the package name
13782                // and the entry is of type "always".
13783                if (packageName == null ||
13784                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13785                                && pa.mPref.mAlways)) {
13786                    if (removed == null) {
13787                        removed = new ArrayList<PreferredActivity>();
13788                    }
13789                    removed.add(pa);
13790                }
13791            }
13792            if (removed != null) {
13793                for (int j=0; j<removed.size(); j++) {
13794                    PreferredActivity pa = removed.get(j);
13795                    pir.removeFilter(pa);
13796                }
13797                changed = true;
13798            }
13799        }
13800        return changed;
13801    }
13802
13803    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13804    private void clearIntentFilterVerificationsLPw(int userId) {
13805        final int packageCount = mPackages.size();
13806        for (int i = 0; i < packageCount; i++) {
13807            PackageParser.Package pkg = mPackages.valueAt(i);
13808            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13809        }
13810    }
13811
13812    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13813    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13814        if (userId == UserHandle.USER_ALL) {
13815            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13816                    sUserManager.getUserIds())) {
13817                for (int oneUserId : sUserManager.getUserIds()) {
13818                    scheduleWritePackageRestrictionsLocked(oneUserId);
13819                }
13820            }
13821        } else {
13822            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13823                scheduleWritePackageRestrictionsLocked(userId);
13824            }
13825        }
13826    }
13827
13828    void clearDefaultBrowserIfNeeded(String packageName) {
13829        for (int oneUserId : sUserManager.getUserIds()) {
13830            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13831            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13832            if (packageName.equals(defaultBrowserPackageName)) {
13833                setDefaultBrowserPackageName(null, oneUserId);
13834            }
13835        }
13836    }
13837
13838    @Override
13839    public void resetApplicationPreferences(int userId) {
13840        mContext.enforceCallingOrSelfPermission(
13841                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13842        // writer
13843        synchronized (mPackages) {
13844            final long identity = Binder.clearCallingIdentity();
13845            try {
13846                clearPackagePreferredActivitiesLPw(null, userId);
13847                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13848                // TODO: We have to reset the default SMS and Phone. This requires
13849                // significant refactoring to keep all default apps in the package
13850                // manager (cleaner but more work) or have the services provide
13851                // callbacks to the package manager to request a default app reset.
13852                applyFactoryDefaultBrowserLPw(userId);
13853                clearIntentFilterVerificationsLPw(userId);
13854                primeDomainVerificationsLPw(userId);
13855                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13856                scheduleWritePackageRestrictionsLocked(userId);
13857            } finally {
13858                Binder.restoreCallingIdentity(identity);
13859            }
13860        }
13861    }
13862
13863    @Override
13864    public int getPreferredActivities(List<IntentFilter> outFilters,
13865            List<ComponentName> outActivities, String packageName) {
13866
13867        int num = 0;
13868        final int userId = UserHandle.getCallingUserId();
13869        // reader
13870        synchronized (mPackages) {
13871            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13872            if (pir != null) {
13873                final Iterator<PreferredActivity> it = pir.filterIterator();
13874                while (it.hasNext()) {
13875                    final PreferredActivity pa = it.next();
13876                    if (packageName == null
13877                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13878                                    && pa.mPref.mAlways)) {
13879                        if (outFilters != null) {
13880                            outFilters.add(new IntentFilter(pa));
13881                        }
13882                        if (outActivities != null) {
13883                            outActivities.add(pa.mPref.mComponent);
13884                        }
13885                    }
13886                }
13887            }
13888        }
13889
13890        return num;
13891    }
13892
13893    @Override
13894    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13895            int userId) {
13896        int callingUid = Binder.getCallingUid();
13897        if (callingUid != Process.SYSTEM_UID) {
13898            throw new SecurityException(
13899                    "addPersistentPreferredActivity can only be run by the system");
13900        }
13901        if (filter.countActions() == 0) {
13902            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13903            return;
13904        }
13905        synchronized (mPackages) {
13906            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13907                    " :");
13908            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13909            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13910                    new PersistentPreferredActivity(filter, activity));
13911            scheduleWritePackageRestrictionsLocked(userId);
13912        }
13913    }
13914
13915    @Override
13916    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13917        int callingUid = Binder.getCallingUid();
13918        if (callingUid != Process.SYSTEM_UID) {
13919            throw new SecurityException(
13920                    "clearPackagePersistentPreferredActivities can only be run by the system");
13921        }
13922        ArrayList<PersistentPreferredActivity> removed = null;
13923        boolean changed = false;
13924        synchronized (mPackages) {
13925            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13926                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13927                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13928                        .valueAt(i);
13929                if (userId != thisUserId) {
13930                    continue;
13931                }
13932                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13933                while (it.hasNext()) {
13934                    PersistentPreferredActivity ppa = it.next();
13935                    // Mark entry for removal only if it matches the package name.
13936                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13937                        if (removed == null) {
13938                            removed = new ArrayList<PersistentPreferredActivity>();
13939                        }
13940                        removed.add(ppa);
13941                    }
13942                }
13943                if (removed != null) {
13944                    for (int j=0; j<removed.size(); j++) {
13945                        PersistentPreferredActivity ppa = removed.get(j);
13946                        ppir.removeFilter(ppa);
13947                    }
13948                    changed = true;
13949                }
13950            }
13951
13952            if (changed) {
13953                scheduleWritePackageRestrictionsLocked(userId);
13954            }
13955        }
13956    }
13957
13958    /**
13959     * Common machinery for picking apart a restored XML blob and passing
13960     * it to a caller-supplied functor to be applied to the running system.
13961     */
13962    private void restoreFromXml(XmlPullParser parser, int userId,
13963            String expectedStartTag, BlobXmlRestorer functor)
13964            throws IOException, XmlPullParserException {
13965        int type;
13966        while ((type = parser.next()) != XmlPullParser.START_TAG
13967                && type != XmlPullParser.END_DOCUMENT) {
13968        }
13969        if (type != XmlPullParser.START_TAG) {
13970            // oops didn't find a start tag?!
13971            if (DEBUG_BACKUP) {
13972                Slog.e(TAG, "Didn't find start tag during restore");
13973            }
13974            return;
13975        }
13976
13977        // this is supposed to be TAG_PREFERRED_BACKUP
13978        if (!expectedStartTag.equals(parser.getName())) {
13979            if (DEBUG_BACKUP) {
13980                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13981            }
13982            return;
13983        }
13984
13985        // skip interfering stuff, then we're aligned with the backing implementation
13986        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13987        functor.apply(parser, userId);
13988    }
13989
13990    private interface BlobXmlRestorer {
13991        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13992    }
13993
13994    /**
13995     * Non-Binder method, support for the backup/restore mechanism: write the
13996     * full set of preferred activities in its canonical XML format.  Returns the
13997     * XML output as a byte array, or null if there is none.
13998     */
13999    @Override
14000    public byte[] getPreferredActivityBackup(int userId) {
14001        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14002            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14003        }
14004
14005        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14006        try {
14007            final XmlSerializer serializer = new FastXmlSerializer();
14008            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14009            serializer.startDocument(null, true);
14010            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14011
14012            synchronized (mPackages) {
14013                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14014            }
14015
14016            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14017            serializer.endDocument();
14018            serializer.flush();
14019        } catch (Exception e) {
14020            if (DEBUG_BACKUP) {
14021                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14022            }
14023            return null;
14024        }
14025
14026        return dataStream.toByteArray();
14027    }
14028
14029    @Override
14030    public void restorePreferredActivities(byte[] backup, int userId) {
14031        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14032            throw new SecurityException("Only the system may call restorePreferredActivities()");
14033        }
14034
14035        try {
14036            final XmlPullParser parser = Xml.newPullParser();
14037            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14038            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14039                    new BlobXmlRestorer() {
14040                        @Override
14041                        public void apply(XmlPullParser parser, int userId)
14042                                throws XmlPullParserException, IOException {
14043                            synchronized (mPackages) {
14044                                mSettings.readPreferredActivitiesLPw(parser, userId);
14045                            }
14046                        }
14047                    } );
14048        } catch (Exception e) {
14049            if (DEBUG_BACKUP) {
14050                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14051            }
14052        }
14053    }
14054
14055    /**
14056     * Non-Binder method, support for the backup/restore mechanism: write the
14057     * default browser (etc) settings in its canonical XML format.  Returns the default
14058     * browser XML representation as a byte array, or null if there is none.
14059     */
14060    @Override
14061    public byte[] getDefaultAppsBackup(int userId) {
14062        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14063            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14064        }
14065
14066        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14067        try {
14068            final XmlSerializer serializer = new FastXmlSerializer();
14069            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14070            serializer.startDocument(null, true);
14071            serializer.startTag(null, TAG_DEFAULT_APPS);
14072
14073            synchronized (mPackages) {
14074                mSettings.writeDefaultAppsLPr(serializer, userId);
14075            }
14076
14077            serializer.endTag(null, TAG_DEFAULT_APPS);
14078            serializer.endDocument();
14079            serializer.flush();
14080        } catch (Exception e) {
14081            if (DEBUG_BACKUP) {
14082                Slog.e(TAG, "Unable to write default apps for backup", e);
14083            }
14084            return null;
14085        }
14086
14087        return dataStream.toByteArray();
14088    }
14089
14090    @Override
14091    public void restoreDefaultApps(byte[] backup, int userId) {
14092        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14093            throw new SecurityException("Only the system may call restoreDefaultApps()");
14094        }
14095
14096        try {
14097            final XmlPullParser parser = Xml.newPullParser();
14098            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14099            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14100                    new BlobXmlRestorer() {
14101                        @Override
14102                        public void apply(XmlPullParser parser, int userId)
14103                                throws XmlPullParserException, IOException {
14104                            synchronized (mPackages) {
14105                                mSettings.readDefaultAppsLPw(parser, userId);
14106                            }
14107                        }
14108                    } );
14109        } catch (Exception e) {
14110            if (DEBUG_BACKUP) {
14111                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14112            }
14113        }
14114    }
14115
14116    @Override
14117    public byte[] getIntentFilterVerificationBackup(int userId) {
14118        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14119            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14120        }
14121
14122        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14123        try {
14124            final XmlSerializer serializer = new FastXmlSerializer();
14125            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14126            serializer.startDocument(null, true);
14127            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14128
14129            synchronized (mPackages) {
14130                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14131            }
14132
14133            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14134            serializer.endDocument();
14135            serializer.flush();
14136        } catch (Exception e) {
14137            if (DEBUG_BACKUP) {
14138                Slog.e(TAG, "Unable to write default apps for backup", e);
14139            }
14140            return null;
14141        }
14142
14143        return dataStream.toByteArray();
14144    }
14145
14146    @Override
14147    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14148        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14149            throw new SecurityException("Only the system may call restorePreferredActivities()");
14150        }
14151
14152        try {
14153            final XmlPullParser parser = Xml.newPullParser();
14154            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14155            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14156                    new BlobXmlRestorer() {
14157                        @Override
14158                        public void apply(XmlPullParser parser, int userId)
14159                                throws XmlPullParserException, IOException {
14160                            synchronized (mPackages) {
14161                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14162                                mSettings.writeLPr();
14163                            }
14164                        }
14165                    } );
14166        } catch (Exception e) {
14167            if (DEBUG_BACKUP) {
14168                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14169            }
14170        }
14171    }
14172
14173    @Override
14174    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14175            int sourceUserId, int targetUserId, int flags) {
14176        mContext.enforceCallingOrSelfPermission(
14177                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14178        int callingUid = Binder.getCallingUid();
14179        enforceOwnerRights(ownerPackage, callingUid);
14180        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14181        if (intentFilter.countActions() == 0) {
14182            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14183            return;
14184        }
14185        synchronized (mPackages) {
14186            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14187                    ownerPackage, targetUserId, flags);
14188            CrossProfileIntentResolver resolver =
14189                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14190            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14191            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14192            if (existing != null) {
14193                int size = existing.size();
14194                for (int i = 0; i < size; i++) {
14195                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14196                        return;
14197                    }
14198                }
14199            }
14200            resolver.addFilter(newFilter);
14201            scheduleWritePackageRestrictionsLocked(sourceUserId);
14202        }
14203    }
14204
14205    @Override
14206    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14207        mContext.enforceCallingOrSelfPermission(
14208                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14209        int callingUid = Binder.getCallingUid();
14210        enforceOwnerRights(ownerPackage, callingUid);
14211        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14212        synchronized (mPackages) {
14213            CrossProfileIntentResolver resolver =
14214                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14215            ArraySet<CrossProfileIntentFilter> set =
14216                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14217            for (CrossProfileIntentFilter filter : set) {
14218                if (filter.getOwnerPackage().equals(ownerPackage)) {
14219                    resolver.removeFilter(filter);
14220                }
14221            }
14222            scheduleWritePackageRestrictionsLocked(sourceUserId);
14223        }
14224    }
14225
14226    // Enforcing that callingUid is owning pkg on userId
14227    private void enforceOwnerRights(String pkg, int callingUid) {
14228        // The system owns everything.
14229        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14230            return;
14231        }
14232        int callingUserId = UserHandle.getUserId(callingUid);
14233        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14234        if (pi == null) {
14235            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14236                    + callingUserId);
14237        }
14238        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14239            throw new SecurityException("Calling uid " + callingUid
14240                    + " does not own package " + pkg);
14241        }
14242    }
14243
14244    @Override
14245    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14246        Intent intent = new Intent(Intent.ACTION_MAIN);
14247        intent.addCategory(Intent.CATEGORY_HOME);
14248
14249        final int callingUserId = UserHandle.getCallingUserId();
14250        List<ResolveInfo> list = queryIntentActivities(intent, null,
14251                PackageManager.GET_META_DATA, callingUserId);
14252        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14253                true, false, false, callingUserId);
14254
14255        allHomeCandidates.clear();
14256        if (list != null) {
14257            for (ResolveInfo ri : list) {
14258                allHomeCandidates.add(ri);
14259            }
14260        }
14261        return (preferred == null || preferred.activityInfo == null)
14262                ? null
14263                : new ComponentName(preferred.activityInfo.packageName,
14264                        preferred.activityInfo.name);
14265    }
14266
14267    @Override
14268    public void setApplicationEnabledSetting(String appPackageName,
14269            int newState, int flags, int userId, String callingPackage) {
14270        if (!sUserManager.exists(userId)) return;
14271        if (callingPackage == null) {
14272            callingPackage = Integer.toString(Binder.getCallingUid());
14273        }
14274        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14275    }
14276
14277    @Override
14278    public void setComponentEnabledSetting(ComponentName componentName,
14279            int newState, int flags, int userId) {
14280        if (!sUserManager.exists(userId)) return;
14281        setEnabledSetting(componentName.getPackageName(),
14282                componentName.getClassName(), newState, flags, userId, null);
14283    }
14284
14285    private void setEnabledSetting(final String packageName, String className, int newState,
14286            final int flags, int userId, String callingPackage) {
14287        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14288              || newState == COMPONENT_ENABLED_STATE_ENABLED
14289              || newState == COMPONENT_ENABLED_STATE_DISABLED
14290              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14291              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14292            throw new IllegalArgumentException("Invalid new component state: "
14293                    + newState);
14294        }
14295        PackageSetting pkgSetting;
14296        final int uid = Binder.getCallingUid();
14297        final int permission = mContext.checkCallingOrSelfPermission(
14298                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14299        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14300        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14301        boolean sendNow = false;
14302        boolean isApp = (className == null);
14303        String componentName = isApp ? packageName : className;
14304        int packageUid = -1;
14305        ArrayList<String> components;
14306
14307        // writer
14308        synchronized (mPackages) {
14309            pkgSetting = mSettings.mPackages.get(packageName);
14310            if (pkgSetting == null) {
14311                if (className == null) {
14312                    throw new IllegalArgumentException(
14313                            "Unknown package: " + packageName);
14314                }
14315                throw new IllegalArgumentException(
14316                        "Unknown component: " + packageName
14317                        + "/" + className);
14318            }
14319            // Allow root and verify that userId is not being specified by a different user
14320            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14321                throw new SecurityException(
14322                        "Permission Denial: attempt to change component state from pid="
14323                        + Binder.getCallingPid()
14324                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14325            }
14326            if (className == null) {
14327                // We're dealing with an application/package level state change
14328                if (pkgSetting.getEnabled(userId) == newState) {
14329                    // Nothing to do
14330                    return;
14331                }
14332                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14333                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14334                    // Don't care about who enables an app.
14335                    callingPackage = null;
14336                }
14337                pkgSetting.setEnabled(newState, userId, callingPackage);
14338                // pkgSetting.pkg.mSetEnabled = newState;
14339            } else {
14340                // We're dealing with a component level state change
14341                // First, verify that this is a valid class name.
14342                PackageParser.Package pkg = pkgSetting.pkg;
14343                if (pkg == null || !pkg.hasComponentClassName(className)) {
14344                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14345                        throw new IllegalArgumentException("Component class " + className
14346                                + " does not exist in " + packageName);
14347                    } else {
14348                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14349                                + className + " does not exist in " + packageName);
14350                    }
14351                }
14352                switch (newState) {
14353                case COMPONENT_ENABLED_STATE_ENABLED:
14354                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14355                        return;
14356                    }
14357                    break;
14358                case COMPONENT_ENABLED_STATE_DISABLED:
14359                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14360                        return;
14361                    }
14362                    break;
14363                case COMPONENT_ENABLED_STATE_DEFAULT:
14364                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14365                        return;
14366                    }
14367                    break;
14368                default:
14369                    Slog.e(TAG, "Invalid new component state: " + newState);
14370                    return;
14371                }
14372            }
14373            scheduleWritePackageRestrictionsLocked(userId);
14374            components = mPendingBroadcasts.get(userId, packageName);
14375            final boolean newPackage = components == null;
14376            if (newPackage) {
14377                components = new ArrayList<String>();
14378            }
14379            if (!components.contains(componentName)) {
14380                components.add(componentName);
14381            }
14382            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14383                sendNow = true;
14384                // Purge entry from pending broadcast list if another one exists already
14385                // since we are sending one right away.
14386                mPendingBroadcasts.remove(userId, packageName);
14387            } else {
14388                if (newPackage) {
14389                    mPendingBroadcasts.put(userId, packageName, components);
14390                }
14391                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14392                    // Schedule a message
14393                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14394                }
14395            }
14396        }
14397
14398        long callingId = Binder.clearCallingIdentity();
14399        try {
14400            if (sendNow) {
14401                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14402                sendPackageChangedBroadcast(packageName,
14403                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14404            }
14405        } finally {
14406            Binder.restoreCallingIdentity(callingId);
14407        }
14408    }
14409
14410    private void sendPackageChangedBroadcast(String packageName,
14411            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14412        if (DEBUG_INSTALL)
14413            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14414                    + componentNames);
14415        Bundle extras = new Bundle(4);
14416        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14417        String nameList[] = new String[componentNames.size()];
14418        componentNames.toArray(nameList);
14419        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14420        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14421        extras.putInt(Intent.EXTRA_UID, packageUid);
14422        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14423                new int[] {UserHandle.getUserId(packageUid)});
14424    }
14425
14426    @Override
14427    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14428        if (!sUserManager.exists(userId)) return;
14429        final int uid = Binder.getCallingUid();
14430        final int permission = mContext.checkCallingOrSelfPermission(
14431                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14432        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14433        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14434        // writer
14435        synchronized (mPackages) {
14436            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14437                    allowedByPermission, uid, userId)) {
14438                scheduleWritePackageRestrictionsLocked(userId);
14439            }
14440        }
14441    }
14442
14443    @Override
14444    public String getInstallerPackageName(String packageName) {
14445        // reader
14446        synchronized (mPackages) {
14447            return mSettings.getInstallerPackageNameLPr(packageName);
14448        }
14449    }
14450
14451    @Override
14452    public int getApplicationEnabledSetting(String packageName, int userId) {
14453        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14454        int uid = Binder.getCallingUid();
14455        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14456        // reader
14457        synchronized (mPackages) {
14458            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14459        }
14460    }
14461
14462    @Override
14463    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14464        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14465        int uid = Binder.getCallingUid();
14466        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14467        // reader
14468        synchronized (mPackages) {
14469            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14470        }
14471    }
14472
14473    @Override
14474    public void enterSafeMode() {
14475        enforceSystemOrRoot("Only the system can request entering safe mode");
14476
14477        if (!mSystemReady) {
14478            mSafeMode = true;
14479        }
14480    }
14481
14482    @Override
14483    public void systemReady() {
14484        mSystemReady = true;
14485
14486        // Read the compatibilty setting when the system is ready.
14487        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14488                mContext.getContentResolver(),
14489                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14490        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14491        if (DEBUG_SETTINGS) {
14492            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14493        }
14494
14495        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14496
14497        synchronized (mPackages) {
14498            // Verify that all of the preferred activity components actually
14499            // exist.  It is possible for applications to be updated and at
14500            // that point remove a previously declared activity component that
14501            // had been set as a preferred activity.  We try to clean this up
14502            // the next time we encounter that preferred activity, but it is
14503            // possible for the user flow to never be able to return to that
14504            // situation so here we do a sanity check to make sure we haven't
14505            // left any junk around.
14506            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14507            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14508                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14509                removed.clear();
14510                for (PreferredActivity pa : pir.filterSet()) {
14511                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14512                        removed.add(pa);
14513                    }
14514                }
14515                if (removed.size() > 0) {
14516                    for (int r=0; r<removed.size(); r++) {
14517                        PreferredActivity pa = removed.get(r);
14518                        Slog.w(TAG, "Removing dangling preferred activity: "
14519                                + pa.mPref.mComponent);
14520                        pir.removeFilter(pa);
14521                    }
14522                    mSettings.writePackageRestrictionsLPr(
14523                            mSettings.mPreferredActivities.keyAt(i));
14524                }
14525            }
14526
14527            for (int userId : UserManagerService.getInstance().getUserIds()) {
14528                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14529                    grantPermissionsUserIds = ArrayUtils.appendInt(
14530                            grantPermissionsUserIds, userId);
14531                }
14532            }
14533        }
14534        sUserManager.systemReady();
14535
14536        // If we upgraded grant all default permissions before kicking off.
14537        for (int userId : grantPermissionsUserIds) {
14538            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14539        }
14540
14541        // Kick off any messages waiting for system ready
14542        if (mPostSystemReadyMessages != null) {
14543            for (Message msg : mPostSystemReadyMessages) {
14544                msg.sendToTarget();
14545            }
14546            mPostSystemReadyMessages = null;
14547        }
14548
14549        // Watch for external volumes that come and go over time
14550        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14551        storage.registerListener(mStorageListener);
14552
14553        mInstallerService.systemReady();
14554        mPackageDexOptimizer.systemReady();
14555
14556        MountServiceInternal mountServiceInternal = LocalServices.getService(
14557                MountServiceInternal.class);
14558        mountServiceInternal.addExternalStoragePolicy(
14559                new MountServiceInternal.ExternalStorageMountPolicy() {
14560            @Override
14561            public int getMountMode(int uid, String packageName) {
14562                if (Process.isIsolated(uid)) {
14563                    return Zygote.MOUNT_EXTERNAL_NONE;
14564                }
14565                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14566                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14567                }
14568                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14569                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14570                }
14571                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14572                    return Zygote.MOUNT_EXTERNAL_READ;
14573                }
14574                return Zygote.MOUNT_EXTERNAL_WRITE;
14575            }
14576
14577            @Override
14578            public boolean hasExternalStorage(int uid, String packageName) {
14579                return true;
14580            }
14581        });
14582    }
14583
14584    @Override
14585    public boolean isSafeMode() {
14586        return mSafeMode;
14587    }
14588
14589    @Override
14590    public boolean hasSystemUidErrors() {
14591        return mHasSystemUidErrors;
14592    }
14593
14594    static String arrayToString(int[] array) {
14595        StringBuffer buf = new StringBuffer(128);
14596        buf.append('[');
14597        if (array != null) {
14598            for (int i=0; i<array.length; i++) {
14599                if (i > 0) buf.append(", ");
14600                buf.append(array[i]);
14601            }
14602        }
14603        buf.append(']');
14604        return buf.toString();
14605    }
14606
14607    static class DumpState {
14608        public static final int DUMP_LIBS = 1 << 0;
14609        public static final int DUMP_FEATURES = 1 << 1;
14610        public static final int DUMP_RESOLVERS = 1 << 2;
14611        public static final int DUMP_PERMISSIONS = 1 << 3;
14612        public static final int DUMP_PACKAGES = 1 << 4;
14613        public static final int DUMP_SHARED_USERS = 1 << 5;
14614        public static final int DUMP_MESSAGES = 1 << 6;
14615        public static final int DUMP_PROVIDERS = 1 << 7;
14616        public static final int DUMP_VERIFIERS = 1 << 8;
14617        public static final int DUMP_PREFERRED = 1 << 9;
14618        public static final int DUMP_PREFERRED_XML = 1 << 10;
14619        public static final int DUMP_KEYSETS = 1 << 11;
14620        public static final int DUMP_VERSION = 1 << 12;
14621        public static final int DUMP_INSTALLS = 1 << 13;
14622        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14623        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14624
14625        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14626
14627        private int mTypes;
14628
14629        private int mOptions;
14630
14631        private boolean mTitlePrinted;
14632
14633        private SharedUserSetting mSharedUser;
14634
14635        public boolean isDumping(int type) {
14636            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14637                return true;
14638            }
14639
14640            return (mTypes & type) != 0;
14641        }
14642
14643        public void setDump(int type) {
14644            mTypes |= type;
14645        }
14646
14647        public boolean isOptionEnabled(int option) {
14648            return (mOptions & option) != 0;
14649        }
14650
14651        public void setOptionEnabled(int option) {
14652            mOptions |= option;
14653        }
14654
14655        public boolean onTitlePrinted() {
14656            final boolean printed = mTitlePrinted;
14657            mTitlePrinted = true;
14658            return printed;
14659        }
14660
14661        public boolean getTitlePrinted() {
14662            return mTitlePrinted;
14663        }
14664
14665        public void setTitlePrinted(boolean enabled) {
14666            mTitlePrinted = enabled;
14667        }
14668
14669        public SharedUserSetting getSharedUser() {
14670            return mSharedUser;
14671        }
14672
14673        public void setSharedUser(SharedUserSetting user) {
14674            mSharedUser = user;
14675        }
14676    }
14677
14678    @Override
14679    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14680        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14681                != PackageManager.PERMISSION_GRANTED) {
14682            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14683                    + Binder.getCallingPid()
14684                    + ", uid=" + Binder.getCallingUid()
14685                    + " without permission "
14686                    + android.Manifest.permission.DUMP);
14687            return;
14688        }
14689
14690        DumpState dumpState = new DumpState();
14691        boolean fullPreferred = false;
14692        boolean checkin = false;
14693
14694        String packageName = null;
14695        ArraySet<String> permissionNames = null;
14696
14697        int opti = 0;
14698        while (opti < args.length) {
14699            String opt = args[opti];
14700            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14701                break;
14702            }
14703            opti++;
14704
14705            if ("-a".equals(opt)) {
14706                // Right now we only know how to print all.
14707            } else if ("-h".equals(opt)) {
14708                pw.println("Package manager dump options:");
14709                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14710                pw.println("    --checkin: dump for a checkin");
14711                pw.println("    -f: print details of intent filters");
14712                pw.println("    -h: print this help");
14713                pw.println("  cmd may be one of:");
14714                pw.println("    l[ibraries]: list known shared libraries");
14715                pw.println("    f[ibraries]: list device features");
14716                pw.println("    k[eysets]: print known keysets");
14717                pw.println("    r[esolvers]: dump intent resolvers");
14718                pw.println("    perm[issions]: dump permissions");
14719                pw.println("    permission [name ...]: dump declaration and use of given permission");
14720                pw.println("    pref[erred]: print preferred package settings");
14721                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14722                pw.println("    prov[iders]: dump content providers");
14723                pw.println("    p[ackages]: dump installed packages");
14724                pw.println("    s[hared-users]: dump shared user IDs");
14725                pw.println("    m[essages]: print collected runtime messages");
14726                pw.println("    v[erifiers]: print package verifier info");
14727                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14728                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14729                pw.println("    version: print database version info");
14730                pw.println("    write: write current settings now");
14731                pw.println("    installs: details about install sessions");
14732                pw.println("    <package.name>: info about given package");
14733                return;
14734            } else if ("--checkin".equals(opt)) {
14735                checkin = true;
14736            } else if ("-f".equals(opt)) {
14737                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14738            } else {
14739                pw.println("Unknown argument: " + opt + "; use -h for help");
14740            }
14741        }
14742
14743        // Is the caller requesting to dump a particular piece of data?
14744        if (opti < args.length) {
14745            String cmd = args[opti];
14746            opti++;
14747            // Is this a package name?
14748            if ("android".equals(cmd) || cmd.contains(".")) {
14749                packageName = cmd;
14750                // When dumping a single package, we always dump all of its
14751                // filter information since the amount of data will be reasonable.
14752                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14753            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14754                dumpState.setDump(DumpState.DUMP_LIBS);
14755            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14756                dumpState.setDump(DumpState.DUMP_FEATURES);
14757            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14758                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14759            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14760                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14761            } else if ("permission".equals(cmd)) {
14762                if (opti >= args.length) {
14763                    pw.println("Error: permission requires permission name");
14764                    return;
14765                }
14766                permissionNames = new ArraySet<>();
14767                while (opti < args.length) {
14768                    permissionNames.add(args[opti]);
14769                    opti++;
14770                }
14771                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14772                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14773            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14774                dumpState.setDump(DumpState.DUMP_PREFERRED);
14775            } else if ("preferred-xml".equals(cmd)) {
14776                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14777                if (opti < args.length && "--full".equals(args[opti])) {
14778                    fullPreferred = true;
14779                    opti++;
14780                }
14781            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14782                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14783            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14784                dumpState.setDump(DumpState.DUMP_PACKAGES);
14785            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14786                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14787            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14788                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14789            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14790                dumpState.setDump(DumpState.DUMP_MESSAGES);
14791            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14792                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14793            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14794                    || "intent-filter-verifiers".equals(cmd)) {
14795                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14796            } else if ("version".equals(cmd)) {
14797                dumpState.setDump(DumpState.DUMP_VERSION);
14798            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14799                dumpState.setDump(DumpState.DUMP_KEYSETS);
14800            } else if ("installs".equals(cmd)) {
14801                dumpState.setDump(DumpState.DUMP_INSTALLS);
14802            } else if ("write".equals(cmd)) {
14803                synchronized (mPackages) {
14804                    mSettings.writeLPr();
14805                    pw.println("Settings written.");
14806                    return;
14807                }
14808            }
14809        }
14810
14811        if (checkin) {
14812            pw.println("vers,1");
14813        }
14814
14815        // reader
14816        synchronized (mPackages) {
14817            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14818                if (!checkin) {
14819                    if (dumpState.onTitlePrinted())
14820                        pw.println();
14821                    pw.println("Database versions:");
14822                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14823                }
14824            }
14825
14826            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14827                if (!checkin) {
14828                    if (dumpState.onTitlePrinted())
14829                        pw.println();
14830                    pw.println("Verifiers:");
14831                    pw.print("  Required: ");
14832                    pw.print(mRequiredVerifierPackage);
14833                    pw.print(" (uid=");
14834                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14835                    pw.println(")");
14836                } else if (mRequiredVerifierPackage != null) {
14837                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14838                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14839                }
14840            }
14841
14842            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14843                    packageName == null) {
14844                if (mIntentFilterVerifierComponent != null) {
14845                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14846                    if (!checkin) {
14847                        if (dumpState.onTitlePrinted())
14848                            pw.println();
14849                        pw.println("Intent Filter Verifier:");
14850                        pw.print("  Using: ");
14851                        pw.print(verifierPackageName);
14852                        pw.print(" (uid=");
14853                        pw.print(getPackageUid(verifierPackageName, 0));
14854                        pw.println(")");
14855                    } else if (verifierPackageName != null) {
14856                        pw.print("ifv,"); pw.print(verifierPackageName);
14857                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14858                    }
14859                } else {
14860                    pw.println();
14861                    pw.println("No Intent Filter Verifier available!");
14862                }
14863            }
14864
14865            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14866                boolean printedHeader = false;
14867                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14868                while (it.hasNext()) {
14869                    String name = it.next();
14870                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14871                    if (!checkin) {
14872                        if (!printedHeader) {
14873                            if (dumpState.onTitlePrinted())
14874                                pw.println();
14875                            pw.println("Libraries:");
14876                            printedHeader = true;
14877                        }
14878                        pw.print("  ");
14879                    } else {
14880                        pw.print("lib,");
14881                    }
14882                    pw.print(name);
14883                    if (!checkin) {
14884                        pw.print(" -> ");
14885                    }
14886                    if (ent.path != null) {
14887                        if (!checkin) {
14888                            pw.print("(jar) ");
14889                            pw.print(ent.path);
14890                        } else {
14891                            pw.print(",jar,");
14892                            pw.print(ent.path);
14893                        }
14894                    } else {
14895                        if (!checkin) {
14896                            pw.print("(apk) ");
14897                            pw.print(ent.apk);
14898                        } else {
14899                            pw.print(",apk,");
14900                            pw.print(ent.apk);
14901                        }
14902                    }
14903                    pw.println();
14904                }
14905            }
14906
14907            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14908                if (dumpState.onTitlePrinted())
14909                    pw.println();
14910                if (!checkin) {
14911                    pw.println("Features:");
14912                }
14913                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14914                while (it.hasNext()) {
14915                    String name = it.next();
14916                    if (!checkin) {
14917                        pw.print("  ");
14918                    } else {
14919                        pw.print("feat,");
14920                    }
14921                    pw.println(name);
14922                }
14923            }
14924
14925            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14926                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14927                        : "Activity Resolver Table:", "  ", packageName,
14928                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14929                    dumpState.setTitlePrinted(true);
14930                }
14931                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14932                        : "Receiver Resolver Table:", "  ", packageName,
14933                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14934                    dumpState.setTitlePrinted(true);
14935                }
14936                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14937                        : "Service Resolver Table:", "  ", packageName,
14938                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14939                    dumpState.setTitlePrinted(true);
14940                }
14941                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14942                        : "Provider Resolver Table:", "  ", packageName,
14943                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14944                    dumpState.setTitlePrinted(true);
14945                }
14946            }
14947
14948            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14949                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14950                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14951                    int user = mSettings.mPreferredActivities.keyAt(i);
14952                    if (pir.dump(pw,
14953                            dumpState.getTitlePrinted()
14954                                ? "\nPreferred Activities User " + user + ":"
14955                                : "Preferred Activities User " + user + ":", "  ",
14956                            packageName, true, false)) {
14957                        dumpState.setTitlePrinted(true);
14958                    }
14959                }
14960            }
14961
14962            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14963                pw.flush();
14964                FileOutputStream fout = new FileOutputStream(fd);
14965                BufferedOutputStream str = new BufferedOutputStream(fout);
14966                XmlSerializer serializer = new FastXmlSerializer();
14967                try {
14968                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14969                    serializer.startDocument(null, true);
14970                    serializer.setFeature(
14971                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14972                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14973                    serializer.endDocument();
14974                    serializer.flush();
14975                } catch (IllegalArgumentException e) {
14976                    pw.println("Failed writing: " + e);
14977                } catch (IllegalStateException e) {
14978                    pw.println("Failed writing: " + e);
14979                } catch (IOException e) {
14980                    pw.println("Failed writing: " + e);
14981                }
14982            }
14983
14984            if (!checkin
14985                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14986                    && packageName == null) {
14987                pw.println();
14988                int count = mSettings.mPackages.size();
14989                if (count == 0) {
14990                    pw.println("No applications!");
14991                    pw.println();
14992                } else {
14993                    final String prefix = "  ";
14994                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14995                    if (allPackageSettings.size() == 0) {
14996                        pw.println("No domain preferred apps!");
14997                        pw.println();
14998                    } else {
14999                        pw.println("App verification status:");
15000                        pw.println();
15001                        count = 0;
15002                        for (PackageSetting ps : allPackageSettings) {
15003                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15004                            if (ivi == null || ivi.getPackageName() == null) continue;
15005                            pw.println(prefix + "Package: " + ivi.getPackageName());
15006                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15007                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15008                            pw.println();
15009                            count++;
15010                        }
15011                        if (count == 0) {
15012                            pw.println(prefix + "No app verification established.");
15013                            pw.println();
15014                        }
15015                        for (int userId : sUserManager.getUserIds()) {
15016                            pw.println("App linkages for user " + userId + ":");
15017                            pw.println();
15018                            count = 0;
15019                            for (PackageSetting ps : allPackageSettings) {
15020                                final long status = ps.getDomainVerificationStatusForUser(userId);
15021                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15022                                    continue;
15023                                }
15024                                pw.println(prefix + "Package: " + ps.name);
15025                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15026                                String statusStr = IntentFilterVerificationInfo.
15027                                        getStatusStringFromValue(status);
15028                                pw.println(prefix + "Status:  " + statusStr);
15029                                pw.println();
15030                                count++;
15031                            }
15032                            if (count == 0) {
15033                                pw.println(prefix + "No configured app linkages.");
15034                                pw.println();
15035                            }
15036                        }
15037                    }
15038                }
15039            }
15040
15041            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15042                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15043                if (packageName == null && permissionNames == null) {
15044                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15045                        if (iperm == 0) {
15046                            if (dumpState.onTitlePrinted())
15047                                pw.println();
15048                            pw.println("AppOp Permissions:");
15049                        }
15050                        pw.print("  AppOp Permission ");
15051                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15052                        pw.println(":");
15053                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15054                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15055                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15056                        }
15057                    }
15058                }
15059            }
15060
15061            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15062                boolean printedSomething = false;
15063                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15064                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15065                        continue;
15066                    }
15067                    if (!printedSomething) {
15068                        if (dumpState.onTitlePrinted())
15069                            pw.println();
15070                        pw.println("Registered ContentProviders:");
15071                        printedSomething = true;
15072                    }
15073                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15074                    pw.print("    "); pw.println(p.toString());
15075                }
15076                printedSomething = false;
15077                for (Map.Entry<String, PackageParser.Provider> entry :
15078                        mProvidersByAuthority.entrySet()) {
15079                    PackageParser.Provider p = entry.getValue();
15080                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15081                        continue;
15082                    }
15083                    if (!printedSomething) {
15084                        if (dumpState.onTitlePrinted())
15085                            pw.println();
15086                        pw.println("ContentProvider Authorities:");
15087                        printedSomething = true;
15088                    }
15089                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15090                    pw.print("    "); pw.println(p.toString());
15091                    if (p.info != null && p.info.applicationInfo != null) {
15092                        final String appInfo = p.info.applicationInfo.toString();
15093                        pw.print("      applicationInfo="); pw.println(appInfo);
15094                    }
15095                }
15096            }
15097
15098            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15099                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15100            }
15101
15102            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15103                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15104            }
15105
15106            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15107                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15108            }
15109
15110            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15111                // XXX should handle packageName != null by dumping only install data that
15112                // the given package is involved with.
15113                if (dumpState.onTitlePrinted()) pw.println();
15114                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15115            }
15116
15117            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15118                if (dumpState.onTitlePrinted()) pw.println();
15119                mSettings.dumpReadMessagesLPr(pw, dumpState);
15120
15121                pw.println();
15122                pw.println("Package warning messages:");
15123                BufferedReader in = null;
15124                String line = null;
15125                try {
15126                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15127                    while ((line = in.readLine()) != null) {
15128                        if (line.contains("ignored: updated version")) continue;
15129                        pw.println(line);
15130                    }
15131                } catch (IOException ignored) {
15132                } finally {
15133                    IoUtils.closeQuietly(in);
15134                }
15135            }
15136
15137            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15138                BufferedReader in = null;
15139                String line = null;
15140                try {
15141                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15142                    while ((line = in.readLine()) != null) {
15143                        if (line.contains("ignored: updated version")) continue;
15144                        pw.print("msg,");
15145                        pw.println(line);
15146                    }
15147                } catch (IOException ignored) {
15148                } finally {
15149                    IoUtils.closeQuietly(in);
15150                }
15151            }
15152        }
15153    }
15154
15155    private String dumpDomainString(String packageName) {
15156        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15157        List<IntentFilter> filters = getAllIntentFilters(packageName);
15158
15159        ArraySet<String> result = new ArraySet<>();
15160        if (iviList.size() > 0) {
15161            for (IntentFilterVerificationInfo ivi : iviList) {
15162                for (String host : ivi.getDomains()) {
15163                    result.add(host);
15164                }
15165            }
15166        }
15167        if (filters != null && filters.size() > 0) {
15168            for (IntentFilter filter : filters) {
15169                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15170                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15171                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15172                    result.addAll(filter.getHostsList());
15173                }
15174            }
15175        }
15176
15177        StringBuilder sb = new StringBuilder(result.size() * 16);
15178        for (String domain : result) {
15179            if (sb.length() > 0) sb.append(" ");
15180            sb.append(domain);
15181        }
15182        return sb.toString();
15183    }
15184
15185    // ------- apps on sdcard specific code -------
15186    static final boolean DEBUG_SD_INSTALL = false;
15187
15188    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15189
15190    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15191
15192    private boolean mMediaMounted = false;
15193
15194    static String getEncryptKey() {
15195        try {
15196            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15197                    SD_ENCRYPTION_KEYSTORE_NAME);
15198            if (sdEncKey == null) {
15199                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15200                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15201                if (sdEncKey == null) {
15202                    Slog.e(TAG, "Failed to create encryption keys");
15203                    return null;
15204                }
15205            }
15206            return sdEncKey;
15207        } catch (NoSuchAlgorithmException nsae) {
15208            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15209            return null;
15210        } catch (IOException ioe) {
15211            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15212            return null;
15213        }
15214    }
15215
15216    /*
15217     * Update media status on PackageManager.
15218     */
15219    @Override
15220    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15221        int callingUid = Binder.getCallingUid();
15222        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15223            throw new SecurityException("Media status can only be updated by the system");
15224        }
15225        // reader; this apparently protects mMediaMounted, but should probably
15226        // be a different lock in that case.
15227        synchronized (mPackages) {
15228            Log.i(TAG, "Updating external media status from "
15229                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15230                    + (mediaStatus ? "mounted" : "unmounted"));
15231            if (DEBUG_SD_INSTALL)
15232                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15233                        + ", mMediaMounted=" + mMediaMounted);
15234            if (mediaStatus == mMediaMounted) {
15235                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15236                        : 0, -1);
15237                mHandler.sendMessage(msg);
15238                return;
15239            }
15240            mMediaMounted = mediaStatus;
15241        }
15242        // Queue up an async operation since the package installation may take a
15243        // little while.
15244        mHandler.post(new Runnable() {
15245            public void run() {
15246                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15247            }
15248        });
15249    }
15250
15251    /**
15252     * Called by MountService when the initial ASECs to scan are available.
15253     * Should block until all the ASEC containers are finished being scanned.
15254     */
15255    public void scanAvailableAsecs() {
15256        updateExternalMediaStatusInner(true, false, false);
15257        if (mShouldRestoreconData) {
15258            SELinuxMMAC.setRestoreconDone();
15259            mShouldRestoreconData = false;
15260        }
15261    }
15262
15263    /*
15264     * Collect information of applications on external media, map them against
15265     * existing containers and update information based on current mount status.
15266     * Please note that we always have to report status if reportStatus has been
15267     * set to true especially when unloading packages.
15268     */
15269    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15270            boolean externalStorage) {
15271        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15272        int[] uidArr = EmptyArray.INT;
15273
15274        final String[] list = PackageHelper.getSecureContainerList();
15275        if (ArrayUtils.isEmpty(list)) {
15276            Log.i(TAG, "No secure containers found");
15277        } else {
15278            // Process list of secure containers and categorize them
15279            // as active or stale based on their package internal state.
15280
15281            // reader
15282            synchronized (mPackages) {
15283                for (String cid : list) {
15284                    // Leave stages untouched for now; installer service owns them
15285                    if (PackageInstallerService.isStageName(cid)) continue;
15286
15287                    if (DEBUG_SD_INSTALL)
15288                        Log.i(TAG, "Processing container " + cid);
15289                    String pkgName = getAsecPackageName(cid);
15290                    if (pkgName == null) {
15291                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15292                        continue;
15293                    }
15294                    if (DEBUG_SD_INSTALL)
15295                        Log.i(TAG, "Looking for pkg : " + pkgName);
15296
15297                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15298                    if (ps == null) {
15299                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15300                        continue;
15301                    }
15302
15303                    /*
15304                     * Skip packages that are not external if we're unmounting
15305                     * external storage.
15306                     */
15307                    if (externalStorage && !isMounted && !isExternal(ps)) {
15308                        continue;
15309                    }
15310
15311                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15312                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15313                    // The package status is changed only if the code path
15314                    // matches between settings and the container id.
15315                    if (ps.codePathString != null
15316                            && ps.codePathString.startsWith(args.getCodePath())) {
15317                        if (DEBUG_SD_INSTALL) {
15318                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15319                                    + " at code path: " + ps.codePathString);
15320                        }
15321
15322                        // We do have a valid package installed on sdcard
15323                        processCids.put(args, ps.codePathString);
15324                        final int uid = ps.appId;
15325                        if (uid != -1) {
15326                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15327                        }
15328                    } else {
15329                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15330                                + ps.codePathString);
15331                    }
15332                }
15333            }
15334
15335            Arrays.sort(uidArr);
15336        }
15337
15338        // Process packages with valid entries.
15339        if (isMounted) {
15340            if (DEBUG_SD_INSTALL)
15341                Log.i(TAG, "Loading packages");
15342            loadMediaPackages(processCids, uidArr);
15343            startCleaningPackages();
15344            mInstallerService.onSecureContainersAvailable();
15345        } else {
15346            if (DEBUG_SD_INSTALL)
15347                Log.i(TAG, "Unloading packages");
15348            unloadMediaPackages(processCids, uidArr, reportStatus);
15349        }
15350    }
15351
15352    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15353            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15354        final int size = infos.size();
15355        final String[] packageNames = new String[size];
15356        final int[] packageUids = new int[size];
15357        for (int i = 0; i < size; i++) {
15358            final ApplicationInfo info = infos.get(i);
15359            packageNames[i] = info.packageName;
15360            packageUids[i] = info.uid;
15361        }
15362        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15363                finishedReceiver);
15364    }
15365
15366    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15367            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15368        sendResourcesChangedBroadcast(mediaStatus, replacing,
15369                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15370    }
15371
15372    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15373            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15374        int size = pkgList.length;
15375        if (size > 0) {
15376            // Send broadcasts here
15377            Bundle extras = new Bundle();
15378            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15379            if (uidArr != null) {
15380                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15381            }
15382            if (replacing) {
15383                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15384            }
15385            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15386                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15387            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15388        }
15389    }
15390
15391   /*
15392     * Look at potentially valid container ids from processCids If package
15393     * information doesn't match the one on record or package scanning fails,
15394     * the cid is added to list of removeCids. We currently don't delete stale
15395     * containers.
15396     */
15397    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15398        ArrayList<String> pkgList = new ArrayList<String>();
15399        Set<AsecInstallArgs> keys = processCids.keySet();
15400
15401        for (AsecInstallArgs args : keys) {
15402            String codePath = processCids.get(args);
15403            if (DEBUG_SD_INSTALL)
15404                Log.i(TAG, "Loading container : " + args.cid);
15405            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15406            try {
15407                // Make sure there are no container errors first.
15408                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15409                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15410                            + " when installing from sdcard");
15411                    continue;
15412                }
15413                // Check code path here.
15414                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15415                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15416                            + " does not match one in settings " + codePath);
15417                    continue;
15418                }
15419                // Parse package
15420                int parseFlags = mDefParseFlags;
15421                if (args.isExternalAsec()) {
15422                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15423                }
15424                if (args.isFwdLocked()) {
15425                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15426                }
15427
15428                synchronized (mInstallLock) {
15429                    PackageParser.Package pkg = null;
15430                    try {
15431                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15432                    } catch (PackageManagerException e) {
15433                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15434                    }
15435                    // Scan the package
15436                    if (pkg != null) {
15437                        /*
15438                         * TODO why is the lock being held? doPostInstall is
15439                         * called in other places without the lock. This needs
15440                         * to be straightened out.
15441                         */
15442                        // writer
15443                        synchronized (mPackages) {
15444                            retCode = PackageManager.INSTALL_SUCCEEDED;
15445                            pkgList.add(pkg.packageName);
15446                            // Post process args
15447                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15448                                    pkg.applicationInfo.uid);
15449                        }
15450                    } else {
15451                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15452                    }
15453                }
15454
15455            } finally {
15456                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15457                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15458                }
15459            }
15460        }
15461        // writer
15462        synchronized (mPackages) {
15463            // If the platform SDK has changed since the last time we booted,
15464            // we need to re-grant app permission to catch any new ones that
15465            // appear. This is really a hack, and means that apps can in some
15466            // cases get permissions that the user didn't initially explicitly
15467            // allow... it would be nice to have some better way to handle
15468            // this situation.
15469            final VersionInfo ver = mSettings.getExternalVersion();
15470
15471            int updateFlags = UPDATE_PERMISSIONS_ALL;
15472            if (ver.sdkVersion != mSdkVersion) {
15473                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15474                        + mSdkVersion + "; regranting permissions for external");
15475                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15476            }
15477            updatePermissionsLPw(null, null, updateFlags);
15478
15479            // Yay, everything is now upgraded
15480            ver.forceCurrent();
15481
15482            // can downgrade to reader
15483            // Persist settings
15484            mSettings.writeLPr();
15485        }
15486        // Send a broadcast to let everyone know we are done processing
15487        if (pkgList.size() > 0) {
15488            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15489        }
15490    }
15491
15492   /*
15493     * Utility method to unload a list of specified containers
15494     */
15495    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15496        // Just unmount all valid containers.
15497        for (AsecInstallArgs arg : cidArgs) {
15498            synchronized (mInstallLock) {
15499                arg.doPostDeleteLI(false);
15500           }
15501       }
15502   }
15503
15504    /*
15505     * Unload packages mounted on external media. This involves deleting package
15506     * data from internal structures, sending broadcasts about diabled packages,
15507     * gc'ing to free up references, unmounting all secure containers
15508     * corresponding to packages on external media, and posting a
15509     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15510     * that we always have to post this message if status has been requested no
15511     * matter what.
15512     */
15513    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15514            final boolean reportStatus) {
15515        if (DEBUG_SD_INSTALL)
15516            Log.i(TAG, "unloading media packages");
15517        ArrayList<String> pkgList = new ArrayList<String>();
15518        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15519        final Set<AsecInstallArgs> keys = processCids.keySet();
15520        for (AsecInstallArgs args : keys) {
15521            String pkgName = args.getPackageName();
15522            if (DEBUG_SD_INSTALL)
15523                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15524            // Delete package internally
15525            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15526            synchronized (mInstallLock) {
15527                boolean res = deletePackageLI(pkgName, null, false, null, null,
15528                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15529                if (res) {
15530                    pkgList.add(pkgName);
15531                } else {
15532                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15533                    failedList.add(args);
15534                }
15535            }
15536        }
15537
15538        // reader
15539        synchronized (mPackages) {
15540            // We didn't update the settings after removing each package;
15541            // write them now for all packages.
15542            mSettings.writeLPr();
15543        }
15544
15545        // We have to absolutely send UPDATED_MEDIA_STATUS only
15546        // after confirming that all the receivers processed the ordered
15547        // broadcast when packages get disabled, force a gc to clean things up.
15548        // and unload all the containers.
15549        if (pkgList.size() > 0) {
15550            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15551                    new IIntentReceiver.Stub() {
15552                public void performReceive(Intent intent, int resultCode, String data,
15553                        Bundle extras, boolean ordered, boolean sticky,
15554                        int sendingUser) throws RemoteException {
15555                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15556                            reportStatus ? 1 : 0, 1, keys);
15557                    mHandler.sendMessage(msg);
15558                }
15559            });
15560        } else {
15561            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15562                    keys);
15563            mHandler.sendMessage(msg);
15564        }
15565    }
15566
15567    private void loadPrivatePackages(VolumeInfo vol) {
15568        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15569        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15570        synchronized (mInstallLock) {
15571        synchronized (mPackages) {
15572            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15573            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15574            for (PackageSetting ps : packages) {
15575                final PackageParser.Package pkg;
15576                try {
15577                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15578                    loaded.add(pkg.applicationInfo);
15579                } catch (PackageManagerException e) {
15580                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15581                }
15582
15583                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15584                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15585                }
15586            }
15587
15588            int updateFlags = UPDATE_PERMISSIONS_ALL;
15589            if (ver.sdkVersion != mSdkVersion) {
15590                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15591                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15592                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15593            }
15594            updatePermissionsLPw(null, null, updateFlags);
15595
15596            // Yay, everything is now upgraded
15597            ver.forceCurrent();
15598
15599            mSettings.writeLPr();
15600        }
15601        }
15602
15603        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15604        sendResourcesChangedBroadcast(true, false, loaded, null);
15605    }
15606
15607    private void unloadPrivatePackages(VolumeInfo vol) {
15608        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15609        synchronized (mInstallLock) {
15610        synchronized (mPackages) {
15611            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15612            for (PackageSetting ps : packages) {
15613                if (ps.pkg == null) continue;
15614
15615                final ApplicationInfo info = ps.pkg.applicationInfo;
15616                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15617                if (deletePackageLI(ps.name, null, false, null, null,
15618                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15619                    unloaded.add(info);
15620                } else {
15621                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15622                }
15623            }
15624
15625            mSettings.writeLPr();
15626        }
15627        }
15628
15629        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15630        sendResourcesChangedBroadcast(false, false, unloaded, null);
15631    }
15632
15633    /**
15634     * Examine all users present on given mounted volume, and destroy data
15635     * belonging to users that are no longer valid, or whose user ID has been
15636     * recycled.
15637     */
15638    private void reconcileUsers(String volumeUuid) {
15639        final File[] files = FileUtils
15640                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15641        for (File file : files) {
15642            if (!file.isDirectory()) continue;
15643
15644            final int userId;
15645            final UserInfo info;
15646            try {
15647                userId = Integer.parseInt(file.getName());
15648                info = sUserManager.getUserInfo(userId);
15649            } catch (NumberFormatException e) {
15650                Slog.w(TAG, "Invalid user directory " + file);
15651                continue;
15652            }
15653
15654            boolean destroyUser = false;
15655            if (info == null) {
15656                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15657                        + " because no matching user was found");
15658                destroyUser = true;
15659            } else {
15660                try {
15661                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15662                } catch (IOException e) {
15663                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15664                            + " because we failed to enforce serial number: " + e);
15665                    destroyUser = true;
15666                }
15667            }
15668
15669            if (destroyUser) {
15670                synchronized (mInstallLock) {
15671                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15672                }
15673            }
15674        }
15675
15676        final UserManager um = mContext.getSystemService(UserManager.class);
15677        for (UserInfo user : um.getUsers()) {
15678            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15679            if (userDir.exists()) continue;
15680
15681            try {
15682                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15683                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15684            } catch (IOException e) {
15685                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15686            }
15687        }
15688    }
15689
15690    /**
15691     * Examine all apps present on given mounted volume, and destroy apps that
15692     * aren't expected, either due to uninstallation or reinstallation on
15693     * another volume.
15694     */
15695    private void reconcileApps(String volumeUuid) {
15696        final File[] files = FileUtils
15697                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15698        for (File file : files) {
15699            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15700                    && !PackageInstallerService.isStageName(file.getName());
15701            if (!isPackage) {
15702                // Ignore entries which are not packages
15703                continue;
15704            }
15705
15706            boolean destroyApp = false;
15707            String packageName = null;
15708            try {
15709                final PackageLite pkg = PackageParser.parsePackageLite(file,
15710                        PackageParser.PARSE_MUST_BE_APK);
15711                packageName = pkg.packageName;
15712
15713                synchronized (mPackages) {
15714                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15715                    if (ps == null) {
15716                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15717                                + volumeUuid + " because we found no install record");
15718                        destroyApp = true;
15719                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15720                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15721                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15722                        destroyApp = true;
15723                    }
15724                }
15725
15726            } catch (PackageParserException e) {
15727                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15728                destroyApp = true;
15729            }
15730
15731            if (destroyApp) {
15732                synchronized (mInstallLock) {
15733                    if (packageName != null) {
15734                        removeDataDirsLI(volumeUuid, packageName);
15735                    }
15736                    if (file.isDirectory()) {
15737                        mInstaller.rmPackageDir(file.getAbsolutePath());
15738                    } else {
15739                        file.delete();
15740                    }
15741                }
15742            }
15743        }
15744    }
15745
15746    private void unfreezePackage(String packageName) {
15747        synchronized (mPackages) {
15748            final PackageSetting ps = mSettings.mPackages.get(packageName);
15749            if (ps != null) {
15750                ps.frozen = false;
15751            }
15752        }
15753    }
15754
15755    @Override
15756    public int movePackage(final String packageName, final String volumeUuid) {
15757        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15758
15759        final int moveId = mNextMoveId.getAndIncrement();
15760        try {
15761            movePackageInternal(packageName, volumeUuid, moveId);
15762        } catch (PackageManagerException e) {
15763            Slog.w(TAG, "Failed to move " + packageName, e);
15764            mMoveCallbacks.notifyStatusChanged(moveId,
15765                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15766        }
15767        return moveId;
15768    }
15769
15770    private void movePackageInternal(final String packageName, final String volumeUuid,
15771            final int moveId) throws PackageManagerException {
15772        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15773        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15774        final PackageManager pm = mContext.getPackageManager();
15775
15776        final boolean currentAsec;
15777        final String currentVolumeUuid;
15778        final File codeFile;
15779        final String installerPackageName;
15780        final String packageAbiOverride;
15781        final int appId;
15782        final String seinfo;
15783        final String label;
15784
15785        // reader
15786        synchronized (mPackages) {
15787            final PackageParser.Package pkg = mPackages.get(packageName);
15788            final PackageSetting ps = mSettings.mPackages.get(packageName);
15789            if (pkg == null || ps == null) {
15790                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15791            }
15792
15793            if (pkg.applicationInfo.isSystemApp()) {
15794                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15795                        "Cannot move system application");
15796            }
15797
15798            if (pkg.applicationInfo.isExternalAsec()) {
15799                currentAsec = true;
15800                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15801            } else if (pkg.applicationInfo.isForwardLocked()) {
15802                currentAsec = true;
15803                currentVolumeUuid = "forward_locked";
15804            } else {
15805                currentAsec = false;
15806                currentVolumeUuid = ps.volumeUuid;
15807
15808                final File probe = new File(pkg.codePath);
15809                final File probeOat = new File(probe, "oat");
15810                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15811                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15812                            "Move only supported for modern cluster style installs");
15813                }
15814            }
15815
15816            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15817                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15818                        "Package already moved to " + volumeUuid);
15819            }
15820
15821            if (ps.frozen) {
15822                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15823                        "Failed to move already frozen package");
15824            }
15825            ps.frozen = true;
15826
15827            codeFile = new File(pkg.codePath);
15828            installerPackageName = ps.installerPackageName;
15829            packageAbiOverride = ps.cpuAbiOverrideString;
15830            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15831            seinfo = pkg.applicationInfo.seinfo;
15832            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15833        }
15834
15835        // Now that we're guarded by frozen state, kill app during move
15836        final long token = Binder.clearCallingIdentity();
15837        try {
15838            killApplication(packageName, appId, "move pkg");
15839        } finally {
15840            Binder.restoreCallingIdentity(token);
15841        }
15842
15843        final Bundle extras = new Bundle();
15844        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15845        extras.putString(Intent.EXTRA_TITLE, label);
15846        mMoveCallbacks.notifyCreated(moveId, extras);
15847
15848        int installFlags;
15849        final boolean moveCompleteApp;
15850        final File measurePath;
15851
15852        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15853            installFlags = INSTALL_INTERNAL;
15854            moveCompleteApp = !currentAsec;
15855            measurePath = Environment.getDataAppDirectory(volumeUuid);
15856        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15857            installFlags = INSTALL_EXTERNAL;
15858            moveCompleteApp = false;
15859            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15860        } else {
15861            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15862            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15863                    || !volume.isMountedWritable()) {
15864                unfreezePackage(packageName);
15865                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15866                        "Move location not mounted private volume");
15867            }
15868
15869            Preconditions.checkState(!currentAsec);
15870
15871            installFlags = INSTALL_INTERNAL;
15872            moveCompleteApp = true;
15873            measurePath = Environment.getDataAppDirectory(volumeUuid);
15874        }
15875
15876        final PackageStats stats = new PackageStats(null, -1);
15877        synchronized (mInstaller) {
15878            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15879                unfreezePackage(packageName);
15880                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15881                        "Failed to measure package size");
15882            }
15883        }
15884
15885        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15886                + stats.dataSize);
15887
15888        final long startFreeBytes = measurePath.getFreeSpace();
15889        final long sizeBytes;
15890        if (moveCompleteApp) {
15891            sizeBytes = stats.codeSize + stats.dataSize;
15892        } else {
15893            sizeBytes = stats.codeSize;
15894        }
15895
15896        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15897            unfreezePackage(packageName);
15898            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15899                    "Not enough free space to move");
15900        }
15901
15902        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15903
15904        final CountDownLatch installedLatch = new CountDownLatch(1);
15905        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15906            @Override
15907            public void onUserActionRequired(Intent intent) throws RemoteException {
15908                throw new IllegalStateException();
15909            }
15910
15911            @Override
15912            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15913                    Bundle extras) throws RemoteException {
15914                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15915                        + PackageManager.installStatusToString(returnCode, msg));
15916
15917                installedLatch.countDown();
15918
15919                // Regardless of success or failure of the move operation,
15920                // always unfreeze the package
15921                unfreezePackage(packageName);
15922
15923                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15924                switch (status) {
15925                    case PackageInstaller.STATUS_SUCCESS:
15926                        mMoveCallbacks.notifyStatusChanged(moveId,
15927                                PackageManager.MOVE_SUCCEEDED);
15928                        break;
15929                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15930                        mMoveCallbacks.notifyStatusChanged(moveId,
15931                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15932                        break;
15933                    default:
15934                        mMoveCallbacks.notifyStatusChanged(moveId,
15935                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15936                        break;
15937                }
15938            }
15939        };
15940
15941        final MoveInfo move;
15942        if (moveCompleteApp) {
15943            // Kick off a thread to report progress estimates
15944            new Thread() {
15945                @Override
15946                public void run() {
15947                    while (true) {
15948                        try {
15949                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15950                                break;
15951                            }
15952                        } catch (InterruptedException ignored) {
15953                        }
15954
15955                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15956                        final int progress = 10 + (int) MathUtils.constrain(
15957                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15958                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15959                    }
15960                }
15961            }.start();
15962
15963            final String dataAppName = codeFile.getName();
15964            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15965                    dataAppName, appId, seinfo);
15966        } else {
15967            move = null;
15968        }
15969
15970        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15971
15972        final Message msg = mHandler.obtainMessage(INIT_COPY);
15973        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15974        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15975                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15976        mHandler.sendMessage(msg);
15977    }
15978
15979    @Override
15980    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15981        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15982
15983        final int realMoveId = mNextMoveId.getAndIncrement();
15984        final Bundle extras = new Bundle();
15985        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15986        mMoveCallbacks.notifyCreated(realMoveId, extras);
15987
15988        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15989            @Override
15990            public void onCreated(int moveId, Bundle extras) {
15991                // Ignored
15992            }
15993
15994            @Override
15995            public void onStatusChanged(int moveId, int status, long estMillis) {
15996                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15997            }
15998        };
15999
16000        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16001        storage.setPrimaryStorageUuid(volumeUuid, callback);
16002        return realMoveId;
16003    }
16004
16005    @Override
16006    public int getMoveStatus(int moveId) {
16007        mContext.enforceCallingOrSelfPermission(
16008                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16009        return mMoveCallbacks.mLastStatus.get(moveId);
16010    }
16011
16012    @Override
16013    public void registerMoveCallback(IPackageMoveObserver callback) {
16014        mContext.enforceCallingOrSelfPermission(
16015                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16016        mMoveCallbacks.register(callback);
16017    }
16018
16019    @Override
16020    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16021        mContext.enforceCallingOrSelfPermission(
16022                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16023        mMoveCallbacks.unregister(callback);
16024    }
16025
16026    @Override
16027    public boolean setInstallLocation(int loc) {
16028        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16029                null);
16030        if (getInstallLocation() == loc) {
16031            return true;
16032        }
16033        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16034                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16035            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16036                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16037            return true;
16038        }
16039        return false;
16040   }
16041
16042    @Override
16043    public int getInstallLocation() {
16044        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16045                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16046                PackageHelper.APP_INSTALL_AUTO);
16047    }
16048
16049    /** Called by UserManagerService */
16050    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16051        mDirtyUsers.remove(userHandle);
16052        mSettings.removeUserLPw(userHandle);
16053        mPendingBroadcasts.remove(userHandle);
16054        if (mInstaller != null) {
16055            // Technically, we shouldn't be doing this with the package lock
16056            // held.  However, this is very rare, and there is already so much
16057            // other disk I/O going on, that we'll let it slide for now.
16058            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16059            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16060                final String volumeUuid = vol.getFsUuid();
16061                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16062                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16063            }
16064        }
16065        mUserNeedsBadging.delete(userHandle);
16066        removeUnusedPackagesLILPw(userManager, userHandle);
16067    }
16068
16069    /**
16070     * We're removing userHandle and would like to remove any downloaded packages
16071     * that are no longer in use by any other user.
16072     * @param userHandle the user being removed
16073     */
16074    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16075        final boolean DEBUG_CLEAN_APKS = false;
16076        int [] users = userManager.getUserIdsLPr();
16077        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16078        while (psit.hasNext()) {
16079            PackageSetting ps = psit.next();
16080            if (ps.pkg == null) {
16081                continue;
16082            }
16083            final String packageName = ps.pkg.packageName;
16084            // Skip over if system app
16085            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16086                continue;
16087            }
16088            if (DEBUG_CLEAN_APKS) {
16089                Slog.i(TAG, "Checking package " + packageName);
16090            }
16091            boolean keep = false;
16092            for (int i = 0; i < users.length; i++) {
16093                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16094                    keep = true;
16095                    if (DEBUG_CLEAN_APKS) {
16096                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16097                                + users[i]);
16098                    }
16099                    break;
16100                }
16101            }
16102            if (!keep) {
16103                if (DEBUG_CLEAN_APKS) {
16104                    Slog.i(TAG, "  Removing package " + packageName);
16105                }
16106                mHandler.post(new Runnable() {
16107                    public void run() {
16108                        deletePackageX(packageName, userHandle, 0);
16109                    } //end run
16110                });
16111            }
16112        }
16113    }
16114
16115    /** Called by UserManagerService */
16116    void createNewUserLILPw(int userHandle) {
16117        if (mInstaller != null) {
16118            mInstaller.createUserConfig(userHandle);
16119            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16120            applyFactoryDefaultBrowserLPw(userHandle);
16121            primeDomainVerificationsLPw(userHandle);
16122        }
16123    }
16124
16125    void newUserCreated(final int userHandle) {
16126        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16127    }
16128
16129    @Override
16130    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16131        mContext.enforceCallingOrSelfPermission(
16132                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16133                "Only package verification agents can read the verifier device identity");
16134
16135        synchronized (mPackages) {
16136            return mSettings.getVerifierDeviceIdentityLPw();
16137        }
16138    }
16139
16140    @Override
16141    public void setPermissionEnforced(String permission, boolean enforced) {
16142        // TODO: Now that we no longer change GID for storage, this should to away.
16143        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16144                "setPermissionEnforced");
16145        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16146            synchronized (mPackages) {
16147                if (mSettings.mReadExternalStorageEnforced == null
16148                        || mSettings.mReadExternalStorageEnforced != enforced) {
16149                    mSettings.mReadExternalStorageEnforced = enforced;
16150                    mSettings.writeLPr();
16151                }
16152            }
16153            // kill any non-foreground processes so we restart them and
16154            // grant/revoke the GID.
16155            final IActivityManager am = ActivityManagerNative.getDefault();
16156            if (am != null) {
16157                final long token = Binder.clearCallingIdentity();
16158                try {
16159                    am.killProcessesBelowForeground("setPermissionEnforcement");
16160                } catch (RemoteException e) {
16161                } finally {
16162                    Binder.restoreCallingIdentity(token);
16163                }
16164            }
16165        } else {
16166            throw new IllegalArgumentException("No selective enforcement for " + permission);
16167        }
16168    }
16169
16170    @Override
16171    @Deprecated
16172    public boolean isPermissionEnforced(String permission) {
16173        return true;
16174    }
16175
16176    @Override
16177    public boolean isStorageLow() {
16178        final long token = Binder.clearCallingIdentity();
16179        try {
16180            final DeviceStorageMonitorInternal
16181                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16182            if (dsm != null) {
16183                return dsm.isMemoryLow();
16184            } else {
16185                return false;
16186            }
16187        } finally {
16188            Binder.restoreCallingIdentity(token);
16189        }
16190    }
16191
16192    @Override
16193    public IPackageInstaller getPackageInstaller() {
16194        return mInstallerService;
16195    }
16196
16197    private boolean userNeedsBadging(int userId) {
16198        int index = mUserNeedsBadging.indexOfKey(userId);
16199        if (index < 0) {
16200            final UserInfo userInfo;
16201            final long token = Binder.clearCallingIdentity();
16202            try {
16203                userInfo = sUserManager.getUserInfo(userId);
16204            } finally {
16205                Binder.restoreCallingIdentity(token);
16206            }
16207            final boolean b;
16208            if (userInfo != null && userInfo.isManagedProfile()) {
16209                b = true;
16210            } else {
16211                b = false;
16212            }
16213            mUserNeedsBadging.put(userId, b);
16214            return b;
16215        }
16216        return mUserNeedsBadging.valueAt(index);
16217    }
16218
16219    @Override
16220    public KeySet getKeySetByAlias(String packageName, String alias) {
16221        if (packageName == null || alias == null) {
16222            return null;
16223        }
16224        synchronized(mPackages) {
16225            final PackageParser.Package pkg = mPackages.get(packageName);
16226            if (pkg == null) {
16227                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16228                throw new IllegalArgumentException("Unknown package: " + packageName);
16229            }
16230            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16231            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16232        }
16233    }
16234
16235    @Override
16236    public KeySet getSigningKeySet(String packageName) {
16237        if (packageName == null) {
16238            return null;
16239        }
16240        synchronized(mPackages) {
16241            final PackageParser.Package pkg = mPackages.get(packageName);
16242            if (pkg == null) {
16243                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16244                throw new IllegalArgumentException("Unknown package: " + packageName);
16245            }
16246            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16247                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16248                throw new SecurityException("May not access signing KeySet of other apps.");
16249            }
16250            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16251            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16252        }
16253    }
16254
16255    @Override
16256    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16257        if (packageName == null || ks == null) {
16258            return false;
16259        }
16260        synchronized(mPackages) {
16261            final PackageParser.Package pkg = mPackages.get(packageName);
16262            if (pkg == null) {
16263                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16264                throw new IllegalArgumentException("Unknown package: " + packageName);
16265            }
16266            IBinder ksh = ks.getToken();
16267            if (ksh instanceof KeySetHandle) {
16268                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16269                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16270            }
16271            return false;
16272        }
16273    }
16274
16275    @Override
16276    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16277        if (packageName == null || ks == null) {
16278            return false;
16279        }
16280        synchronized(mPackages) {
16281            final PackageParser.Package pkg = mPackages.get(packageName);
16282            if (pkg == null) {
16283                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16284                throw new IllegalArgumentException("Unknown package: " + packageName);
16285            }
16286            IBinder ksh = ks.getToken();
16287            if (ksh instanceof KeySetHandle) {
16288                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16289                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16290            }
16291            return false;
16292        }
16293    }
16294
16295    public void getUsageStatsIfNoPackageUsageInfo() {
16296        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16297            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16298            if (usm == null) {
16299                throw new IllegalStateException("UsageStatsManager must be initialized");
16300            }
16301            long now = System.currentTimeMillis();
16302            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16303            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16304                String packageName = entry.getKey();
16305                PackageParser.Package pkg = mPackages.get(packageName);
16306                if (pkg == null) {
16307                    continue;
16308                }
16309                UsageStats usage = entry.getValue();
16310                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16311                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16312            }
16313        }
16314    }
16315
16316    /**
16317     * Check and throw if the given before/after packages would be considered a
16318     * downgrade.
16319     */
16320    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16321            throws PackageManagerException {
16322        if (after.versionCode < before.mVersionCode) {
16323            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16324                    "Update version code " + after.versionCode + " is older than current "
16325                    + before.mVersionCode);
16326        } else if (after.versionCode == before.mVersionCode) {
16327            if (after.baseRevisionCode < before.baseRevisionCode) {
16328                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16329                        "Update base revision code " + after.baseRevisionCode
16330                        + " is older than current " + before.baseRevisionCode);
16331            }
16332
16333            if (!ArrayUtils.isEmpty(after.splitNames)) {
16334                for (int i = 0; i < after.splitNames.length; i++) {
16335                    final String splitName = after.splitNames[i];
16336                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16337                    if (j != -1) {
16338                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16339                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16340                                    "Update split " + splitName + " revision code "
16341                                    + after.splitRevisionCodes[i] + " is older than current "
16342                                    + before.splitRevisionCodes[j]);
16343                        }
16344                    }
16345                }
16346            }
16347        }
16348    }
16349
16350    private static class MoveCallbacks extends Handler {
16351        private static final int MSG_CREATED = 1;
16352        private static final int MSG_STATUS_CHANGED = 2;
16353
16354        private final RemoteCallbackList<IPackageMoveObserver>
16355                mCallbacks = new RemoteCallbackList<>();
16356
16357        private final SparseIntArray mLastStatus = new SparseIntArray();
16358
16359        public MoveCallbacks(Looper looper) {
16360            super(looper);
16361        }
16362
16363        public void register(IPackageMoveObserver callback) {
16364            mCallbacks.register(callback);
16365        }
16366
16367        public void unregister(IPackageMoveObserver callback) {
16368            mCallbacks.unregister(callback);
16369        }
16370
16371        @Override
16372        public void handleMessage(Message msg) {
16373            final SomeArgs args = (SomeArgs) msg.obj;
16374            final int n = mCallbacks.beginBroadcast();
16375            for (int i = 0; i < n; i++) {
16376                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16377                try {
16378                    invokeCallback(callback, msg.what, args);
16379                } catch (RemoteException ignored) {
16380                }
16381            }
16382            mCallbacks.finishBroadcast();
16383            args.recycle();
16384        }
16385
16386        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16387                throws RemoteException {
16388            switch (what) {
16389                case MSG_CREATED: {
16390                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16391                    break;
16392                }
16393                case MSG_STATUS_CHANGED: {
16394                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16395                    break;
16396                }
16397            }
16398        }
16399
16400        private void notifyCreated(int moveId, Bundle extras) {
16401            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16402
16403            final SomeArgs args = SomeArgs.obtain();
16404            args.argi1 = moveId;
16405            args.arg2 = extras;
16406            obtainMessage(MSG_CREATED, args).sendToTarget();
16407        }
16408
16409        private void notifyStatusChanged(int moveId, int status) {
16410            notifyStatusChanged(moveId, status, -1);
16411        }
16412
16413        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16414            Slog.v(TAG, "Move " + moveId + " status " + status);
16415
16416            final SomeArgs args = SomeArgs.obtain();
16417            args.argi1 = moveId;
16418            args.argi2 = status;
16419            args.arg3 = estMillis;
16420            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16421
16422            synchronized (mLastStatus) {
16423                mLastStatus.put(moveId, status);
16424            }
16425        }
16426    }
16427
16428    private final class OnPermissionChangeListeners extends Handler {
16429        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16430
16431        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16432                new RemoteCallbackList<>();
16433
16434        public OnPermissionChangeListeners(Looper looper) {
16435            super(looper);
16436        }
16437
16438        @Override
16439        public void handleMessage(Message msg) {
16440            switch (msg.what) {
16441                case MSG_ON_PERMISSIONS_CHANGED: {
16442                    final int uid = msg.arg1;
16443                    handleOnPermissionsChanged(uid);
16444                } break;
16445            }
16446        }
16447
16448        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16449            mPermissionListeners.register(listener);
16450
16451        }
16452
16453        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16454            mPermissionListeners.unregister(listener);
16455        }
16456
16457        public void onPermissionsChanged(int uid) {
16458            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16459                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16460            }
16461        }
16462
16463        private void handleOnPermissionsChanged(int uid) {
16464            final int count = mPermissionListeners.beginBroadcast();
16465            try {
16466                for (int i = 0; i < count; i++) {
16467                    IOnPermissionsChangeListener callback = mPermissionListeners
16468                            .getBroadcastItem(i);
16469                    try {
16470                        callback.onPermissionsChanged(uid);
16471                    } catch (RemoteException e) {
16472                        Log.e(TAG, "Permission listener is dead", e);
16473                    }
16474                }
16475            } finally {
16476                mPermissionListeners.finishBroadcast();
16477            }
16478        }
16479    }
16480
16481    private class PackageManagerInternalImpl extends PackageManagerInternal {
16482        @Override
16483        public void setLocationPackagesProvider(PackagesProvider provider) {
16484            synchronized (mPackages) {
16485                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16486            }
16487        }
16488
16489        @Override
16490        public void setImePackagesProvider(PackagesProvider provider) {
16491            synchronized (mPackages) {
16492                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16493            }
16494        }
16495
16496        @Override
16497        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16498            synchronized (mPackages) {
16499                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16500            }
16501        }
16502
16503        @Override
16504        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16505            synchronized (mPackages) {
16506                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16507            }
16508        }
16509
16510        @Override
16511        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16512            synchronized (mPackages) {
16513                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16514            }
16515        }
16516
16517        @Override
16518        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16519            synchronized (mPackages) {
16520                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16521            }
16522        }
16523
16524        @Override
16525        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16526            synchronized (mPackages) {
16527                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16528            }
16529        }
16530
16531        @Override
16532        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16533            synchronized (mPackages) {
16534                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16535                        packageName, userId);
16536            }
16537        }
16538
16539        @Override
16540        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16541            synchronized (mPackages) {
16542                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16543                        packageName, userId);
16544            }
16545        }
16546        @Override
16547        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16548            synchronized (mPackages) {
16549                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16550                        packageName, userId);
16551            }
16552        }
16553    }
16554
16555    @Override
16556    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16557        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16558        synchronized (mPackages) {
16559            final long identity = Binder.clearCallingIdentity();
16560            try {
16561                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16562                        packageNames, userId);
16563            } finally {
16564                Binder.restoreCallingIdentity(identity);
16565            }
16566        }
16567    }
16568
16569    private static void enforceSystemOrPhoneCaller(String tag) {
16570        int callingUid = Binder.getCallingUid();
16571        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16572            throw new SecurityException(
16573                    "Cannot call " + tag + " from UID " + callingUid);
16574        }
16575    }
16576}
16577