PackageManagerService.java revision 40cda8ef7c2e91fe1557a8cc35e01b91acf1def8
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 = Build.IS_DEBUGGABLE;
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_REQUIRE_KNOWN = 1<<12;
327    static final int SCAN_MOVE = 1<<13;
328    static final int SCAN_INITIAL = 1<<14;
329
330    static final int REMOVE_CHATTY = 1<<16;
331
332    private static final int[] EMPTY_INT_ARRAY = new int[0];
333
334    /**
335     * Timeout (in milliseconds) after which the watchdog should declare that
336     * our handler thread is wedged.  The usual default for such things is one
337     * minute but we sometimes do very lengthy I/O operations on this thread,
338     * such as installing multi-gigabyte applications, so ours needs to be longer.
339     */
340    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
341
342    /**
343     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
344     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
345     * settings entry if available, otherwise we use the hardcoded default.  If it's been
346     * more than this long since the last fstrim, we force one during the boot sequence.
347     *
348     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
349     * one gets run at the next available charging+idle time.  This final mandatory
350     * no-fstrim check kicks in only of the other scheduling criteria is never met.
351     */
352    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
353
354    /**
355     * Whether verification is enabled by default.
356     */
357    private static final boolean DEFAULT_VERIFY_ENABLE = true;
358
359    /**
360     * The default maximum time to wait for the verification agent to return in
361     * milliseconds.
362     */
363    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
364
365    /**
366     * The default response for package verification timeout.
367     *
368     * This can be either PackageManager.VERIFICATION_ALLOW or
369     * PackageManager.VERIFICATION_REJECT.
370     */
371    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
372
373    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
374
375    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
376            DEFAULT_CONTAINER_PACKAGE,
377            "com.android.defcontainer.DefaultContainerService");
378
379    private static final String KILL_APP_REASON_GIDS_CHANGED =
380            "permission grant or revoke changed gids";
381
382    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
383            "permissions revoked";
384
385    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
386
387    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
388
389    /** Permission grant: not grant the permission. */
390    private static final int GRANT_DENIED = 1;
391
392    /** Permission grant: grant the permission as an install permission. */
393    private static final int GRANT_INSTALL = 2;
394
395    /** Permission grant: grant the permission as an install permission for a legacy app. */
396    private static final int GRANT_INSTALL_LEGACY = 3;
397
398    /** Permission grant: grant the permission as a runtime one. */
399    private static final int GRANT_RUNTIME = 4;
400
401    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
402    private static final int GRANT_UPGRADE = 5;
403
404    /** Canonical intent used to identify what counts as a "web browser" app */
405    private static final Intent sBrowserIntent;
406    static {
407        sBrowserIntent = new Intent();
408        sBrowserIntent.setAction(Intent.ACTION_VIEW);
409        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
410        sBrowserIntent.setData(Uri.parse("http:"));
411    }
412
413    final ServiceThread mHandlerThread;
414
415    final PackageHandler mHandler;
416
417    /**
418     * Messages for {@link #mHandler} that need to wait for system ready before
419     * being dispatched.
420     */
421    private ArrayList<Message> mPostSystemReadyMessages;
422
423    final int mSdkVersion = Build.VERSION.SDK_INT;
424
425    final Context mContext;
426    final boolean mFactoryTest;
427    final boolean mOnlyCore;
428    final boolean mLazyDexOpt;
429    final long mDexOptLRUThresholdInMills;
430    final DisplayMetrics mMetrics;
431    final int mDefParseFlags;
432    final String[] mSeparateProcesses;
433    final boolean mIsUpgrade;
434
435    // This is where all application persistent data goes.
436    final File mAppDataDir;
437
438    // This is where all application persistent data goes for secondary users.
439    final File mUserAppDataDir;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451
452    /**
453     * Directory to which applications installed internally have their
454     * 32 bit native libraries copied.
455     */
456    private File mAppLib32InstallDir;
457
458    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
459    // apps.
460    final File mDrmAppPrivateInstallDir;
461
462    // ----------------------------------------------------------------
463
464    // Lock for state used when installing and doing other long running
465    // operations.  Methods that must be called with this lock held have
466    // the suffix "LI".
467    final Object mInstallLock = new Object();
468
469    // ----------------------------------------------------------------
470
471    // Keys are String (package name), values are Package.  This also serves
472    // as the lock for the global state.  Methods that must be called with
473    // this lock held have the prefix "LP".
474    @GuardedBy("mPackages")
475    final ArrayMap<String, PackageParser.Package> mPackages =
476            new ArrayMap<String, PackageParser.Package>();
477
478    // Tracks available target package names -> overlay package paths.
479    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
480        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
481
482    /**
483     * Tracks new system packages [receiving in an OTA] that we expect to
484     * find updated user-installed versions. Keys are package name, values
485     * are package location.
486     */
487    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
488
489    final Settings mSettings;
490    boolean mRestoredSettings;
491
492    // System configuration read by SystemConfig.
493    final int[] mGlobalGids;
494    final SparseArray<ArraySet<String>> mSystemPermissions;
495    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
496
497    // If mac_permissions.xml was found for seinfo labeling.
498    boolean mFoundPolicyFile;
499
500    // If a recursive restorecon of /data/data/<pkg> is needed.
501    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
502
503    public static final class SharedLibraryEntry {
504        public final String path;
505        public final String apk;
506
507        SharedLibraryEntry(String _path, String _apk) {
508            path = _path;
509            apk = _apk;
510        }
511    }
512
513    // Currently known shared libraries.
514    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
515            new ArrayMap<String, SharedLibraryEntry>();
516
517    // All available activities, for your resolving pleasure.
518    final ActivityIntentResolver mActivities =
519            new ActivityIntentResolver();
520
521    // All available receivers, for your resolving pleasure.
522    final ActivityIntentResolver mReceivers =
523            new ActivityIntentResolver();
524
525    // All available services, for your resolving pleasure.
526    final ServiceIntentResolver mServices = new ServiceIntentResolver();
527
528    // All available providers, for your resolving pleasure.
529    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
530
531    // Mapping from provider base names (first directory in content URI codePath)
532    // to the provider information.
533    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
534            new ArrayMap<String, PackageParser.Provider>();
535
536    // Mapping from instrumentation class names to info about them.
537    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
538            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
539
540    // Mapping from permission names to info about them.
541    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
542            new ArrayMap<String, PackageParser.PermissionGroup>();
543
544    // Packages whose data we have transfered into another package, thus
545    // should no longer exist.
546    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
547
548    // Broadcast actions that are only available to the system.
549    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
550
551    /** List of packages waiting for verification. */
552    final SparseArray<PackageVerificationState> mPendingVerification
553            = new SparseArray<PackageVerificationState>();
554
555    /** Set of packages associated with each app op permission. */
556    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
557
558    final PackageInstallerService mInstallerService;
559
560    private final PackageDexOptimizer mPackageDexOptimizer;
561
562    private AtomicInteger mNextMoveId = new AtomicInteger();
563    private final MoveCallbacks mMoveCallbacks;
564
565    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
566
567    // Cache of users who need badging.
568    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
569
570    /** Token for keys in mPendingVerification. */
571    private int mPendingVerificationToken = 0;
572
573    volatile boolean mSystemReady;
574    volatile boolean mSafeMode;
575    volatile boolean mHasSystemUidErrors;
576
577    ApplicationInfo mAndroidApplication;
578    final ActivityInfo mResolveActivity = new ActivityInfo();
579    final ResolveInfo mResolveInfo = new ResolveInfo();
580    ComponentName mResolveComponentName;
581    PackageParser.Package mPlatformPackage;
582    ComponentName mCustomResolverComponentName;
583
584    boolean mResolverReplaced = false;
585
586    private final ComponentName mIntentFilterVerifierComponent;
587    private int mIntentFilterVerificationToken = 0;
588
589    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
590            = new SparseArray<IntentFilterVerificationState>();
591
592    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
593            new DefaultPermissionGrantPolicy(this);
594
595    private static class IFVerificationParams {
596        PackageParser.Package pkg;
597        boolean replacing;
598        int userId;
599        int verifierUid;
600
601        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
602                int _userId, int _verifierUid) {
603            pkg = _pkg;
604            replacing = _replacing;
605            userId = _userId;
606            replacing = _replacing;
607            verifierUid = _verifierUid;
608        }
609    }
610
611    private interface IntentFilterVerifier<T extends IntentFilter> {
612        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
613                                               T filter, String packageName);
614        void startVerifications(int userId);
615        void receiveVerificationResponse(int verificationId);
616    }
617
618    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
619        private Context mContext;
620        private ComponentName mIntentFilterVerifierComponent;
621        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
622
623        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
624            mContext = context;
625            mIntentFilterVerifierComponent = verifierComponent;
626        }
627
628        private String getDefaultScheme() {
629            return IntentFilter.SCHEME_HTTPS;
630        }
631
632        @Override
633        public void startVerifications(int userId) {
634            // Launch verifications requests
635            int count = mCurrentIntentFilterVerifications.size();
636            for (int n=0; n<count; n++) {
637                int verificationId = mCurrentIntentFilterVerifications.get(n);
638                final IntentFilterVerificationState ivs =
639                        mIntentFilterVerificationStates.get(verificationId);
640
641                String packageName = ivs.getPackageName();
642
643                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
644                final int filterCount = filters.size();
645                ArraySet<String> domainsSet = new ArraySet<>();
646                for (int m=0; m<filterCount; m++) {
647                    PackageParser.ActivityIntentInfo filter = filters.get(m);
648                    domainsSet.addAll(filter.getHostsList());
649                }
650                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
651                synchronized (mPackages) {
652                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
653                            packageName, domainsList) != null) {
654                        scheduleWriteSettingsLocked();
655                    }
656                }
657                sendVerificationRequest(userId, verificationId, ivs);
658            }
659            mCurrentIntentFilterVerifications.clear();
660        }
661
662        private void sendVerificationRequest(int userId, int verificationId,
663                IntentFilterVerificationState ivs) {
664
665            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
668                    verificationId);
669            verificationIntent.putExtra(
670                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
671                    getDefaultScheme());
672            verificationIntent.putExtra(
673                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
674                    ivs.getHostsString());
675            verificationIntent.putExtra(
676                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
677                    ivs.getPackageName());
678            verificationIntent.setComponent(mIntentFilterVerifierComponent);
679            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
680
681            UserHandle user = new UserHandle(userId);
682            mContext.sendBroadcastAsUser(verificationIntent, user);
683            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
684                    "Sending IntentFilter verification broadcast");
685        }
686
687        public void receiveVerificationResponse(int verificationId) {
688            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
689
690            final boolean verified = ivs.isVerified();
691
692            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
693            final int count = filters.size();
694            if (DEBUG_DOMAIN_VERIFICATION) {
695                Slog.i(TAG, "Received verification response " + verificationId
696                        + " for " + count + " filters, verified=" + verified);
697            }
698            for (int n=0; n<count; n++) {
699                PackageParser.ActivityIntentInfo filter = filters.get(n);
700                filter.setVerified(verified);
701
702                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
703                        + " verified with result:" + verified + " and hosts:"
704                        + ivs.getHostsString());
705            }
706
707            mIntentFilterVerificationStates.remove(verificationId);
708
709            final String packageName = ivs.getPackageName();
710            IntentFilterVerificationInfo ivi = null;
711
712            synchronized (mPackages) {
713                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
714            }
715            if (ivi == null) {
716                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
717                        + verificationId + " packageName:" + packageName);
718                return;
719            }
720            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
721                    "Updating IntentFilterVerificationInfo for package " + packageName
722                            +" verificationId:" + verificationId);
723
724            synchronized (mPackages) {
725                if (verified) {
726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
727                } else {
728                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
729                }
730                scheduleWriteSettingsLocked();
731
732                final int userId = ivs.getUserId();
733                if (userId != UserHandle.USER_ALL) {
734                    final int userStatus =
735                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
736
737                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
738                    boolean needUpdate = false;
739
740                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
741                    // already been set by the User thru the Disambiguation dialog
742                    switch (userStatus) {
743                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
744                            if (verified) {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
746                            } else {
747                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
748                            }
749                            needUpdate = true;
750                            break;
751
752                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
753                            if (verified) {
754                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
755                                needUpdate = true;
756                            }
757                            break;
758
759                        default:
760                            // Nothing to do
761                    }
762
763                    if (needUpdate) {
764                        mSettings.updateIntentFilterVerificationStatusLPw(
765                                packageName, updatedStatus, userId);
766                        scheduleWritePackageRestrictionsLocked(userId);
767                    }
768                }
769            }
770        }
771
772        @Override
773        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
774                    ActivityIntentInfo filter, String packageName) {
775            if (!hasValidDomains(filter)) {
776                return false;
777            }
778            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
779            if (ivs == null) {
780                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
781                        packageName);
782            }
783            if (DEBUG_DOMAIN_VERIFICATION) {
784                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
785            }
786            ivs.addFilter(filter);
787            return true;
788        }
789
790        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
791                int userId, int verificationId, String packageName) {
792            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
793                    verifierUid, userId, packageName);
794            ivs.setPendingState();
795            synchronized (mPackages) {
796                mIntentFilterVerificationStates.append(verificationId, ivs);
797                mCurrentIntentFilterVerifications.add(verificationId);
798            }
799            return ivs;
800        }
801    }
802
803    private static boolean hasValidDomains(ActivityIntentInfo filter) {
804        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
805                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
806                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
807    }
808
809    private IntentFilterVerifier mIntentFilterVerifier;
810
811    // Set of pending broadcasts for aggregating enable/disable of components.
812    static class PendingPackageBroadcasts {
813        // for each user id, a map of <package name -> components within that package>
814        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
815
816        public PendingPackageBroadcasts() {
817            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
818        }
819
820        public ArrayList<String> get(int userId, String packageName) {
821            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
822            return packages.get(packageName);
823        }
824
825        public void put(int userId, String packageName, ArrayList<String> components) {
826            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
827            packages.put(packageName, components);
828        }
829
830        public void remove(int userId, String packageName) {
831            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
832            if (packages != null) {
833                packages.remove(packageName);
834            }
835        }
836
837        public void remove(int userId) {
838            mUidMap.remove(userId);
839        }
840
841        public int userIdCount() {
842            return mUidMap.size();
843        }
844
845        public int userIdAt(int n) {
846            return mUidMap.keyAt(n);
847        }
848
849        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
850            return mUidMap.get(userId);
851        }
852
853        public int size() {
854            // total number of pending broadcast entries across all userIds
855            int num = 0;
856            for (int i = 0; i< mUidMap.size(); i++) {
857                num += mUidMap.valueAt(i).size();
858            }
859            return num;
860        }
861
862        public void clear() {
863            mUidMap.clear();
864        }
865
866        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
867            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
868            if (map == null) {
869                map = new ArrayMap<String, ArrayList<String>>();
870                mUidMap.put(userId, map);
871            }
872            return map;
873        }
874    }
875    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
876
877    // Service Connection to remote media container service to copy
878    // package uri's from external media onto secure containers
879    // or internal storage.
880    private IMediaContainerService mContainerService = null;
881
882    static final int SEND_PENDING_BROADCAST = 1;
883    static final int MCS_BOUND = 3;
884    static final int END_COPY = 4;
885    static final int INIT_COPY = 5;
886    static final int MCS_UNBIND = 6;
887    static final int START_CLEANING_PACKAGE = 7;
888    static final int FIND_INSTALL_LOC = 8;
889    static final int POST_INSTALL = 9;
890    static final int MCS_RECONNECT = 10;
891    static final int MCS_GIVE_UP = 11;
892    static final int UPDATED_MEDIA_STATUS = 12;
893    static final int WRITE_SETTINGS = 13;
894    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
895    static final int PACKAGE_VERIFIED = 15;
896    static final int CHECK_PENDING_VERIFICATION = 16;
897    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
898    static final int INTENT_FILTER_VERIFIED = 18;
899
900    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
901
902    // Delay time in millisecs
903    static final int BROADCAST_DELAY = 10 * 1000;
904
905    static UserManagerService sUserManager;
906
907    // Stores a list of users whose package restrictions file needs to be updated
908    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
909
910    final private DefaultContainerConnection mDefContainerConn =
911            new DefaultContainerConnection();
912    class DefaultContainerConnection implements ServiceConnection {
913        public void onServiceConnected(ComponentName name, IBinder service) {
914            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
915            IMediaContainerService imcs =
916                IMediaContainerService.Stub.asInterface(service);
917            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
918        }
919
920        public void onServiceDisconnected(ComponentName name) {
921            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
922        }
923    }
924
925    // Recordkeeping of restore-after-install operations that are currently in flight
926    // between the Package Manager and the Backup Manager
927    class PostInstallData {
928        public InstallArgs args;
929        public PackageInstalledInfo res;
930
931        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
932            args = _a;
933            res = _r;
934        }
935    }
936
937    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
938    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
939
940    // XML tags for backup/restore of various bits of state
941    private static final String TAG_PREFERRED_BACKUP = "pa";
942    private static final String TAG_DEFAULT_APPS = "da";
943    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
944
945    final String mRequiredVerifierPackage;
946    final String mRequiredInstallerPackage;
947
948    private final PackageUsage mPackageUsage = new PackageUsage();
949
950    private class PackageUsage {
951        private static final int WRITE_INTERVAL
952            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
953
954        private final Object mFileLock = new Object();
955        private final AtomicLong mLastWritten = new AtomicLong(0);
956        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
957
958        private boolean mIsHistoricalPackageUsageAvailable = true;
959
960        boolean isHistoricalPackageUsageAvailable() {
961            return mIsHistoricalPackageUsageAvailable;
962        }
963
964        void write(boolean force) {
965            if (force) {
966                writeInternal();
967                return;
968            }
969            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
970                && !DEBUG_DEXOPT) {
971                return;
972            }
973            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
974                new Thread("PackageUsage_DiskWriter") {
975                    @Override
976                    public void run() {
977                        try {
978                            writeInternal();
979                        } finally {
980                            mBackgroundWriteRunning.set(false);
981                        }
982                    }
983                }.start();
984            }
985        }
986
987        private void writeInternal() {
988            synchronized (mPackages) {
989                synchronized (mFileLock) {
990                    AtomicFile file = getFile();
991                    FileOutputStream f = null;
992                    try {
993                        f = file.startWrite();
994                        BufferedOutputStream out = new BufferedOutputStream(f);
995                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
996                        StringBuilder sb = new StringBuilder();
997                        for (PackageParser.Package pkg : mPackages.values()) {
998                            if (pkg.mLastPackageUsageTimeInMills == 0) {
999                                continue;
1000                            }
1001                            sb.setLength(0);
1002                            sb.append(pkg.packageName);
1003                            sb.append(' ');
1004                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1005                            sb.append('\n');
1006                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1007                        }
1008                        out.flush();
1009                        file.finishWrite(f);
1010                    } catch (IOException e) {
1011                        if (f != null) {
1012                            file.failWrite(f);
1013                        }
1014                        Log.e(TAG, "Failed to write package usage times", e);
1015                    }
1016                }
1017            }
1018            mLastWritten.set(SystemClock.elapsedRealtime());
1019        }
1020
1021        void readLP() {
1022            synchronized (mFileLock) {
1023                AtomicFile file = getFile();
1024                BufferedInputStream in = null;
1025                try {
1026                    in = new BufferedInputStream(file.openRead());
1027                    StringBuffer sb = new StringBuffer();
1028                    while (true) {
1029                        String packageName = readToken(in, sb, ' ');
1030                        if (packageName == null) {
1031                            break;
1032                        }
1033                        String timeInMillisString = readToken(in, sb, '\n');
1034                        if (timeInMillisString == null) {
1035                            throw new IOException("Failed to find last usage time for package "
1036                                                  + packageName);
1037                        }
1038                        PackageParser.Package pkg = mPackages.get(packageName);
1039                        if (pkg == null) {
1040                            continue;
1041                        }
1042                        long timeInMillis;
1043                        try {
1044                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1045                        } catch (NumberFormatException e) {
1046                            throw new IOException("Failed to parse " + timeInMillisString
1047                                                  + " as a long.", e);
1048                        }
1049                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1050                    }
1051                } catch (FileNotFoundException expected) {
1052                    mIsHistoricalPackageUsageAvailable = false;
1053                } catch (IOException e) {
1054                    Log.w(TAG, "Failed to read package usage times", e);
1055                } finally {
1056                    IoUtils.closeQuietly(in);
1057                }
1058            }
1059            mLastWritten.set(SystemClock.elapsedRealtime());
1060        }
1061
1062        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1063                throws IOException {
1064            sb.setLength(0);
1065            while (true) {
1066                int ch = in.read();
1067                if (ch == -1) {
1068                    if (sb.length() == 0) {
1069                        return null;
1070                    }
1071                    throw new IOException("Unexpected EOF");
1072                }
1073                if (ch == endOfToken) {
1074                    return sb.toString();
1075                }
1076                sb.append((char)ch);
1077            }
1078        }
1079
1080        private AtomicFile getFile() {
1081            File dataDir = Environment.getDataDirectory();
1082            File systemDir = new File(dataDir, "system");
1083            File fname = new File(systemDir, "package-usage.list");
1084            return new AtomicFile(fname);
1085        }
1086    }
1087
1088    class PackageHandler extends Handler {
1089        private boolean mBound = false;
1090        final ArrayList<HandlerParams> mPendingInstalls =
1091            new ArrayList<HandlerParams>();
1092
1093        private boolean connectToService() {
1094            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1095                    " DefaultContainerService");
1096            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1099                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1100                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1101                mBound = true;
1102                return true;
1103            }
1104            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1105            return false;
1106        }
1107
1108        private void disconnectService() {
1109            mContainerService = null;
1110            mBound = false;
1111            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112            mContext.unbindService(mDefContainerConn);
1113            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1114        }
1115
1116        PackageHandler(Looper looper) {
1117            super(looper);
1118        }
1119
1120        public void handleMessage(Message msg) {
1121            try {
1122                doHandleMessage(msg);
1123            } finally {
1124                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125            }
1126        }
1127
1128        void doHandleMessage(Message msg) {
1129            switch (msg.what) {
1130                case INIT_COPY: {
1131                    HandlerParams params = (HandlerParams) msg.obj;
1132                    int idx = mPendingInstalls.size();
1133                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1134                    // If a bind was already initiated we dont really
1135                    // need to do anything. The pending install
1136                    // will be processed later on.
1137                    if (!mBound) {
1138                        // If this is the only one pending we might
1139                        // have to bind to the service again.
1140                        if (!connectToService()) {
1141                            Slog.e(TAG, "Failed to bind to media container service");
1142                            params.serviceError();
1143                            return;
1144                        } else {
1145                            // Once we bind to the service, the first
1146                            // pending request will be processed.
1147                            mPendingInstalls.add(idx, params);
1148                        }
1149                    } else {
1150                        mPendingInstalls.add(idx, params);
1151                        // Already bound to the service. Just make
1152                        // sure we trigger off processing the first request.
1153                        if (idx == 0) {
1154                            mHandler.sendEmptyMessage(MCS_BOUND);
1155                        }
1156                    }
1157                    break;
1158                }
1159                case MCS_BOUND: {
1160                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1161                    if (msg.obj != null) {
1162                        mContainerService = (IMediaContainerService) msg.obj;
1163                    }
1164                    if (mContainerService == null) {
1165                        if (!mBound) {
1166                            // Something seriously wrong since we are not bound and we are not
1167                            // waiting for connection. Bail out.
1168                            Slog.e(TAG, "Cannot bind to media container service");
1169                            for (HandlerParams params : mPendingInstalls) {
1170                                // Indicate service bind error
1171                                params.serviceError();
1172                            }
1173                            mPendingInstalls.clear();
1174                        } else {
1175                            Slog.w(TAG, "Waiting to connect to media container service");
1176                        }
1177                    } else if (mPendingInstalls.size() > 0) {
1178                        HandlerParams params = mPendingInstalls.get(0);
1179                        if (params != null) {
1180                            if (params.startCopy()) {
1181                                // We are done...  look for more work or to
1182                                // go idle.
1183                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1184                                        "Checking for more work or unbind...");
1185                                // Delete pending install
1186                                if (mPendingInstalls.size() > 0) {
1187                                    mPendingInstalls.remove(0);
1188                                }
1189                                if (mPendingInstalls.size() == 0) {
1190                                    if (mBound) {
1191                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1192                                                "Posting delayed MCS_UNBIND");
1193                                        removeMessages(MCS_UNBIND);
1194                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1195                                        // Unbind after a little delay, to avoid
1196                                        // continual thrashing.
1197                                        sendMessageDelayed(ubmsg, 10000);
1198                                    }
1199                                } else {
1200                                    // There are more pending requests in queue.
1201                                    // Just post MCS_BOUND message to trigger processing
1202                                    // of next pending install.
1203                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                            "Posting MCS_BOUND for next work");
1205                                    mHandler.sendEmptyMessage(MCS_BOUND);
1206                                }
1207                            }
1208                        }
1209                    } else {
1210                        // Should never happen ideally.
1211                        Slog.w(TAG, "Empty queue");
1212                    }
1213                    break;
1214                }
1215                case MCS_RECONNECT: {
1216                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1217                    if (mPendingInstalls.size() > 0) {
1218                        if (mBound) {
1219                            disconnectService();
1220                        }
1221                        if (!connectToService()) {
1222                            Slog.e(TAG, "Failed to bind to media container service");
1223                            for (HandlerParams params : mPendingInstalls) {
1224                                // Indicate service bind error
1225                                params.serviceError();
1226                            }
1227                            mPendingInstalls.clear();
1228                        }
1229                    }
1230                    break;
1231                }
1232                case MCS_UNBIND: {
1233                    // If there is no actual work left, then time to unbind.
1234                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1235
1236                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1237                        if (mBound) {
1238                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1239
1240                            disconnectService();
1241                        }
1242                    } else if (mPendingInstalls.size() > 0) {
1243                        // There are more pending requests in queue.
1244                        // Just post MCS_BOUND message to trigger processing
1245                        // of next pending install.
1246                        mHandler.sendEmptyMessage(MCS_BOUND);
1247                    }
1248
1249                    break;
1250                }
1251                case MCS_GIVE_UP: {
1252                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1253                    mPendingInstalls.remove(0);
1254                    break;
1255                }
1256                case SEND_PENDING_BROADCAST: {
1257                    String packages[];
1258                    ArrayList<String> components[];
1259                    int size = 0;
1260                    int uids[];
1261                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1262                    synchronized (mPackages) {
1263                        if (mPendingBroadcasts == null) {
1264                            return;
1265                        }
1266                        size = mPendingBroadcasts.size();
1267                        if (size <= 0) {
1268                            // Nothing to be done. Just return
1269                            return;
1270                        }
1271                        packages = new String[size];
1272                        components = new ArrayList[size];
1273                        uids = new int[size];
1274                        int i = 0;  // filling out the above arrays
1275
1276                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1277                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1278                            Iterator<Map.Entry<String, ArrayList<String>>> it
1279                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1280                                            .entrySet().iterator();
1281                            while (it.hasNext() && i < size) {
1282                                Map.Entry<String, ArrayList<String>> ent = it.next();
1283                                packages[i] = ent.getKey();
1284                                components[i] = ent.getValue();
1285                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1286                                uids[i] = (ps != null)
1287                                        ? UserHandle.getUid(packageUserId, ps.appId)
1288                                        : -1;
1289                                i++;
1290                            }
1291                        }
1292                        size = i;
1293                        mPendingBroadcasts.clear();
1294                    }
1295                    // Send broadcasts
1296                    for (int i = 0; i < size; i++) {
1297                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1298                    }
1299                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1300                    break;
1301                }
1302                case START_CLEANING_PACKAGE: {
1303                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1304                    final String packageName = (String)msg.obj;
1305                    final int userId = msg.arg1;
1306                    final boolean andCode = msg.arg2 != 0;
1307                    synchronized (mPackages) {
1308                        if (userId == UserHandle.USER_ALL) {
1309                            int[] users = sUserManager.getUserIds();
1310                            for (int user : users) {
1311                                mSettings.addPackageToCleanLPw(
1312                                        new PackageCleanItem(user, packageName, andCode));
1313                            }
1314                        } else {
1315                            mSettings.addPackageToCleanLPw(
1316                                    new PackageCleanItem(userId, packageName, andCode));
1317                        }
1318                    }
1319                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1320                    startCleaningPackages();
1321                } break;
1322                case POST_INSTALL: {
1323                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1324                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1325                    mRunningInstalls.delete(msg.arg1);
1326                    boolean deleteOld = false;
1327
1328                    if (data != null) {
1329                        InstallArgs args = data.args;
1330                        PackageInstalledInfo res = data.res;
1331
1332                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1333                            final String packageName = res.pkg.applicationInfo.packageName;
1334                            res.removedInfo.sendBroadcast(false, true, false);
1335                            Bundle extras = new Bundle(1);
1336                            extras.putInt(Intent.EXTRA_UID, res.uid);
1337
1338                            // Now that we successfully installed the package, grant runtime
1339                            // permissions if requested before broadcasting the install.
1340                            if ((args.installFlags
1341                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1342                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1343                                        args.installGrantPermissions);
1344                            }
1345
1346                            // Determine the set of users who are adding this
1347                            // package for the first time vs. those who are seeing
1348                            // an update.
1349                            int[] firstUsers;
1350                            int[] updateUsers = new int[0];
1351                            if (res.origUsers == null || res.origUsers.length == 0) {
1352                                firstUsers = res.newUsers;
1353                            } else {
1354                                firstUsers = new int[0];
1355                                for (int i=0; i<res.newUsers.length; i++) {
1356                                    int user = res.newUsers[i];
1357                                    boolean isNew = true;
1358                                    for (int j=0; j<res.origUsers.length; j++) {
1359                                        if (res.origUsers[j] == user) {
1360                                            isNew = false;
1361                                            break;
1362                                        }
1363                                    }
1364                                    if (isNew) {
1365                                        int[] newFirst = new int[firstUsers.length+1];
1366                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1367                                                firstUsers.length);
1368                                        newFirst[firstUsers.length] = user;
1369                                        firstUsers = newFirst;
1370                                    } else {
1371                                        int[] newUpdate = new int[updateUsers.length+1];
1372                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1373                                                updateUsers.length);
1374                                        newUpdate[updateUsers.length] = user;
1375                                        updateUsers = newUpdate;
1376                                    }
1377                                }
1378                            }
1379                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1380                                    packageName, extras, null, null, firstUsers);
1381                            final boolean update = res.removedInfo.removedPackage != null;
1382                            if (update) {
1383                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1384                            }
1385                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1386                                    packageName, extras, null, null, updateUsers);
1387                            if (update) {
1388                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1389                                        packageName, extras, null, null, updateUsers);
1390                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1391                                        null, null, packageName, null, updateUsers);
1392
1393                                // treat asec-hosted packages like removable media on upgrade
1394                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1395                                    if (DEBUG_INSTALL) {
1396                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1397                                                + " is ASEC-hosted -> AVAILABLE");
1398                                    }
1399                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1400                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1401                                    pkgList.add(packageName);
1402                                    sendResourcesChangedBroadcast(true, true,
1403                                            pkgList,uidArray, null);
1404                                }
1405                            }
1406                            if (res.removedInfo.args != null) {
1407                                // Remove the replaced package's older resources safely now
1408                                deleteOld = true;
1409                            }
1410
1411                            // If this app is a browser and it's newly-installed for some
1412                            // users, clear any default-browser state in those users
1413                            if (firstUsers.length > 0) {
1414                                // the app's nature doesn't depend on the user, so we can just
1415                                // check its browser nature in any user and generalize.
1416                                if (packageIsBrowser(packageName, firstUsers[0])) {
1417                                    synchronized (mPackages) {
1418                                        for (int userId : firstUsers) {
1419                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1420                                        }
1421                                    }
1422                                }
1423                            }
1424                            // Log current value of "unknown sources" setting
1425                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1426                                getUnknownSourcesSettings());
1427                        }
1428                        // Force a gc to clear up things
1429                        Runtime.getRuntime().gc();
1430                        // We delete after a gc for applications  on sdcard.
1431                        if (deleteOld) {
1432                            synchronized (mInstallLock) {
1433                                res.removedInfo.args.doPostDeleteLI(true);
1434                            }
1435                        }
1436                        if (args.observer != null) {
1437                            try {
1438                                Bundle extras = extrasForInstallResult(res);
1439                                args.observer.onPackageInstalled(res.name, res.returnCode,
1440                                        res.returnMsg, extras);
1441                            } catch (RemoteException e) {
1442                                Slog.i(TAG, "Observer no longer exists.");
1443                            }
1444                        }
1445                    } else {
1446                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1447                    }
1448                } break;
1449                case UPDATED_MEDIA_STATUS: {
1450                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1451                    boolean reportStatus = msg.arg1 == 1;
1452                    boolean doGc = msg.arg2 == 1;
1453                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1454                    if (doGc) {
1455                        // Force a gc to clear up stale containers.
1456                        Runtime.getRuntime().gc();
1457                    }
1458                    if (msg.obj != null) {
1459                        @SuppressWarnings("unchecked")
1460                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1461                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1462                        // Unload containers
1463                        unloadAllContainers(args);
1464                    }
1465                    if (reportStatus) {
1466                        try {
1467                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1468                            PackageHelper.getMountService().finishMediaUpdate();
1469                        } catch (RemoteException e) {
1470                            Log.e(TAG, "MountService not running?");
1471                        }
1472                    }
1473                } break;
1474                case WRITE_SETTINGS: {
1475                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1476                    synchronized (mPackages) {
1477                        removeMessages(WRITE_SETTINGS);
1478                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1479                        mSettings.writeLPr();
1480                        mDirtyUsers.clear();
1481                    }
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                } break;
1484                case WRITE_PACKAGE_RESTRICTIONS: {
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1486                    synchronized (mPackages) {
1487                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1488                        for (int userId : mDirtyUsers) {
1489                            mSettings.writePackageRestrictionsLPr(userId);
1490                        }
1491                        mDirtyUsers.clear();
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                } break;
1495                case CHECK_PENDING_VERIFICATION: {
1496                    final int verificationId = msg.arg1;
1497                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1498
1499                    if ((state != null) && !state.timeoutExtended()) {
1500                        final InstallArgs args = state.getInstallArgs();
1501                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1502
1503                        Slog.i(TAG, "Verification timed out for " + originUri);
1504                        mPendingVerification.remove(verificationId);
1505
1506                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1507
1508                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1509                            Slog.i(TAG, "Continuing with installation of " + originUri);
1510                            state.setVerifierResponse(Binder.getCallingUid(),
1511                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_ALLOW,
1514                                    state.getInstallArgs().getUser());
1515                            try {
1516                                ret = args.copyApk(mContainerService, true);
1517                            } catch (RemoteException e) {
1518                                Slog.e(TAG, "Could not contact the ContainerService");
1519                            }
1520                        } else {
1521                            broadcastPackageVerified(verificationId, originUri,
1522                                    PackageManager.VERIFICATION_REJECT,
1523                                    state.getInstallArgs().getUser());
1524                        }
1525
1526                        processPendingInstall(args, ret);
1527                        mHandler.sendEmptyMessage(MCS_UNBIND);
1528                    }
1529                    break;
1530                }
1531                case PACKAGE_VERIFIED: {
1532                    final int verificationId = msg.arg1;
1533
1534                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1535                    if (state == null) {
1536                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1537                        break;
1538                    }
1539
1540                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1541
1542                    state.setVerifierResponse(response.callerUid, response.code);
1543
1544                    if (state.isVerificationComplete()) {
1545                        mPendingVerification.remove(verificationId);
1546
1547                        final InstallArgs args = state.getInstallArgs();
1548                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1549
1550                        int ret;
1551                        if (state.isInstallAllowed()) {
1552                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1553                            broadcastPackageVerified(verificationId, originUri,
1554                                    response.code, state.getInstallArgs().getUser());
1555                            try {
1556                                ret = args.copyApk(mContainerService, true);
1557                            } catch (RemoteException e) {
1558                                Slog.e(TAG, "Could not contact the ContainerService");
1559                            }
1560                        } else {
1561                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1562                        }
1563
1564                        processPendingInstall(args, ret);
1565
1566                        mHandler.sendEmptyMessage(MCS_UNBIND);
1567                    }
1568
1569                    break;
1570                }
1571                case START_INTENT_FILTER_VERIFICATIONS: {
1572                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1573                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1574                            params.replacing, params.pkg);
1575                    break;
1576                }
1577                case INTENT_FILTER_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1581                            verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid IntentFilter verification token "
1584                                + verificationId + " received");
1585                        break;
1586                    }
1587
1588                    final int userId = state.getUserId();
1589
1590                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1591                            "Processing IntentFilter verification with token:"
1592                            + verificationId + " and userId:" + userId);
1593
1594                    final IntentFilterVerificationResponse response =
1595                            (IntentFilterVerificationResponse) msg.obj;
1596
1597                    state.setVerifierResponse(response.callerUid, response.code);
1598
1599                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                            "IntentFilter verification with token:" + verificationId
1601                            + " and userId:" + userId
1602                            + " is settings verifier response with response code:"
1603                            + response.code);
1604
1605                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1606                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1607                                + response.getFailedDomainsString());
1608                    }
1609
1610                    if (state.isVerificationComplete()) {
1611                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1612                    } else {
1613                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614                                "IntentFilter verification with token:" + verificationId
1615                                + " was not said to be complete");
1616                    }
1617
1618                    break;
1619                }
1620            }
1621        }
1622    }
1623
1624    private StorageEventListener mStorageListener = new StorageEventListener() {
1625        @Override
1626        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1627            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1628                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1629                    final String volumeUuid = vol.getFsUuid();
1630
1631                    // Clean up any users or apps that were removed or recreated
1632                    // while this volume was missing
1633                    reconcileUsers(volumeUuid);
1634                    reconcileApps(volumeUuid);
1635
1636                    // Clean up any install sessions that expired or were
1637                    // cancelled while this volume was missing
1638                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1639
1640                    loadPrivatePackages(vol);
1641
1642                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1643                    unloadPrivatePackages(vol);
1644                }
1645            }
1646
1647            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1648                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1649                    updateExternalMediaStatus(true, false);
1650                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1651                    updateExternalMediaStatus(false, false);
1652                }
1653            }
1654        }
1655
1656        @Override
1657        public void onVolumeForgotten(String fsUuid) {
1658            if (TextUtils.isEmpty(fsUuid)) {
1659                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1660                return;
1661            }
1662
1663            // Remove any apps installed on the forgotten volume
1664            synchronized (mPackages) {
1665                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1666                for (PackageSetting ps : packages) {
1667                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1668                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1669                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1670                }
1671
1672                mSettings.onVolumeForgotten(fsUuid);
1673                mSettings.writeLPr();
1674            }
1675        }
1676    };
1677
1678    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1679            String[] grantedPermissions) {
1680        if (userId >= UserHandle.USER_OWNER) {
1681            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1682        } else if (userId == UserHandle.USER_ALL) {
1683            final int[] userIds;
1684            synchronized (mPackages) {
1685                userIds = UserManagerService.getInstance().getUserIds();
1686            }
1687            for (int someUserId : userIds) {
1688                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1689            }
1690        }
1691
1692        // We could have touched GID membership, so flush out packages.list
1693        synchronized (mPackages) {
1694            mSettings.writePackageListLPr();
1695        }
1696    }
1697
1698    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1699            String[] grantedPermissions) {
1700        SettingBase sb = (SettingBase) pkg.mExtras;
1701        if (sb == null) {
1702            return;
1703        }
1704
1705        PermissionsState permissionsState = sb.getPermissionsState();
1706
1707        for (String permission : pkg.requestedPermissions) {
1708            BasePermission bp = mSettings.mPermissions.get(permission);
1709            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1710                    || ArrayUtils.contains(grantedPermissions, permission))) {
1711                permissionsState.grantRuntimePermission(bp, userId);
1712            }
1713        }
1714    }
1715
1716    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1717        Bundle extras = null;
1718        switch (res.returnCode) {
1719            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1720                extras = new Bundle();
1721                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1722                        res.origPermission);
1723                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1724                        res.origPackage);
1725                break;
1726            }
1727            case PackageManager.INSTALL_SUCCEEDED: {
1728                extras = new Bundle();
1729                extras.putBoolean(Intent.EXTRA_REPLACING,
1730                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1731                break;
1732            }
1733        }
1734        return extras;
1735    }
1736
1737    void scheduleWriteSettingsLocked() {
1738        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1739            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1740        }
1741    }
1742
1743    void scheduleWritePackageRestrictionsLocked(int userId) {
1744        if (!sUserManager.exists(userId)) return;
1745        mDirtyUsers.add(userId);
1746        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1747            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1748        }
1749    }
1750
1751    public static PackageManagerService main(Context context, Installer installer,
1752            boolean factoryTest, boolean onlyCore) {
1753        PackageManagerService m = new PackageManagerService(context, installer,
1754                factoryTest, onlyCore);
1755        ServiceManager.addService("package", m);
1756        return m;
1757    }
1758
1759    static String[] splitString(String str, char sep) {
1760        int count = 1;
1761        int i = 0;
1762        while ((i=str.indexOf(sep, i)) >= 0) {
1763            count++;
1764            i++;
1765        }
1766
1767        String[] res = new String[count];
1768        i=0;
1769        count = 0;
1770        int lastI=0;
1771        while ((i=str.indexOf(sep, i)) >= 0) {
1772            res[count] = str.substring(lastI, i);
1773            count++;
1774            i++;
1775            lastI = i;
1776        }
1777        res[count] = str.substring(lastI, str.length());
1778        return res;
1779    }
1780
1781    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1782        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1783                Context.DISPLAY_SERVICE);
1784        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1785    }
1786
1787    public PackageManagerService(Context context, Installer installer,
1788            boolean factoryTest, boolean onlyCore) {
1789        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1790                SystemClock.uptimeMillis());
1791
1792        if (mSdkVersion <= 0) {
1793            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1794        }
1795
1796        mContext = context;
1797        mFactoryTest = factoryTest;
1798        mOnlyCore = onlyCore;
1799        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1800        mMetrics = new DisplayMetrics();
1801        mSettings = new Settings(mPackages);
1802        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1803                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1804        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1805                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1806        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1807                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1808        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1809                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1810        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1811                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1812        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1813                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1814
1815        // TODO: add a property to control this?
1816        long dexOptLRUThresholdInMinutes;
1817        if (mLazyDexOpt) {
1818            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1819        } else {
1820            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1821        }
1822        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1823
1824        String separateProcesses = SystemProperties.get("debug.separate_processes");
1825        if (separateProcesses != null && separateProcesses.length() > 0) {
1826            if ("*".equals(separateProcesses)) {
1827                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1828                mSeparateProcesses = null;
1829                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1830            } else {
1831                mDefParseFlags = 0;
1832                mSeparateProcesses = separateProcesses.split(",");
1833                Slog.w(TAG, "Running with debug.separate_processes: "
1834                        + separateProcesses);
1835            }
1836        } else {
1837            mDefParseFlags = 0;
1838            mSeparateProcesses = null;
1839        }
1840
1841        mInstaller = installer;
1842        mPackageDexOptimizer = new PackageDexOptimizer(this);
1843        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1844
1845        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1846                FgThread.get().getLooper());
1847
1848        getDefaultDisplayMetrics(context, mMetrics);
1849
1850        SystemConfig systemConfig = SystemConfig.getInstance();
1851        mGlobalGids = systemConfig.getGlobalGids();
1852        mSystemPermissions = systemConfig.getSystemPermissions();
1853        mAvailableFeatures = systemConfig.getAvailableFeatures();
1854
1855        synchronized (mInstallLock) {
1856        // writer
1857        synchronized (mPackages) {
1858            mHandlerThread = new ServiceThread(TAG,
1859                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1860            mHandlerThread.start();
1861            mHandler = new PackageHandler(mHandlerThread.getLooper());
1862            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1863
1864            File dataDir = Environment.getDataDirectory();
1865            mAppDataDir = new File(dataDir, "data");
1866            mAppInstallDir = new File(dataDir, "app");
1867            mAppLib32InstallDir = new File(dataDir, "app-lib");
1868            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1869            mUserAppDataDir = new File(dataDir, "user");
1870            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1871
1872            sUserManager = new UserManagerService(context, this,
1873                    mInstallLock, mPackages);
1874
1875            // Propagate permission configuration in to package manager.
1876            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1877                    = systemConfig.getPermissions();
1878            for (int i=0; i<permConfig.size(); i++) {
1879                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1880                BasePermission bp = mSettings.mPermissions.get(perm.name);
1881                if (bp == null) {
1882                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1883                    mSettings.mPermissions.put(perm.name, bp);
1884                }
1885                if (perm.gids != null) {
1886                    bp.setGids(perm.gids, perm.perUser);
1887                }
1888            }
1889
1890            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1891            for (int i=0; i<libConfig.size(); i++) {
1892                mSharedLibraries.put(libConfig.keyAt(i),
1893                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1894            }
1895
1896            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1897
1898            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1899                    mSdkVersion, mOnlyCore);
1900
1901            String customResolverActivity = Resources.getSystem().getString(
1902                    R.string.config_customResolverActivity);
1903            if (TextUtils.isEmpty(customResolverActivity)) {
1904                customResolverActivity = null;
1905            } else {
1906                mCustomResolverComponentName = ComponentName.unflattenFromString(
1907                        customResolverActivity);
1908            }
1909
1910            long startTime = SystemClock.uptimeMillis();
1911
1912            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1913                    startTime);
1914
1915            // Set flag to monitor and not change apk file paths when
1916            // scanning install directories.
1917            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1918
1919            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1920
1921            /**
1922             * Add everything in the in the boot class path to the
1923             * list of process files because dexopt will have been run
1924             * if necessary during zygote startup.
1925             */
1926            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1927            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1928
1929            if (bootClassPath != null) {
1930                String[] bootClassPathElements = splitString(bootClassPath, ':');
1931                for (String element : bootClassPathElements) {
1932                    alreadyDexOpted.add(element);
1933                }
1934            } else {
1935                Slog.w(TAG, "No BOOTCLASSPATH found!");
1936            }
1937
1938            if (systemServerClassPath != null) {
1939                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1940                for (String element : systemServerClassPathElements) {
1941                    alreadyDexOpted.add(element);
1942                }
1943            } else {
1944                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1945            }
1946
1947            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1948            final String[] dexCodeInstructionSets =
1949                    getDexCodeInstructionSets(
1950                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1951
1952            /**
1953             * Ensure all external libraries have had dexopt run on them.
1954             */
1955            if (mSharedLibraries.size() > 0) {
1956                // NOTE: For now, we're compiling these system "shared libraries"
1957                // (and framework jars) into all available architectures. It's possible
1958                // to compile them only when we come across an app that uses them (there's
1959                // already logic for that in scanPackageLI) but that adds some complexity.
1960                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1961                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1962                        final String lib = libEntry.path;
1963                        if (lib == null) {
1964                            continue;
1965                        }
1966
1967                        try {
1968                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1969                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1970                                alreadyDexOpted.add(lib);
1971                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1972                            }
1973                        } catch (FileNotFoundException e) {
1974                            Slog.w(TAG, "Library not found: " + lib);
1975                        } catch (IOException e) {
1976                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1977                                    + e.getMessage());
1978                        }
1979                    }
1980                }
1981            }
1982
1983            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1984
1985            // Gross hack for now: we know this file doesn't contain any
1986            // code, so don't dexopt it to avoid the resulting log spew.
1987            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1988
1989            // Gross hack for now: we know this file is only part of
1990            // the boot class path for art, so don't dexopt it to
1991            // avoid the resulting log spew.
1992            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1993
1994            /**
1995             * There are a number of commands implemented in Java, which
1996             * we currently need to do the dexopt on so that they can be
1997             * run from a non-root shell.
1998             */
1999            String[] frameworkFiles = frameworkDir.list();
2000            if (frameworkFiles != null) {
2001                // TODO: We could compile these only for the most preferred ABI. We should
2002                // first double check that the dex files for these commands are not referenced
2003                // by other system apps.
2004                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2005                    for (int i=0; i<frameworkFiles.length; i++) {
2006                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2007                        String path = libPath.getPath();
2008                        // Skip the file if we already did it.
2009                        if (alreadyDexOpted.contains(path)) {
2010                            continue;
2011                        }
2012                        // Skip the file if it is not a type we want to dexopt.
2013                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2014                            continue;
2015                        }
2016                        try {
2017                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2018                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2019                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2020                            }
2021                        } catch (FileNotFoundException e) {
2022                            Slog.w(TAG, "Jar not found: " + path);
2023                        } catch (IOException e) {
2024                            Slog.w(TAG, "Exception reading jar: " + path, e);
2025                        }
2026                    }
2027                }
2028            }
2029
2030            // Collect vendor overlay packages.
2031            // (Do this before scanning any apps.)
2032            // For security and version matching reason, only consider
2033            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2034            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2035            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2036                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2037
2038            // Find base frameworks (resource packages without code).
2039            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2040                    | PackageParser.PARSE_IS_SYSTEM_DIR
2041                    | PackageParser.PARSE_IS_PRIVILEGED,
2042                    scanFlags | SCAN_NO_DEX, 0);
2043
2044            // Collected privileged system packages.
2045            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2046            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2047                    | PackageParser.PARSE_IS_SYSTEM_DIR
2048                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2049
2050            // Collect ordinary system packages.
2051            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2052            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2053                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2054
2055            // Collect all vendor packages.
2056            File vendorAppDir = new File("/vendor/app");
2057            try {
2058                vendorAppDir = vendorAppDir.getCanonicalFile();
2059            } catch (IOException e) {
2060                // failed to look up canonical path, continue with original one
2061            }
2062            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2063                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2064
2065            // Collect all OEM packages.
2066            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2067            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2068                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2069
2070            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2071            mInstaller.moveFiles();
2072
2073            // Prune any system packages that no longer exist.
2074            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2075            if (!mOnlyCore) {
2076                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2077                while (psit.hasNext()) {
2078                    PackageSetting ps = psit.next();
2079
2080                    /*
2081                     * If this is not a system app, it can't be a
2082                     * disable system app.
2083                     */
2084                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2085                        continue;
2086                    }
2087
2088                    /*
2089                     * If the package is scanned, it's not erased.
2090                     */
2091                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2092                    if (scannedPkg != null) {
2093                        /*
2094                         * If the system app is both scanned and in the
2095                         * disabled packages list, then it must have been
2096                         * added via OTA. Remove it from the currently
2097                         * scanned package so the previously user-installed
2098                         * application can be scanned.
2099                         */
2100                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2101                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2102                                    + ps.name + "; removing system app.  Last known codePath="
2103                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2104                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2105                                    + scannedPkg.mVersionCode);
2106                            removePackageLI(ps, true);
2107                            mExpectingBetter.put(ps.name, ps.codePath);
2108                        }
2109
2110                        continue;
2111                    }
2112
2113                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2114                        psit.remove();
2115                        logCriticalInfo(Log.WARN, "System package " + ps.name
2116                                + " no longer exists; wiping its data");
2117                        removeDataDirsLI(null, ps.name);
2118                    } else {
2119                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2120                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2121                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2122                        }
2123                    }
2124                }
2125            }
2126
2127            //look for any incomplete package installations
2128            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2129            //clean up list
2130            for(int i = 0; i < deletePkgsList.size(); i++) {
2131                //clean up here
2132                cleanupInstallFailedPackage(deletePkgsList.get(i));
2133            }
2134            //delete tmp files
2135            deleteTempPackageFiles();
2136
2137            // Remove any shared userIDs that have no associated packages
2138            mSettings.pruneSharedUsersLPw();
2139
2140            if (!mOnlyCore) {
2141                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2142                        SystemClock.uptimeMillis());
2143                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2144
2145                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2146                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2147
2148                /**
2149                 * Remove disable package settings for any updated system
2150                 * apps that were removed via an OTA. If they're not a
2151                 * previously-updated app, remove them completely.
2152                 * Otherwise, just revoke their system-level permissions.
2153                 */
2154                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2155                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2156                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2157
2158                    String msg;
2159                    if (deletedPkg == null) {
2160                        msg = "Updated system package " + deletedAppName
2161                                + " no longer exists; wiping its data";
2162                        removeDataDirsLI(null, deletedAppName);
2163                    } else {
2164                        msg = "Updated system app + " + deletedAppName
2165                                + " no longer present; removing system privileges for "
2166                                + deletedAppName;
2167
2168                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2169
2170                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2171                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2172                    }
2173                    logCriticalInfo(Log.WARN, msg);
2174                }
2175
2176                /**
2177                 * Make sure all system apps that we expected to appear on
2178                 * the userdata partition actually showed up. If they never
2179                 * appeared, crawl back and revive the system version.
2180                 */
2181                for (int i = 0; i < mExpectingBetter.size(); i++) {
2182                    final String packageName = mExpectingBetter.keyAt(i);
2183                    if (!mPackages.containsKey(packageName)) {
2184                        final File scanFile = mExpectingBetter.valueAt(i);
2185
2186                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2187                                + " but never showed up; reverting to system");
2188
2189                        final int reparseFlags;
2190                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2191                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2192                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2193                                    | PackageParser.PARSE_IS_PRIVILEGED;
2194                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2195                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2196                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2197                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2198                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2199                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2200                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2201                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2202                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2203                        } else {
2204                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2205                            continue;
2206                        }
2207
2208                        mSettings.enableSystemPackageLPw(packageName);
2209
2210                        try {
2211                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2212                        } catch (PackageManagerException e) {
2213                            Slog.e(TAG, "Failed to parse original system package: "
2214                                    + e.getMessage());
2215                        }
2216                    }
2217                }
2218            }
2219            mExpectingBetter.clear();
2220
2221            // Now that we know all of the shared libraries, update all clients to have
2222            // the correct library paths.
2223            updateAllSharedLibrariesLPw();
2224
2225            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2226                // NOTE: We ignore potential failures here during a system scan (like
2227                // the rest of the commands above) because there's precious little we
2228                // can do about it. A settings error is reported, though.
2229                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2230                        false /* force dexopt */, false /* defer dexopt */);
2231            }
2232
2233            // Now that we know all the packages we are keeping,
2234            // read and update their last usage times.
2235            mPackageUsage.readLP();
2236
2237            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2238                    SystemClock.uptimeMillis());
2239            Slog.i(TAG, "Time to scan packages: "
2240                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2241                    + " seconds");
2242
2243            // If the platform SDK has changed since the last time we booted,
2244            // we need to re-grant app permission to catch any new ones that
2245            // appear.  This is really a hack, and means that apps can in some
2246            // cases get permissions that the user didn't initially explicitly
2247            // allow...  it would be nice to have some better way to handle
2248            // this situation.
2249            final VersionInfo ver = mSettings.getInternalVersion();
2250
2251            int updateFlags = UPDATE_PERMISSIONS_ALL;
2252            if (ver.sdkVersion != mSdkVersion) {
2253                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2254                        + mSdkVersion + "; regranting permissions for internal storage");
2255                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2256            }
2257            updatePermissionsLPw(null, null, updateFlags);
2258            ver.sdkVersion = mSdkVersion;
2259
2260            // If this is the first boot, and it is a normal boot, then
2261            // we need to initialize the default preferred apps.
2262            if (!mRestoredSettings && !onlyCore) {
2263                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2264                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2265                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2266            }
2267
2268            // If this is first boot after an OTA, and a normal boot, then
2269            // we need to clear code cache directories.
2270            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2271            if (mIsUpgrade && !onlyCore) {
2272                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2273                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2274                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2275                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2276                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2277                    }
2278                }
2279                ver.fingerprint = Build.FINGERPRINT;
2280            }
2281
2282            checkDefaultBrowser();
2283
2284            // All the changes are done during package scanning.
2285            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2286
2287            // can downgrade to reader
2288            mSettings.writeLPr();
2289
2290            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2291                    SystemClock.uptimeMillis());
2292
2293            mRequiredVerifierPackage = getRequiredVerifierLPr();
2294            mRequiredInstallerPackage = getRequiredInstallerLPr();
2295
2296            mInstallerService = new PackageInstallerService(context, this);
2297
2298            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2299            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2300                    mIntentFilterVerifierComponent);
2301
2302        } // synchronized (mPackages)
2303        } // synchronized (mInstallLock)
2304
2305        // Now after opening every single application zip, make sure they
2306        // are all flushed.  Not really needed, but keeps things nice and
2307        // tidy.
2308        Runtime.getRuntime().gc();
2309
2310        // Expose private service for system components to use.
2311        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2312    }
2313
2314    @Override
2315    public boolean isFirstBoot() {
2316        return !mRestoredSettings;
2317    }
2318
2319    @Override
2320    public boolean isOnlyCoreApps() {
2321        return mOnlyCore;
2322    }
2323
2324    @Override
2325    public boolean isUpgrade() {
2326        return mIsUpgrade;
2327    }
2328
2329    private String getRequiredVerifierLPr() {
2330        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2331        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2332                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2333
2334        String requiredVerifier = null;
2335
2336        final int N = receivers.size();
2337        for (int i = 0; i < N; i++) {
2338            final ResolveInfo info = receivers.get(i);
2339
2340            if (info.activityInfo == null) {
2341                continue;
2342            }
2343
2344            final String packageName = info.activityInfo.packageName;
2345
2346            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2347                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2348                continue;
2349            }
2350
2351            if (requiredVerifier != null) {
2352                throw new RuntimeException("There can be only one required verifier");
2353            }
2354
2355            requiredVerifier = packageName;
2356        }
2357
2358        return requiredVerifier;
2359    }
2360
2361    private String getRequiredInstallerLPr() {
2362        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2363        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2364        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2365
2366        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2367                PACKAGE_MIME_TYPE, 0, 0);
2368
2369        String requiredInstaller = null;
2370
2371        final int N = installers.size();
2372        for (int i = 0; i < N; i++) {
2373            final ResolveInfo info = installers.get(i);
2374            final String packageName = info.activityInfo.packageName;
2375
2376            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2377                continue;
2378            }
2379
2380            if (requiredInstaller != null) {
2381                throw new RuntimeException("There must be one required installer");
2382            }
2383
2384            requiredInstaller = packageName;
2385        }
2386
2387        if (requiredInstaller == null) {
2388            throw new RuntimeException("There must be one required installer");
2389        }
2390
2391        return requiredInstaller;
2392    }
2393
2394    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2395        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2396        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2397                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2398
2399        ComponentName verifierComponentName = null;
2400
2401        int priority = -1000;
2402        final int N = receivers.size();
2403        for (int i = 0; i < N; i++) {
2404            final ResolveInfo info = receivers.get(i);
2405
2406            if (info.activityInfo == null) {
2407                continue;
2408            }
2409
2410            final String packageName = info.activityInfo.packageName;
2411
2412            final PackageSetting ps = mSettings.mPackages.get(packageName);
2413            if (ps == null) {
2414                continue;
2415            }
2416
2417            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2418                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2419                continue;
2420            }
2421
2422            // Select the IntentFilterVerifier with the highest priority
2423            if (priority < info.priority) {
2424                priority = info.priority;
2425                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2426                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2427                        + verifierComponentName + " with priority: " + info.priority);
2428            }
2429        }
2430
2431        return verifierComponentName;
2432    }
2433
2434    private void primeDomainVerificationsLPw(int userId) {
2435        if (DEBUG_DOMAIN_VERIFICATION) {
2436            Slog.d(TAG, "Priming domain verifications in user " + userId);
2437        }
2438
2439        SystemConfig systemConfig = SystemConfig.getInstance();
2440        ArraySet<String> packages = systemConfig.getLinkedApps();
2441        ArraySet<String> domains = new ArraySet<String>();
2442
2443        for (String packageName : packages) {
2444            PackageParser.Package pkg = mPackages.get(packageName);
2445            if (pkg != null) {
2446                if (!pkg.isSystemApp()) {
2447                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2448                    continue;
2449                }
2450
2451                domains.clear();
2452                for (PackageParser.Activity a : pkg.activities) {
2453                    for (ActivityIntentInfo filter : a.intents) {
2454                        if (hasValidDomains(filter)) {
2455                            domains.addAll(filter.getHostsList());
2456                        }
2457                    }
2458                }
2459
2460                if (domains.size() > 0) {
2461                    if (DEBUG_DOMAIN_VERIFICATION) {
2462                        Slog.v(TAG, "      + " + packageName);
2463                    }
2464                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2465                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2466                    // and then 'always' in the per-user state actually used for intent resolution.
2467                    final IntentFilterVerificationInfo ivi;
2468                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2469                            new ArrayList<String>(domains));
2470                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2471                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2472                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2473                } else {
2474                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2475                            + "' does not handle web links");
2476                }
2477            } else {
2478                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2479            }
2480        }
2481
2482        scheduleWritePackageRestrictionsLocked(userId);
2483        scheduleWriteSettingsLocked();
2484    }
2485
2486    private void applyFactoryDefaultBrowserLPw(int userId) {
2487        // The default browser app's package name is stored in a string resource,
2488        // with a product-specific overlay used for vendor customization.
2489        String browserPkg = mContext.getResources().getString(
2490                com.android.internal.R.string.default_browser);
2491        if (!TextUtils.isEmpty(browserPkg)) {
2492            // non-empty string => required to be a known package
2493            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2494            if (ps == null) {
2495                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2496                browserPkg = null;
2497            } else {
2498                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2499            }
2500        }
2501
2502        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2503        // default.  If there's more than one, just leave everything alone.
2504        if (browserPkg == null) {
2505            calculateDefaultBrowserLPw(userId);
2506        }
2507    }
2508
2509    private void calculateDefaultBrowserLPw(int userId) {
2510        List<String> allBrowsers = resolveAllBrowserApps(userId);
2511        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2512        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2513    }
2514
2515    private List<String> resolveAllBrowserApps(int userId) {
2516        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2517        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2518                PackageManager.MATCH_ALL, userId);
2519
2520        final int count = list.size();
2521        List<String> result = new ArrayList<String>(count);
2522        for (int i=0; i<count; i++) {
2523            ResolveInfo info = list.get(i);
2524            if (info.activityInfo == null
2525                    || !info.handleAllWebDataURI
2526                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2527                    || result.contains(info.activityInfo.packageName)) {
2528                continue;
2529            }
2530            result.add(info.activityInfo.packageName);
2531        }
2532
2533        return result;
2534    }
2535
2536    private boolean packageIsBrowser(String packageName, int userId) {
2537        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2538                PackageManager.MATCH_ALL, userId);
2539        final int N = list.size();
2540        for (int i = 0; i < N; i++) {
2541            ResolveInfo info = list.get(i);
2542            if (packageName.equals(info.activityInfo.packageName)) {
2543                return true;
2544            }
2545        }
2546        return false;
2547    }
2548
2549    private void checkDefaultBrowser() {
2550        final int myUserId = UserHandle.myUserId();
2551        final String packageName = getDefaultBrowserPackageName(myUserId);
2552        if (packageName != null) {
2553            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2554            if (info == null) {
2555                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2556                synchronized (mPackages) {
2557                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2558                }
2559            }
2560        }
2561    }
2562
2563    @Override
2564    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2565            throws RemoteException {
2566        try {
2567            return super.onTransact(code, data, reply, flags);
2568        } catch (RuntimeException e) {
2569            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2570                Slog.wtf(TAG, "Package Manager Crash", e);
2571            }
2572            throw e;
2573        }
2574    }
2575
2576    void cleanupInstallFailedPackage(PackageSetting ps) {
2577        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2578
2579        removeDataDirsLI(ps.volumeUuid, ps.name);
2580        if (ps.codePath != null) {
2581            if (ps.codePath.isDirectory()) {
2582                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2583            } else {
2584                ps.codePath.delete();
2585            }
2586        }
2587        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2588            if (ps.resourcePath.isDirectory()) {
2589                FileUtils.deleteContents(ps.resourcePath);
2590            }
2591            ps.resourcePath.delete();
2592        }
2593        mSettings.removePackageLPw(ps.name);
2594    }
2595
2596    static int[] appendInts(int[] cur, int[] add) {
2597        if (add == null) return cur;
2598        if (cur == null) return add;
2599        final int N = add.length;
2600        for (int i=0; i<N; i++) {
2601            cur = appendInt(cur, add[i]);
2602        }
2603        return cur;
2604    }
2605
2606    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2607        if (!sUserManager.exists(userId)) return null;
2608        final PackageSetting ps = (PackageSetting) p.mExtras;
2609        if (ps == null) {
2610            return null;
2611        }
2612
2613        final PermissionsState permissionsState = ps.getPermissionsState();
2614
2615        final int[] gids = permissionsState.computeGids(userId);
2616        final Set<String> permissions = permissionsState.getPermissions(userId);
2617        final PackageUserState state = ps.readUserState(userId);
2618
2619        return PackageParser.generatePackageInfo(p, gids, flags,
2620                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2621    }
2622
2623    @Override
2624    public boolean isPackageFrozen(String packageName) {
2625        synchronized (mPackages) {
2626            final PackageSetting ps = mSettings.mPackages.get(packageName);
2627            if (ps != null) {
2628                return ps.frozen;
2629            }
2630        }
2631        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2632        return true;
2633    }
2634
2635    @Override
2636    public boolean isPackageAvailable(String packageName, int userId) {
2637        if (!sUserManager.exists(userId)) return false;
2638        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2639        synchronized (mPackages) {
2640            PackageParser.Package p = mPackages.get(packageName);
2641            if (p != null) {
2642                final PackageSetting ps = (PackageSetting) p.mExtras;
2643                if (ps != null) {
2644                    final PackageUserState state = ps.readUserState(userId);
2645                    if (state != null) {
2646                        return PackageParser.isAvailable(state);
2647                    }
2648                }
2649            }
2650        }
2651        return false;
2652    }
2653
2654    @Override
2655    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2656        if (!sUserManager.exists(userId)) return null;
2657        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2658        // reader
2659        synchronized (mPackages) {
2660            PackageParser.Package p = mPackages.get(packageName);
2661            if (DEBUG_PACKAGE_INFO)
2662                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2663            if (p != null) {
2664                return generatePackageInfo(p, flags, userId);
2665            }
2666            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2667                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2668            }
2669        }
2670        return null;
2671    }
2672
2673    @Override
2674    public String[] currentToCanonicalPackageNames(String[] names) {
2675        String[] out = new String[names.length];
2676        // reader
2677        synchronized (mPackages) {
2678            for (int i=names.length-1; i>=0; i--) {
2679                PackageSetting ps = mSettings.mPackages.get(names[i]);
2680                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2681            }
2682        }
2683        return out;
2684    }
2685
2686    @Override
2687    public String[] canonicalToCurrentPackageNames(String[] names) {
2688        String[] out = new String[names.length];
2689        // reader
2690        synchronized (mPackages) {
2691            for (int i=names.length-1; i>=0; i--) {
2692                String cur = mSettings.mRenamedPackages.get(names[i]);
2693                out[i] = cur != null ? cur : names[i];
2694            }
2695        }
2696        return out;
2697    }
2698
2699    @Override
2700    public int getPackageUid(String packageName, int userId) {
2701        if (!sUserManager.exists(userId)) return -1;
2702        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2703
2704        // reader
2705        synchronized (mPackages) {
2706            PackageParser.Package p = mPackages.get(packageName);
2707            if(p != null) {
2708                return UserHandle.getUid(userId, p.applicationInfo.uid);
2709            }
2710            PackageSetting ps = mSettings.mPackages.get(packageName);
2711            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2712                return -1;
2713            }
2714            p = ps.pkg;
2715            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2716        }
2717    }
2718
2719    @Override
2720    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2721        if (!sUserManager.exists(userId)) {
2722            return null;
2723        }
2724
2725        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2726                "getPackageGids");
2727
2728        // reader
2729        synchronized (mPackages) {
2730            PackageParser.Package p = mPackages.get(packageName);
2731            if (DEBUG_PACKAGE_INFO) {
2732                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2733            }
2734            if (p != null) {
2735                PackageSetting ps = (PackageSetting) p.mExtras;
2736                return ps.getPermissionsState().computeGids(userId);
2737            }
2738        }
2739
2740        return null;
2741    }
2742
2743    static PermissionInfo generatePermissionInfo(
2744            BasePermission bp, int flags) {
2745        if (bp.perm != null) {
2746            return PackageParser.generatePermissionInfo(bp.perm, flags);
2747        }
2748        PermissionInfo pi = new PermissionInfo();
2749        pi.name = bp.name;
2750        pi.packageName = bp.sourcePackage;
2751        pi.nonLocalizedLabel = bp.name;
2752        pi.protectionLevel = bp.protectionLevel;
2753        return pi;
2754    }
2755
2756    @Override
2757    public PermissionInfo getPermissionInfo(String name, int flags) {
2758        // reader
2759        synchronized (mPackages) {
2760            final BasePermission p = mSettings.mPermissions.get(name);
2761            if (p != null) {
2762                return generatePermissionInfo(p, flags);
2763            }
2764            return null;
2765        }
2766    }
2767
2768    @Override
2769    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2770        // reader
2771        synchronized (mPackages) {
2772            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2773            for (BasePermission p : mSettings.mPermissions.values()) {
2774                if (group == null) {
2775                    if (p.perm == null || p.perm.info.group == null) {
2776                        out.add(generatePermissionInfo(p, flags));
2777                    }
2778                } else {
2779                    if (p.perm != null && group.equals(p.perm.info.group)) {
2780                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2781                    }
2782                }
2783            }
2784
2785            if (out.size() > 0) {
2786                return out;
2787            }
2788            return mPermissionGroups.containsKey(group) ? out : null;
2789        }
2790    }
2791
2792    @Override
2793    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2794        // reader
2795        synchronized (mPackages) {
2796            return PackageParser.generatePermissionGroupInfo(
2797                    mPermissionGroups.get(name), flags);
2798        }
2799    }
2800
2801    @Override
2802    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2803        // reader
2804        synchronized (mPackages) {
2805            final int N = mPermissionGroups.size();
2806            ArrayList<PermissionGroupInfo> out
2807                    = new ArrayList<PermissionGroupInfo>(N);
2808            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2809                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2810            }
2811            return out;
2812        }
2813    }
2814
2815    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2816            int userId) {
2817        if (!sUserManager.exists(userId)) return null;
2818        PackageSetting ps = mSettings.mPackages.get(packageName);
2819        if (ps != null) {
2820            if (ps.pkg == null) {
2821                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2822                        flags, userId);
2823                if (pInfo != null) {
2824                    return pInfo.applicationInfo;
2825                }
2826                return null;
2827            }
2828            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2829                    ps.readUserState(userId), userId);
2830        }
2831        return null;
2832    }
2833
2834    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2835            int userId) {
2836        if (!sUserManager.exists(userId)) return null;
2837        PackageSetting ps = mSettings.mPackages.get(packageName);
2838        if (ps != null) {
2839            PackageParser.Package pkg = ps.pkg;
2840            if (pkg == null) {
2841                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2842                    return null;
2843                }
2844                // Only data remains, so we aren't worried about code paths
2845                pkg = new PackageParser.Package(packageName);
2846                pkg.applicationInfo.packageName = packageName;
2847                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2848                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2849                pkg.applicationInfo.dataDir = Environment
2850                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2851                        .getAbsolutePath();
2852                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2853                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2854            }
2855            return generatePackageInfo(pkg, flags, userId);
2856        }
2857        return null;
2858    }
2859
2860    @Override
2861    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2862        if (!sUserManager.exists(userId)) return null;
2863        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2864        // writer
2865        synchronized (mPackages) {
2866            PackageParser.Package p = mPackages.get(packageName);
2867            if (DEBUG_PACKAGE_INFO) Log.v(
2868                    TAG, "getApplicationInfo " + packageName
2869                    + ": " + p);
2870            if (p != null) {
2871                PackageSetting ps = mSettings.mPackages.get(packageName);
2872                if (ps == null) return null;
2873                // Note: isEnabledLP() does not apply here - always return info
2874                return PackageParser.generateApplicationInfo(
2875                        p, flags, ps.readUserState(userId), userId);
2876            }
2877            if ("android".equals(packageName)||"system".equals(packageName)) {
2878                return mAndroidApplication;
2879            }
2880            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2881                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2882            }
2883        }
2884        return null;
2885    }
2886
2887    @Override
2888    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2889            final IPackageDataObserver observer) {
2890        mContext.enforceCallingOrSelfPermission(
2891                android.Manifest.permission.CLEAR_APP_CACHE, null);
2892        // Queue up an async operation since clearing cache may take a little while.
2893        mHandler.post(new Runnable() {
2894            public void run() {
2895                mHandler.removeCallbacks(this);
2896                int retCode = -1;
2897                synchronized (mInstallLock) {
2898                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2899                    if (retCode < 0) {
2900                        Slog.w(TAG, "Couldn't clear application caches");
2901                    }
2902                }
2903                if (observer != null) {
2904                    try {
2905                        observer.onRemoveCompleted(null, (retCode >= 0));
2906                    } catch (RemoteException e) {
2907                        Slog.w(TAG, "RemoveException when invoking call back");
2908                    }
2909                }
2910            }
2911        });
2912    }
2913
2914    @Override
2915    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2916            final IntentSender pi) {
2917        mContext.enforceCallingOrSelfPermission(
2918                android.Manifest.permission.CLEAR_APP_CACHE, null);
2919        // Queue up an async operation since clearing cache may take a little while.
2920        mHandler.post(new Runnable() {
2921            public void run() {
2922                mHandler.removeCallbacks(this);
2923                int retCode = -1;
2924                synchronized (mInstallLock) {
2925                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2926                    if (retCode < 0) {
2927                        Slog.w(TAG, "Couldn't clear application caches");
2928                    }
2929                }
2930                if(pi != null) {
2931                    try {
2932                        // Callback via pending intent
2933                        int code = (retCode >= 0) ? 1 : 0;
2934                        pi.sendIntent(null, code, null,
2935                                null, null);
2936                    } catch (SendIntentException e1) {
2937                        Slog.i(TAG, "Failed to send pending intent");
2938                    }
2939                }
2940            }
2941        });
2942    }
2943
2944    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2945        synchronized (mInstallLock) {
2946            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2947                throw new IOException("Failed to free enough space");
2948            }
2949        }
2950    }
2951
2952    @Override
2953    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2954        if (!sUserManager.exists(userId)) return null;
2955        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2956        synchronized (mPackages) {
2957            PackageParser.Activity a = mActivities.mActivities.get(component);
2958
2959            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2960            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2961                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2962                if (ps == null) return null;
2963                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2964                        userId);
2965            }
2966            if (mResolveComponentName.equals(component)) {
2967                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2968                        new PackageUserState(), userId);
2969            }
2970        }
2971        return null;
2972    }
2973
2974    @Override
2975    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2976            String resolvedType) {
2977        synchronized (mPackages) {
2978            PackageParser.Activity a = mActivities.mActivities.get(component);
2979            if (a == null) {
2980                return false;
2981            }
2982            for (int i=0; i<a.intents.size(); i++) {
2983                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2984                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2985                    return true;
2986                }
2987            }
2988            return false;
2989        }
2990    }
2991
2992    @Override
2993    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2994        if (!sUserManager.exists(userId)) return null;
2995        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2996        synchronized (mPackages) {
2997            PackageParser.Activity a = mReceivers.mActivities.get(component);
2998            if (DEBUG_PACKAGE_INFO) Log.v(
2999                TAG, "getReceiverInfo " + component + ": " + a);
3000            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3001                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3002                if (ps == null) return null;
3003                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3004                        userId);
3005            }
3006        }
3007        return null;
3008    }
3009
3010    @Override
3011    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3012        if (!sUserManager.exists(userId)) return null;
3013        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3014        synchronized (mPackages) {
3015            PackageParser.Service s = mServices.mServices.get(component);
3016            if (DEBUG_PACKAGE_INFO) Log.v(
3017                TAG, "getServiceInfo " + component + ": " + s);
3018            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3019                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3020                if (ps == null) return null;
3021                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3022                        userId);
3023            }
3024        }
3025        return null;
3026    }
3027
3028    @Override
3029    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3030        if (!sUserManager.exists(userId)) return null;
3031        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3032        synchronized (mPackages) {
3033            PackageParser.Provider p = mProviders.mProviders.get(component);
3034            if (DEBUG_PACKAGE_INFO) Log.v(
3035                TAG, "getProviderInfo " + component + ": " + p);
3036            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3037                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3038                if (ps == null) return null;
3039                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3040                        userId);
3041            }
3042        }
3043        return null;
3044    }
3045
3046    @Override
3047    public String[] getSystemSharedLibraryNames() {
3048        Set<String> libSet;
3049        synchronized (mPackages) {
3050            libSet = mSharedLibraries.keySet();
3051            int size = libSet.size();
3052            if (size > 0) {
3053                String[] libs = new String[size];
3054                libSet.toArray(libs);
3055                return libs;
3056            }
3057        }
3058        return null;
3059    }
3060
3061    /**
3062     * @hide
3063     */
3064    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3065        synchronized (mPackages) {
3066            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3067            if (lib != null && lib.apk != null) {
3068                return mPackages.get(lib.apk);
3069            }
3070        }
3071        return null;
3072    }
3073
3074    @Override
3075    public FeatureInfo[] getSystemAvailableFeatures() {
3076        Collection<FeatureInfo> featSet;
3077        synchronized (mPackages) {
3078            featSet = mAvailableFeatures.values();
3079            int size = featSet.size();
3080            if (size > 0) {
3081                FeatureInfo[] features = new FeatureInfo[size+1];
3082                featSet.toArray(features);
3083                FeatureInfo fi = new FeatureInfo();
3084                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3085                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3086                features[size] = fi;
3087                return features;
3088            }
3089        }
3090        return null;
3091    }
3092
3093    @Override
3094    public boolean hasSystemFeature(String name) {
3095        synchronized (mPackages) {
3096            return mAvailableFeatures.containsKey(name);
3097        }
3098    }
3099
3100    private void checkValidCaller(int uid, int userId) {
3101        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3102            return;
3103
3104        throw new SecurityException("Caller uid=" + uid
3105                + " is not privileged to communicate with user=" + userId);
3106    }
3107
3108    @Override
3109    public int checkPermission(String permName, String pkgName, int userId) {
3110        if (!sUserManager.exists(userId)) {
3111            return PackageManager.PERMISSION_DENIED;
3112        }
3113
3114        synchronized (mPackages) {
3115            final PackageParser.Package p = mPackages.get(pkgName);
3116            if (p != null && p.mExtras != null) {
3117                final PackageSetting ps = (PackageSetting) p.mExtras;
3118                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3119                    return PackageManager.PERMISSION_GRANTED;
3120                }
3121            }
3122        }
3123
3124        return PackageManager.PERMISSION_DENIED;
3125    }
3126
3127    @Override
3128    public int checkUidPermission(String permName, int uid) {
3129        final int userId = UserHandle.getUserId(uid);
3130
3131        if (!sUserManager.exists(userId)) {
3132            return PackageManager.PERMISSION_DENIED;
3133        }
3134
3135        synchronized (mPackages) {
3136            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3137            if (obj != null) {
3138                final SettingBase ps = (SettingBase) obj;
3139                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3140                    return PackageManager.PERMISSION_GRANTED;
3141                }
3142            } else {
3143                ArraySet<String> perms = mSystemPermissions.get(uid);
3144                if (perms != null && perms.contains(permName)) {
3145                    return PackageManager.PERMISSION_GRANTED;
3146                }
3147            }
3148        }
3149
3150        return PackageManager.PERMISSION_DENIED;
3151    }
3152
3153    @Override
3154    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3155        if (UserHandle.getCallingUserId() != userId) {
3156            mContext.enforceCallingPermission(
3157                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3158                    "isPermissionRevokedByPolicy for user " + userId);
3159        }
3160
3161        if (checkPermission(permission, packageName, userId)
3162                == PackageManager.PERMISSION_GRANTED) {
3163            return false;
3164        }
3165
3166        final long identity = Binder.clearCallingIdentity();
3167        try {
3168            final int flags = getPermissionFlags(permission, packageName, userId);
3169            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3170        } finally {
3171            Binder.restoreCallingIdentity(identity);
3172        }
3173    }
3174
3175    /**
3176     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3177     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3178     * @param checkShell TODO(yamasani):
3179     * @param message the message to log on security exception
3180     */
3181    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3182            boolean checkShell, String message) {
3183        if (userId < 0) {
3184            throw new IllegalArgumentException("Invalid userId " + userId);
3185        }
3186        if (checkShell) {
3187            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3188        }
3189        if (userId == UserHandle.getUserId(callingUid)) return;
3190        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3191            if (requireFullPermission) {
3192                mContext.enforceCallingOrSelfPermission(
3193                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3194            } else {
3195                try {
3196                    mContext.enforceCallingOrSelfPermission(
3197                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3198                } catch (SecurityException se) {
3199                    mContext.enforceCallingOrSelfPermission(
3200                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3201                }
3202            }
3203        }
3204    }
3205
3206    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3207        if (callingUid == Process.SHELL_UID) {
3208            if (userHandle >= 0
3209                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3210                throw new SecurityException("Shell does not have permission to access user "
3211                        + userHandle);
3212            } else if (userHandle < 0) {
3213                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3214                        + Debug.getCallers(3));
3215            }
3216        }
3217    }
3218
3219    private BasePermission findPermissionTreeLP(String permName) {
3220        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3221            if (permName.startsWith(bp.name) &&
3222                    permName.length() > bp.name.length() &&
3223                    permName.charAt(bp.name.length()) == '.') {
3224                return bp;
3225            }
3226        }
3227        return null;
3228    }
3229
3230    private BasePermission checkPermissionTreeLP(String permName) {
3231        if (permName != null) {
3232            BasePermission bp = findPermissionTreeLP(permName);
3233            if (bp != null) {
3234                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3235                    return bp;
3236                }
3237                throw new SecurityException("Calling uid "
3238                        + Binder.getCallingUid()
3239                        + " is not allowed to add to permission tree "
3240                        + bp.name + " owned by uid " + bp.uid);
3241            }
3242        }
3243        throw new SecurityException("No permission tree found for " + permName);
3244    }
3245
3246    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3247        if (s1 == null) {
3248            return s2 == null;
3249        }
3250        if (s2 == null) {
3251            return false;
3252        }
3253        if (s1.getClass() != s2.getClass()) {
3254            return false;
3255        }
3256        return s1.equals(s2);
3257    }
3258
3259    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3260        if (pi1.icon != pi2.icon) return false;
3261        if (pi1.logo != pi2.logo) return false;
3262        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3263        if (!compareStrings(pi1.name, pi2.name)) return false;
3264        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3265        // We'll take care of setting this one.
3266        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3267        // These are not currently stored in settings.
3268        //if (!compareStrings(pi1.group, pi2.group)) return false;
3269        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3270        //if (pi1.labelRes != pi2.labelRes) return false;
3271        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3272        return true;
3273    }
3274
3275    int permissionInfoFootprint(PermissionInfo info) {
3276        int size = info.name.length();
3277        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3278        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3279        return size;
3280    }
3281
3282    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3283        int size = 0;
3284        for (BasePermission perm : mSettings.mPermissions.values()) {
3285            if (perm.uid == tree.uid) {
3286                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3287            }
3288        }
3289        return size;
3290    }
3291
3292    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3293        // We calculate the max size of permissions defined by this uid and throw
3294        // if that plus the size of 'info' would exceed our stated maximum.
3295        if (tree.uid != Process.SYSTEM_UID) {
3296            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3297            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3298                throw new SecurityException("Permission tree size cap exceeded");
3299            }
3300        }
3301    }
3302
3303    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3304        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3305            throw new SecurityException("Label must be specified in permission");
3306        }
3307        BasePermission tree = checkPermissionTreeLP(info.name);
3308        BasePermission bp = mSettings.mPermissions.get(info.name);
3309        boolean added = bp == null;
3310        boolean changed = true;
3311        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3312        if (added) {
3313            enforcePermissionCapLocked(info, tree);
3314            bp = new BasePermission(info.name, tree.sourcePackage,
3315                    BasePermission.TYPE_DYNAMIC);
3316        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3317            throw new SecurityException(
3318                    "Not allowed to modify non-dynamic permission "
3319                    + info.name);
3320        } else {
3321            if (bp.protectionLevel == fixedLevel
3322                    && bp.perm.owner.equals(tree.perm.owner)
3323                    && bp.uid == tree.uid
3324                    && comparePermissionInfos(bp.perm.info, info)) {
3325                changed = false;
3326            }
3327        }
3328        bp.protectionLevel = fixedLevel;
3329        info = new PermissionInfo(info);
3330        info.protectionLevel = fixedLevel;
3331        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3332        bp.perm.info.packageName = tree.perm.info.packageName;
3333        bp.uid = tree.uid;
3334        if (added) {
3335            mSettings.mPermissions.put(info.name, bp);
3336        }
3337        if (changed) {
3338            if (!async) {
3339                mSettings.writeLPr();
3340            } else {
3341                scheduleWriteSettingsLocked();
3342            }
3343        }
3344        return added;
3345    }
3346
3347    @Override
3348    public boolean addPermission(PermissionInfo info) {
3349        synchronized (mPackages) {
3350            return addPermissionLocked(info, false);
3351        }
3352    }
3353
3354    @Override
3355    public boolean addPermissionAsync(PermissionInfo info) {
3356        synchronized (mPackages) {
3357            return addPermissionLocked(info, true);
3358        }
3359    }
3360
3361    @Override
3362    public void removePermission(String name) {
3363        synchronized (mPackages) {
3364            checkPermissionTreeLP(name);
3365            BasePermission bp = mSettings.mPermissions.get(name);
3366            if (bp != null) {
3367                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3368                    throw new SecurityException(
3369                            "Not allowed to modify non-dynamic permission "
3370                            + name);
3371                }
3372                mSettings.mPermissions.remove(name);
3373                mSettings.writeLPr();
3374            }
3375        }
3376    }
3377
3378    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3379            BasePermission bp) {
3380        int index = pkg.requestedPermissions.indexOf(bp.name);
3381        if (index == -1) {
3382            throw new SecurityException("Package " + pkg.packageName
3383                    + " has not requested permission " + bp.name);
3384        }
3385        if (!bp.isRuntime()) {
3386            throw new SecurityException("Permission " + bp.name
3387                    + " is not a changeable permission type");
3388        }
3389    }
3390
3391    @Override
3392    public void grantRuntimePermission(String packageName, String name, final int userId) {
3393        if (!sUserManager.exists(userId)) {
3394            Log.e(TAG, "No such user:" + userId);
3395            return;
3396        }
3397
3398        mContext.enforceCallingOrSelfPermission(
3399                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3400                "grantRuntimePermission");
3401
3402        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3403                "grantRuntimePermission");
3404
3405        final int uid;
3406        final SettingBase sb;
3407
3408        synchronized (mPackages) {
3409            final PackageParser.Package pkg = mPackages.get(packageName);
3410            if (pkg == null) {
3411                throw new IllegalArgumentException("Unknown package: " + packageName);
3412            }
3413
3414            final BasePermission bp = mSettings.mPermissions.get(name);
3415            if (bp == null) {
3416                throw new IllegalArgumentException("Unknown permission: " + name);
3417            }
3418
3419            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3420
3421            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3422            sb = (SettingBase) pkg.mExtras;
3423            if (sb == null) {
3424                throw new IllegalArgumentException("Unknown package: " + packageName);
3425            }
3426
3427            final PermissionsState permissionsState = sb.getPermissionsState();
3428
3429            final int flags = permissionsState.getPermissionFlags(name, userId);
3430            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3431                throw new SecurityException("Cannot grant system fixed permission: "
3432                        + name + " for package: " + packageName);
3433            }
3434
3435            final int result = permissionsState.grantRuntimePermission(bp, userId);
3436            switch (result) {
3437                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3438                    return;
3439                }
3440
3441                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3442                    mHandler.post(new Runnable() {
3443                        @Override
3444                        public void run() {
3445                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3446                        }
3447                    });
3448                } break;
3449            }
3450
3451            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3452
3453            // Not critical if that is lost - app has to request again.
3454            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3455        }
3456
3457        // Only need to do this if user is initialized. Otherwise it's a new user
3458        // and there are no processes running as the user yet and there's no need
3459        // to make an expensive call to remount processes for the changed permissions.
3460        if (READ_EXTERNAL_STORAGE.equals(name)
3461                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3462            final long token = Binder.clearCallingIdentity();
3463            try {
3464                if (sUserManager.isInitialized(userId)) {
3465                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3466                            MountServiceInternal.class);
3467                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3468                }
3469            } finally {
3470                Binder.restoreCallingIdentity(token);
3471            }
3472        }
3473    }
3474
3475    @Override
3476    public void revokeRuntimePermission(String packageName, String name, int userId) {
3477        if (!sUserManager.exists(userId)) {
3478            Log.e(TAG, "No such user:" + userId);
3479            return;
3480        }
3481
3482        mContext.enforceCallingOrSelfPermission(
3483                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3484                "revokeRuntimePermission");
3485
3486        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3487                "revokeRuntimePermission");
3488
3489        final SettingBase sb;
3490
3491        synchronized (mPackages) {
3492            final PackageParser.Package pkg = mPackages.get(packageName);
3493            if (pkg == null) {
3494                throw new IllegalArgumentException("Unknown package: " + packageName);
3495            }
3496
3497            final BasePermission bp = mSettings.mPermissions.get(name);
3498            if (bp == null) {
3499                throw new IllegalArgumentException("Unknown permission: " + name);
3500            }
3501
3502            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3503
3504            sb = (SettingBase) pkg.mExtras;
3505            if (sb == null) {
3506                throw new IllegalArgumentException("Unknown package: " + packageName);
3507            }
3508
3509            final PermissionsState permissionsState = sb.getPermissionsState();
3510
3511            final int flags = permissionsState.getPermissionFlags(name, userId);
3512            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3513                throw new SecurityException("Cannot revoke system fixed permission: "
3514                        + name + " for package: " + packageName);
3515            }
3516
3517            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3518                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3519                return;
3520            }
3521
3522            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3523
3524            // Critical, after this call app should never have the permission.
3525            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3526        }
3527
3528        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3529    }
3530
3531    @Override
3532    public void resetRuntimePermissions() {
3533        mContext.enforceCallingOrSelfPermission(
3534                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3535                "revokeRuntimePermission");
3536
3537        int callingUid = Binder.getCallingUid();
3538        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3539            mContext.enforceCallingOrSelfPermission(
3540                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3541                    "resetRuntimePermissions");
3542        }
3543
3544        synchronized (mPackages) {
3545            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3546            for (int userId : UserManagerService.getInstance().getUserIds()) {
3547                final int packageCount = mPackages.size();
3548                for (int i = 0; i < packageCount; i++) {
3549                    PackageParser.Package pkg = mPackages.valueAt(i);
3550                    if (!(pkg.mExtras instanceof PackageSetting)) {
3551                        continue;
3552                    }
3553                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3554                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
3555                }
3556            }
3557        }
3558    }
3559
3560    @Override
3561    public int getPermissionFlags(String name, String packageName, int userId) {
3562        if (!sUserManager.exists(userId)) {
3563            return 0;
3564        }
3565
3566        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3567
3568        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3569                "getPermissionFlags");
3570
3571        synchronized (mPackages) {
3572            final PackageParser.Package pkg = mPackages.get(packageName);
3573            if (pkg == null) {
3574                throw new IllegalArgumentException("Unknown package: " + packageName);
3575            }
3576
3577            final BasePermission bp = mSettings.mPermissions.get(name);
3578            if (bp == null) {
3579                throw new IllegalArgumentException("Unknown permission: " + name);
3580            }
3581
3582            SettingBase sb = (SettingBase) pkg.mExtras;
3583            if (sb == null) {
3584                throw new IllegalArgumentException("Unknown package: " + packageName);
3585            }
3586
3587            PermissionsState permissionsState = sb.getPermissionsState();
3588            return permissionsState.getPermissionFlags(name, userId);
3589        }
3590    }
3591
3592    @Override
3593    public void updatePermissionFlags(String name, String packageName, int flagMask,
3594            int flagValues, int userId) {
3595        if (!sUserManager.exists(userId)) {
3596            return;
3597        }
3598
3599        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3600
3601        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3602                "updatePermissionFlags");
3603
3604        // Only the system can change system fixed flags.
3605        if (getCallingUid() != Process.SYSTEM_UID) {
3606            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3607            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3608        }
3609
3610        synchronized (mPackages) {
3611            final PackageParser.Package pkg = mPackages.get(packageName);
3612            if (pkg == null) {
3613                throw new IllegalArgumentException("Unknown package: " + packageName);
3614            }
3615
3616            final BasePermission bp = mSettings.mPermissions.get(name);
3617            if (bp == null) {
3618                throw new IllegalArgumentException("Unknown permission: " + name);
3619            }
3620
3621            SettingBase sb = (SettingBase) pkg.mExtras;
3622            if (sb == null) {
3623                throw new IllegalArgumentException("Unknown package: " + packageName);
3624            }
3625
3626            PermissionsState permissionsState = sb.getPermissionsState();
3627
3628            // Only the package manager can change flags for system component permissions.
3629            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3630            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3631                return;
3632            }
3633
3634            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3635
3636            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3637                // Install and runtime permissions are stored in different places,
3638                // so figure out what permission changed and persist the change.
3639                if (permissionsState.getInstallPermissionState(name) != null) {
3640                    scheduleWriteSettingsLocked();
3641                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3642                        || hadState) {
3643                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3644                }
3645            }
3646        }
3647    }
3648
3649    /**
3650     * Update the permission flags for all packages and runtime permissions of a user in order
3651     * to allow device or profile owner to remove POLICY_FIXED.
3652     */
3653    @Override
3654    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3655        if (!sUserManager.exists(userId)) {
3656            return;
3657        }
3658
3659        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3660
3661        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3662                "updatePermissionFlagsForAllApps");
3663
3664        // Only the system can change system fixed flags.
3665        if (getCallingUid() != Process.SYSTEM_UID) {
3666            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3667            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3668        }
3669
3670        synchronized (mPackages) {
3671            boolean changed = false;
3672            final int packageCount = mPackages.size();
3673            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3674                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3675                SettingBase sb = (SettingBase) pkg.mExtras;
3676                if (sb == null) {
3677                    continue;
3678                }
3679                PermissionsState permissionsState = sb.getPermissionsState();
3680                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3681                        userId, flagMask, flagValues);
3682            }
3683            if (changed) {
3684                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3685            }
3686        }
3687    }
3688
3689    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3690        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3691                != PackageManager.PERMISSION_GRANTED
3692            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3693                != PackageManager.PERMISSION_GRANTED) {
3694            throw new SecurityException(message + " requires "
3695                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3696                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3697        }
3698    }
3699
3700    @Override
3701    public boolean shouldShowRequestPermissionRationale(String permissionName,
3702            String packageName, int userId) {
3703        if (UserHandle.getCallingUserId() != userId) {
3704            mContext.enforceCallingPermission(
3705                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3706                    "canShowRequestPermissionRationale for user " + userId);
3707        }
3708
3709        final int uid = getPackageUid(packageName, userId);
3710        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3711            return false;
3712        }
3713
3714        if (checkPermission(permissionName, packageName, userId)
3715                == PackageManager.PERMISSION_GRANTED) {
3716            return false;
3717        }
3718
3719        final int flags;
3720
3721        final long identity = Binder.clearCallingIdentity();
3722        try {
3723            flags = getPermissionFlags(permissionName,
3724                    packageName, userId);
3725        } finally {
3726            Binder.restoreCallingIdentity(identity);
3727        }
3728
3729        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3730                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3731                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3732
3733        if ((flags & fixedFlags) != 0) {
3734            return false;
3735        }
3736
3737        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3738    }
3739
3740    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3741        BasePermission bp = mSettings.mPermissions.get(permission);
3742        if (bp == null) {
3743            throw new SecurityException("Missing " + permission + " permission");
3744        }
3745
3746        SettingBase sb = (SettingBase) pkg.mExtras;
3747        PermissionsState permissionsState = sb.getPermissionsState();
3748
3749        if (permissionsState.grantInstallPermission(bp) !=
3750                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3751            scheduleWriteSettingsLocked();
3752        }
3753    }
3754
3755    @Override
3756    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3757        mContext.enforceCallingOrSelfPermission(
3758                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3759                "addOnPermissionsChangeListener");
3760
3761        synchronized (mPackages) {
3762            mOnPermissionChangeListeners.addListenerLocked(listener);
3763        }
3764    }
3765
3766    @Override
3767    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3768        synchronized (mPackages) {
3769            mOnPermissionChangeListeners.removeListenerLocked(listener);
3770        }
3771    }
3772
3773    @Override
3774    public boolean isProtectedBroadcast(String actionName) {
3775        synchronized (mPackages) {
3776            return mProtectedBroadcasts.contains(actionName);
3777        }
3778    }
3779
3780    @Override
3781    public int checkSignatures(String pkg1, String pkg2) {
3782        synchronized (mPackages) {
3783            final PackageParser.Package p1 = mPackages.get(pkg1);
3784            final PackageParser.Package p2 = mPackages.get(pkg2);
3785            if (p1 == null || p1.mExtras == null
3786                    || p2 == null || p2.mExtras == null) {
3787                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3788            }
3789            return compareSignatures(p1.mSignatures, p2.mSignatures);
3790        }
3791    }
3792
3793    @Override
3794    public int checkUidSignatures(int uid1, int uid2) {
3795        // Map to base uids.
3796        uid1 = UserHandle.getAppId(uid1);
3797        uid2 = UserHandle.getAppId(uid2);
3798        // reader
3799        synchronized (mPackages) {
3800            Signature[] s1;
3801            Signature[] s2;
3802            Object obj = mSettings.getUserIdLPr(uid1);
3803            if (obj != null) {
3804                if (obj instanceof SharedUserSetting) {
3805                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3806                } else if (obj instanceof PackageSetting) {
3807                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3808                } else {
3809                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3810                }
3811            } else {
3812                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3813            }
3814            obj = mSettings.getUserIdLPr(uid2);
3815            if (obj != null) {
3816                if (obj instanceof SharedUserSetting) {
3817                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3818                } else if (obj instanceof PackageSetting) {
3819                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3820                } else {
3821                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3822                }
3823            } else {
3824                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3825            }
3826            return compareSignatures(s1, s2);
3827        }
3828    }
3829
3830    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3831        final long identity = Binder.clearCallingIdentity();
3832        try {
3833            if (sb instanceof SharedUserSetting) {
3834                SharedUserSetting sus = (SharedUserSetting) sb;
3835                final int packageCount = sus.packages.size();
3836                for (int i = 0; i < packageCount; i++) {
3837                    PackageSetting susPs = sus.packages.valueAt(i);
3838                    if (userId == UserHandle.USER_ALL) {
3839                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3840                    } else {
3841                        final int uid = UserHandle.getUid(userId, susPs.appId);
3842                        killUid(uid, reason);
3843                    }
3844                }
3845            } else if (sb instanceof PackageSetting) {
3846                PackageSetting ps = (PackageSetting) sb;
3847                if (userId == UserHandle.USER_ALL) {
3848                    killApplication(ps.pkg.packageName, ps.appId, reason);
3849                } else {
3850                    final int uid = UserHandle.getUid(userId, ps.appId);
3851                    killUid(uid, reason);
3852                }
3853            }
3854        } finally {
3855            Binder.restoreCallingIdentity(identity);
3856        }
3857    }
3858
3859    private static void killUid(int uid, String reason) {
3860        IActivityManager am = ActivityManagerNative.getDefault();
3861        if (am != null) {
3862            try {
3863                am.killUid(uid, reason);
3864            } catch (RemoteException e) {
3865                /* ignore - same process */
3866            }
3867        }
3868    }
3869
3870    /**
3871     * Compares two sets of signatures. Returns:
3872     * <br />
3873     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3874     * <br />
3875     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3876     * <br />
3877     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3878     * <br />
3879     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3880     * <br />
3881     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3882     */
3883    static int compareSignatures(Signature[] s1, Signature[] s2) {
3884        if (s1 == null) {
3885            return s2 == null
3886                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3887                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3888        }
3889
3890        if (s2 == null) {
3891            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3892        }
3893
3894        if (s1.length != s2.length) {
3895            return PackageManager.SIGNATURE_NO_MATCH;
3896        }
3897
3898        // Since both signature sets are of size 1, we can compare without HashSets.
3899        if (s1.length == 1) {
3900            return s1[0].equals(s2[0]) ?
3901                    PackageManager.SIGNATURE_MATCH :
3902                    PackageManager.SIGNATURE_NO_MATCH;
3903        }
3904
3905        ArraySet<Signature> set1 = new ArraySet<Signature>();
3906        for (Signature sig : s1) {
3907            set1.add(sig);
3908        }
3909        ArraySet<Signature> set2 = new ArraySet<Signature>();
3910        for (Signature sig : s2) {
3911            set2.add(sig);
3912        }
3913        // Make sure s2 contains all signatures in s1.
3914        if (set1.equals(set2)) {
3915            return PackageManager.SIGNATURE_MATCH;
3916        }
3917        return PackageManager.SIGNATURE_NO_MATCH;
3918    }
3919
3920    /**
3921     * If the database version for this type of package (internal storage or
3922     * external storage) is less than the version where package signatures
3923     * were updated, return true.
3924     */
3925    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3926        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3927        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3928    }
3929
3930    /**
3931     * Used for backward compatibility to make sure any packages with
3932     * certificate chains get upgraded to the new style. {@code existingSigs}
3933     * will be in the old format (since they were stored on disk from before the
3934     * system upgrade) and {@code scannedSigs} will be in the newer format.
3935     */
3936    private int compareSignaturesCompat(PackageSignatures existingSigs,
3937            PackageParser.Package scannedPkg) {
3938        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3939            return PackageManager.SIGNATURE_NO_MATCH;
3940        }
3941
3942        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3943        for (Signature sig : existingSigs.mSignatures) {
3944            existingSet.add(sig);
3945        }
3946        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3947        for (Signature sig : scannedPkg.mSignatures) {
3948            try {
3949                Signature[] chainSignatures = sig.getChainSignatures();
3950                for (Signature chainSig : chainSignatures) {
3951                    scannedCompatSet.add(chainSig);
3952                }
3953            } catch (CertificateEncodingException e) {
3954                scannedCompatSet.add(sig);
3955            }
3956        }
3957        /*
3958         * Make sure the expanded scanned set contains all signatures in the
3959         * existing one.
3960         */
3961        if (scannedCompatSet.equals(existingSet)) {
3962            // Migrate the old signatures to the new scheme.
3963            existingSigs.assignSignatures(scannedPkg.mSignatures);
3964            // The new KeySets will be re-added later in the scanning process.
3965            synchronized (mPackages) {
3966                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3967            }
3968            return PackageManager.SIGNATURE_MATCH;
3969        }
3970        return PackageManager.SIGNATURE_NO_MATCH;
3971    }
3972
3973    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3974        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3975        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
3976    }
3977
3978    private int compareSignaturesRecover(PackageSignatures existingSigs,
3979            PackageParser.Package scannedPkg) {
3980        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3981            return PackageManager.SIGNATURE_NO_MATCH;
3982        }
3983
3984        String msg = null;
3985        try {
3986            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3987                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3988                        + scannedPkg.packageName);
3989                return PackageManager.SIGNATURE_MATCH;
3990            }
3991        } catch (CertificateException e) {
3992            msg = e.getMessage();
3993        }
3994
3995        logCriticalInfo(Log.INFO,
3996                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3997        return PackageManager.SIGNATURE_NO_MATCH;
3998    }
3999
4000    @Override
4001    public String[] getPackagesForUid(int uid) {
4002        uid = UserHandle.getAppId(uid);
4003        // reader
4004        synchronized (mPackages) {
4005            Object obj = mSettings.getUserIdLPr(uid);
4006            if (obj instanceof SharedUserSetting) {
4007                final SharedUserSetting sus = (SharedUserSetting) obj;
4008                final int N = sus.packages.size();
4009                final String[] res = new String[N];
4010                final Iterator<PackageSetting> it = sus.packages.iterator();
4011                int i = 0;
4012                while (it.hasNext()) {
4013                    res[i++] = it.next().name;
4014                }
4015                return res;
4016            } else if (obj instanceof PackageSetting) {
4017                final PackageSetting ps = (PackageSetting) obj;
4018                return new String[] { ps.name };
4019            }
4020        }
4021        return null;
4022    }
4023
4024    @Override
4025    public String getNameForUid(int uid) {
4026        // reader
4027        synchronized (mPackages) {
4028            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4029            if (obj instanceof SharedUserSetting) {
4030                final SharedUserSetting sus = (SharedUserSetting) obj;
4031                return sus.name + ":" + sus.userId;
4032            } else if (obj instanceof PackageSetting) {
4033                final PackageSetting ps = (PackageSetting) obj;
4034                return ps.name;
4035            }
4036        }
4037        return null;
4038    }
4039
4040    @Override
4041    public int getUidForSharedUser(String sharedUserName) {
4042        if(sharedUserName == null) {
4043            return -1;
4044        }
4045        // reader
4046        synchronized (mPackages) {
4047            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4048            if (suid == null) {
4049                return -1;
4050            }
4051            return suid.userId;
4052        }
4053    }
4054
4055    @Override
4056    public int getFlagsForUid(int uid) {
4057        synchronized (mPackages) {
4058            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4059            if (obj instanceof SharedUserSetting) {
4060                final SharedUserSetting sus = (SharedUserSetting) obj;
4061                return sus.pkgFlags;
4062            } else if (obj instanceof PackageSetting) {
4063                final PackageSetting ps = (PackageSetting) obj;
4064                return ps.pkgFlags;
4065            }
4066        }
4067        return 0;
4068    }
4069
4070    @Override
4071    public int getPrivateFlagsForUid(int uid) {
4072        synchronized (mPackages) {
4073            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4074            if (obj instanceof SharedUserSetting) {
4075                final SharedUserSetting sus = (SharedUserSetting) obj;
4076                return sus.pkgPrivateFlags;
4077            } else if (obj instanceof PackageSetting) {
4078                final PackageSetting ps = (PackageSetting) obj;
4079                return ps.pkgPrivateFlags;
4080            }
4081        }
4082        return 0;
4083    }
4084
4085    @Override
4086    public boolean isUidPrivileged(int uid) {
4087        uid = UserHandle.getAppId(uid);
4088        // reader
4089        synchronized (mPackages) {
4090            Object obj = mSettings.getUserIdLPr(uid);
4091            if (obj instanceof SharedUserSetting) {
4092                final SharedUserSetting sus = (SharedUserSetting) obj;
4093                final Iterator<PackageSetting> it = sus.packages.iterator();
4094                while (it.hasNext()) {
4095                    if (it.next().isPrivileged()) {
4096                        return true;
4097                    }
4098                }
4099            } else if (obj instanceof PackageSetting) {
4100                final PackageSetting ps = (PackageSetting) obj;
4101                return ps.isPrivileged();
4102            }
4103        }
4104        return false;
4105    }
4106
4107    @Override
4108    public String[] getAppOpPermissionPackages(String permissionName) {
4109        synchronized (mPackages) {
4110            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4111            if (pkgs == null) {
4112                return null;
4113            }
4114            return pkgs.toArray(new String[pkgs.size()]);
4115        }
4116    }
4117
4118    @Override
4119    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4120            int flags, int userId) {
4121        if (!sUserManager.exists(userId)) return null;
4122        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4123        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4124        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4125    }
4126
4127    @Override
4128    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4129            IntentFilter filter, int match, ComponentName activity) {
4130        final int userId = UserHandle.getCallingUserId();
4131        if (DEBUG_PREFERRED) {
4132            Log.v(TAG, "setLastChosenActivity intent=" + intent
4133                + " resolvedType=" + resolvedType
4134                + " flags=" + flags
4135                + " filter=" + filter
4136                + " match=" + match
4137                + " activity=" + activity);
4138            filter.dump(new PrintStreamPrinter(System.out), "    ");
4139        }
4140        intent.setComponent(null);
4141        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4142        // Find any earlier preferred or last chosen entries and nuke them
4143        findPreferredActivity(intent, resolvedType,
4144                flags, query, 0, false, true, false, userId);
4145        // Add the new activity as the last chosen for this filter
4146        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4147                "Setting last chosen");
4148    }
4149
4150    @Override
4151    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4152        final int userId = UserHandle.getCallingUserId();
4153        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4154        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4155        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4156                false, false, false, userId);
4157    }
4158
4159    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4160            int flags, List<ResolveInfo> query, int userId) {
4161        if (query != null) {
4162            final int N = query.size();
4163            if (N == 1) {
4164                return query.get(0);
4165            } else if (N > 1) {
4166                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4167                // If there is more than one activity with the same priority,
4168                // then let the user decide between them.
4169                ResolveInfo r0 = query.get(0);
4170                ResolveInfo r1 = query.get(1);
4171                if (DEBUG_INTENT_MATCHING || debug) {
4172                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4173                            + r1.activityInfo.name + "=" + r1.priority);
4174                }
4175                // If the first activity has a higher priority, or a different
4176                // default, then it is always desireable to pick it.
4177                if (r0.priority != r1.priority
4178                        || r0.preferredOrder != r1.preferredOrder
4179                        || r0.isDefault != r1.isDefault) {
4180                    return query.get(0);
4181                }
4182                // If we have saved a preference for a preferred activity for
4183                // this Intent, use that.
4184                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4185                        flags, query, r0.priority, true, false, debug, userId);
4186                if (ri != null) {
4187                    return ri;
4188                }
4189                if (userId != 0) {
4190                    ri = new ResolveInfo(mResolveInfo);
4191                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4192                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4193                            ri.activityInfo.applicationInfo);
4194                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4195                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4196                    return ri;
4197                }
4198                return mResolveInfo;
4199            }
4200        }
4201        return null;
4202    }
4203
4204    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4205            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4206        final int N = query.size();
4207        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4208                .get(userId);
4209        // Get the list of persistent preferred activities that handle the intent
4210        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4211        List<PersistentPreferredActivity> pprefs = ppir != null
4212                ? ppir.queryIntent(intent, resolvedType,
4213                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4214                : null;
4215        if (pprefs != null && pprefs.size() > 0) {
4216            final int M = pprefs.size();
4217            for (int i=0; i<M; i++) {
4218                final PersistentPreferredActivity ppa = pprefs.get(i);
4219                if (DEBUG_PREFERRED || debug) {
4220                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4221                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4222                            + "\n  component=" + ppa.mComponent);
4223                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4224                }
4225                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4226                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4227                if (DEBUG_PREFERRED || debug) {
4228                    Slog.v(TAG, "Found persistent preferred activity:");
4229                    if (ai != null) {
4230                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4231                    } else {
4232                        Slog.v(TAG, "  null");
4233                    }
4234                }
4235                if (ai == null) {
4236                    // This previously registered persistent preferred activity
4237                    // component is no longer known. Ignore it and do NOT remove it.
4238                    continue;
4239                }
4240                for (int j=0; j<N; j++) {
4241                    final ResolveInfo ri = query.get(j);
4242                    if (!ri.activityInfo.applicationInfo.packageName
4243                            .equals(ai.applicationInfo.packageName)) {
4244                        continue;
4245                    }
4246                    if (!ri.activityInfo.name.equals(ai.name)) {
4247                        continue;
4248                    }
4249                    //  Found a persistent preference that can handle the intent.
4250                    if (DEBUG_PREFERRED || debug) {
4251                        Slog.v(TAG, "Returning persistent preferred activity: " +
4252                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4253                    }
4254                    return ri;
4255                }
4256            }
4257        }
4258        return null;
4259    }
4260
4261    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4262            List<ResolveInfo> query, int priority, boolean always,
4263            boolean removeMatches, boolean debug, int userId) {
4264        if (!sUserManager.exists(userId)) return null;
4265        // writer
4266        synchronized (mPackages) {
4267            if (intent.getSelector() != null) {
4268                intent = intent.getSelector();
4269            }
4270            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4271
4272            // Try to find a matching persistent preferred activity.
4273            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4274                    debug, userId);
4275
4276            // If a persistent preferred activity matched, use it.
4277            if (pri != null) {
4278                return pri;
4279            }
4280
4281            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4282            // Get the list of preferred activities that handle the intent
4283            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4284            List<PreferredActivity> prefs = pir != null
4285                    ? pir.queryIntent(intent, resolvedType,
4286                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4287                    : null;
4288            if (prefs != null && prefs.size() > 0) {
4289                boolean changed = false;
4290                try {
4291                    // First figure out how good the original match set is.
4292                    // We will only allow preferred activities that came
4293                    // from the same match quality.
4294                    int match = 0;
4295
4296                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4297
4298                    final int N = query.size();
4299                    for (int j=0; j<N; j++) {
4300                        final ResolveInfo ri = query.get(j);
4301                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4302                                + ": 0x" + Integer.toHexString(match));
4303                        if (ri.match > match) {
4304                            match = ri.match;
4305                        }
4306                    }
4307
4308                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4309                            + Integer.toHexString(match));
4310
4311                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4312                    final int M = prefs.size();
4313                    for (int i=0; i<M; i++) {
4314                        final PreferredActivity pa = prefs.get(i);
4315                        if (DEBUG_PREFERRED || debug) {
4316                            Slog.v(TAG, "Checking PreferredActivity ds="
4317                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4318                                    + "\n  component=" + pa.mPref.mComponent);
4319                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4320                        }
4321                        if (pa.mPref.mMatch != match) {
4322                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4323                                    + Integer.toHexString(pa.mPref.mMatch));
4324                            continue;
4325                        }
4326                        // If it's not an "always" type preferred activity and that's what we're
4327                        // looking for, skip it.
4328                        if (always && !pa.mPref.mAlways) {
4329                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4330                            continue;
4331                        }
4332                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4333                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4334                        if (DEBUG_PREFERRED || debug) {
4335                            Slog.v(TAG, "Found preferred activity:");
4336                            if (ai != null) {
4337                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4338                            } else {
4339                                Slog.v(TAG, "  null");
4340                            }
4341                        }
4342                        if (ai == null) {
4343                            // This previously registered preferred activity
4344                            // component is no longer known.  Most likely an update
4345                            // to the app was installed and in the new version this
4346                            // component no longer exists.  Clean it up by removing
4347                            // it from the preferred activities list, and skip it.
4348                            Slog.w(TAG, "Removing dangling preferred activity: "
4349                                    + pa.mPref.mComponent);
4350                            pir.removeFilter(pa);
4351                            changed = true;
4352                            continue;
4353                        }
4354                        for (int j=0; j<N; j++) {
4355                            final ResolveInfo ri = query.get(j);
4356                            if (!ri.activityInfo.applicationInfo.packageName
4357                                    .equals(ai.applicationInfo.packageName)) {
4358                                continue;
4359                            }
4360                            if (!ri.activityInfo.name.equals(ai.name)) {
4361                                continue;
4362                            }
4363
4364                            if (removeMatches) {
4365                                pir.removeFilter(pa);
4366                                changed = true;
4367                                if (DEBUG_PREFERRED) {
4368                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4369                                }
4370                                break;
4371                            }
4372
4373                            // Okay we found a previously set preferred or last chosen app.
4374                            // If the result set is different from when this
4375                            // was created, we need to clear it and re-ask the
4376                            // user their preference, if we're looking for an "always" type entry.
4377                            if (always && !pa.mPref.sameSet(query)) {
4378                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4379                                        + intent + " type " + resolvedType);
4380                                if (DEBUG_PREFERRED) {
4381                                    Slog.v(TAG, "Removing preferred activity since set changed "
4382                                            + pa.mPref.mComponent);
4383                                }
4384                                pir.removeFilter(pa);
4385                                // Re-add the filter as a "last chosen" entry (!always)
4386                                PreferredActivity lastChosen = new PreferredActivity(
4387                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4388                                pir.addFilter(lastChosen);
4389                                changed = true;
4390                                return null;
4391                            }
4392
4393                            // Yay! Either the set matched or we're looking for the last chosen
4394                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4395                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4396                            return ri;
4397                        }
4398                    }
4399                } finally {
4400                    if (changed) {
4401                        if (DEBUG_PREFERRED) {
4402                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4403                        }
4404                        scheduleWritePackageRestrictionsLocked(userId);
4405                    }
4406                }
4407            }
4408        }
4409        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4410        return null;
4411    }
4412
4413    /*
4414     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4415     */
4416    @Override
4417    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4418            int targetUserId) {
4419        mContext.enforceCallingOrSelfPermission(
4420                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4421        List<CrossProfileIntentFilter> matches =
4422                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4423        if (matches != null) {
4424            int size = matches.size();
4425            for (int i = 0; i < size; i++) {
4426                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4427            }
4428        }
4429        if (hasWebURI(intent)) {
4430            // cross-profile app linking works only towards the parent.
4431            final UserInfo parent = getProfileParent(sourceUserId);
4432            synchronized(mPackages) {
4433                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4434                        intent, resolvedType, 0, sourceUserId, parent.id);
4435                return xpDomainInfo != null;
4436            }
4437        }
4438        return false;
4439    }
4440
4441    private UserInfo getProfileParent(int userId) {
4442        final long identity = Binder.clearCallingIdentity();
4443        try {
4444            return sUserManager.getProfileParent(userId);
4445        } finally {
4446            Binder.restoreCallingIdentity(identity);
4447        }
4448    }
4449
4450    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4451            String resolvedType, int userId) {
4452        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4453        if (resolver != null) {
4454            return resolver.queryIntent(intent, resolvedType, false, userId);
4455        }
4456        return null;
4457    }
4458
4459    @Override
4460    public List<ResolveInfo> queryIntentActivities(Intent intent,
4461            String resolvedType, int flags, int userId) {
4462        if (!sUserManager.exists(userId)) return Collections.emptyList();
4463        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4464        ComponentName comp = intent.getComponent();
4465        if (comp == null) {
4466            if (intent.getSelector() != null) {
4467                intent = intent.getSelector();
4468                comp = intent.getComponent();
4469            }
4470        }
4471
4472        if (comp != null) {
4473            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4474            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4475            if (ai != null) {
4476                final ResolveInfo ri = new ResolveInfo();
4477                ri.activityInfo = ai;
4478                list.add(ri);
4479            }
4480            return list;
4481        }
4482
4483        // reader
4484        synchronized (mPackages) {
4485            final String pkgName = intent.getPackage();
4486            if (pkgName == null) {
4487                List<CrossProfileIntentFilter> matchingFilters =
4488                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4489                // Check for results that need to skip the current profile.
4490                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4491                        resolvedType, flags, userId);
4492                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4493                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4494                    result.add(xpResolveInfo);
4495                    return filterIfNotPrimaryUser(result, userId);
4496                }
4497
4498                // Check for results in the current profile.
4499                List<ResolveInfo> result = mActivities.queryIntent(
4500                        intent, resolvedType, flags, userId);
4501
4502                // Check for cross profile results.
4503                xpResolveInfo = queryCrossProfileIntents(
4504                        matchingFilters, intent, resolvedType, flags, userId);
4505                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4506                    result.add(xpResolveInfo);
4507                    Collections.sort(result, mResolvePrioritySorter);
4508                }
4509                result = filterIfNotPrimaryUser(result, userId);
4510                if (hasWebURI(intent)) {
4511                    CrossProfileDomainInfo xpDomainInfo = null;
4512                    final UserInfo parent = getProfileParent(userId);
4513                    if (parent != null) {
4514                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4515                                flags, userId, parent.id);
4516                    }
4517                    if (xpDomainInfo != null) {
4518                        if (xpResolveInfo != null) {
4519                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4520                            // in the result.
4521                            result.remove(xpResolveInfo);
4522                        }
4523                        if (result.size() == 0) {
4524                            result.add(xpDomainInfo.resolveInfo);
4525                            return result;
4526                        }
4527                    } else if (result.size() <= 1) {
4528                        return result;
4529                    }
4530                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4531                            xpDomainInfo, userId);
4532                    Collections.sort(result, mResolvePrioritySorter);
4533                }
4534                return result;
4535            }
4536            final PackageParser.Package pkg = mPackages.get(pkgName);
4537            if (pkg != null) {
4538                return filterIfNotPrimaryUser(
4539                        mActivities.queryIntentForPackage(
4540                                intent, resolvedType, flags, pkg.activities, userId),
4541                        userId);
4542            }
4543            return new ArrayList<ResolveInfo>();
4544        }
4545    }
4546
4547    private static class CrossProfileDomainInfo {
4548        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4549        ResolveInfo resolveInfo;
4550        /* Best domain verification status of the activities found in the other profile */
4551        int bestDomainVerificationStatus;
4552    }
4553
4554    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4555            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4556        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4557                sourceUserId)) {
4558            return null;
4559        }
4560        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4561                resolvedType, flags, parentUserId);
4562
4563        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4564            return null;
4565        }
4566        CrossProfileDomainInfo result = null;
4567        int size = resultTargetUser.size();
4568        for (int i = 0; i < size; i++) {
4569            ResolveInfo riTargetUser = resultTargetUser.get(i);
4570            // Intent filter verification is only for filters that specify a host. So don't return
4571            // those that handle all web uris.
4572            if (riTargetUser.handleAllWebDataURI) {
4573                continue;
4574            }
4575            String packageName = riTargetUser.activityInfo.packageName;
4576            PackageSetting ps = mSettings.mPackages.get(packageName);
4577            if (ps == null) {
4578                continue;
4579            }
4580            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4581            int status = (int)(verificationState >> 32);
4582            if (result == null) {
4583                result = new CrossProfileDomainInfo();
4584                result.resolveInfo =
4585                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4586                result.bestDomainVerificationStatus = status;
4587            } else {
4588                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4589                        result.bestDomainVerificationStatus);
4590            }
4591        }
4592        // Don't consider matches with status NEVER across profiles.
4593        if (result != null && result.bestDomainVerificationStatus
4594                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4595            return null;
4596        }
4597        return result;
4598    }
4599
4600    /**
4601     * Verification statuses are ordered from the worse to the best, except for
4602     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4603     */
4604    private int bestDomainVerificationStatus(int status1, int status2) {
4605        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4606            return status2;
4607        }
4608        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4609            return status1;
4610        }
4611        return (int) MathUtils.max(status1, status2);
4612    }
4613
4614    private boolean isUserEnabled(int userId) {
4615        long callingId = Binder.clearCallingIdentity();
4616        try {
4617            UserInfo userInfo = sUserManager.getUserInfo(userId);
4618            return userInfo != null && userInfo.isEnabled();
4619        } finally {
4620            Binder.restoreCallingIdentity(callingId);
4621        }
4622    }
4623
4624    /**
4625     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4626     *
4627     * @return filtered list
4628     */
4629    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4630        if (userId == UserHandle.USER_OWNER) {
4631            return resolveInfos;
4632        }
4633        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4634            ResolveInfo info = resolveInfos.get(i);
4635            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4636                resolveInfos.remove(i);
4637            }
4638        }
4639        return resolveInfos;
4640    }
4641
4642    private static boolean hasWebURI(Intent intent) {
4643        if (intent.getData() == null) {
4644            return false;
4645        }
4646        final String scheme = intent.getScheme();
4647        if (TextUtils.isEmpty(scheme)) {
4648            return false;
4649        }
4650        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4651    }
4652
4653    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4654            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4655            int userId) {
4656        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4657
4658        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4659            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4660                    candidates.size());
4661        }
4662
4663        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4664        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4665        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4666        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4667        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4668
4669        synchronized (mPackages) {
4670            final int count = candidates.size();
4671            // First, try to use linked apps. Partition the candidates into four lists:
4672            // one for the final results, one for the "do not use ever", one for "undefined status"
4673            // and finally one for "browser app type".
4674            for (int n=0; n<count; n++) {
4675                ResolveInfo info = candidates.get(n);
4676                String packageName = info.activityInfo.packageName;
4677                PackageSetting ps = mSettings.mPackages.get(packageName);
4678                if (ps != null) {
4679                    // Add to the special match all list (Browser use case)
4680                    if (info.handleAllWebDataURI) {
4681                        matchAllList.add(info);
4682                        continue;
4683                    }
4684                    // Try to get the status from User settings first
4685                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4686                    int status = (int)(packedStatus >> 32);
4687                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4688                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4689                        if (DEBUG_DOMAIN_VERIFICATION) {
4690                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4691                                    + " : linkgen=" + linkGeneration);
4692                        }
4693                        // Use link-enabled generation as preferredOrder, i.e.
4694                        // prefer newly-enabled over earlier-enabled.
4695                        info.preferredOrder = linkGeneration;
4696                        alwaysList.add(info);
4697                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4698                        if (DEBUG_DOMAIN_VERIFICATION) {
4699                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4700                        }
4701                        neverList.add(info);
4702                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4703                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4704                        if (DEBUG_DOMAIN_VERIFICATION) {
4705                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4706                        }
4707                        undefinedList.add(info);
4708                    }
4709                }
4710            }
4711            // First try to add the "always" resolution(s) for the current user, if any
4712            if (alwaysList.size() > 0) {
4713                result.addAll(alwaysList);
4714            // if there is an "always" for the parent user, add it.
4715            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4716                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4717                result.add(xpDomainInfo.resolveInfo);
4718            } else {
4719                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4720                result.addAll(undefinedList);
4721                if (xpDomainInfo != null && (
4722                        xpDomainInfo.bestDomainVerificationStatus
4723                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4724                        || xpDomainInfo.bestDomainVerificationStatus
4725                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4726                    result.add(xpDomainInfo.resolveInfo);
4727                }
4728                // Also add Browsers (all of them or only the default one)
4729                if ((matchFlags & MATCH_ALL) != 0) {
4730                    result.addAll(matchAllList);
4731                } else {
4732                    // Browser/generic handling case.  If there's a default browser, go straight
4733                    // to that (but only if there is no other higher-priority match).
4734                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4735                    int maxMatchPrio = 0;
4736                    ResolveInfo defaultBrowserMatch = null;
4737                    final int numCandidates = matchAllList.size();
4738                    for (int n = 0; n < numCandidates; n++) {
4739                        ResolveInfo info = matchAllList.get(n);
4740                        // track the highest overall match priority...
4741                        if (info.priority > maxMatchPrio) {
4742                            maxMatchPrio = info.priority;
4743                        }
4744                        // ...and the highest-priority default browser match
4745                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4746                            if (defaultBrowserMatch == null
4747                                    || (defaultBrowserMatch.priority < info.priority)) {
4748                                if (debug) {
4749                                    Slog.v(TAG, "Considering default browser match " + info);
4750                                }
4751                                defaultBrowserMatch = info;
4752                            }
4753                        }
4754                    }
4755                    if (defaultBrowserMatch != null
4756                            && defaultBrowserMatch.priority >= maxMatchPrio
4757                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4758                    {
4759                        if (debug) {
4760                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4761                        }
4762                        result.add(defaultBrowserMatch);
4763                    } else {
4764                        result.addAll(matchAllList);
4765                    }
4766                }
4767
4768                // If there is nothing selected, add all candidates and remove the ones that the user
4769                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4770                if (result.size() == 0) {
4771                    result.addAll(candidates);
4772                    result.removeAll(neverList);
4773                }
4774            }
4775        }
4776        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4777            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4778                    result.size());
4779            for (ResolveInfo info : result) {
4780                Slog.v(TAG, "  + " + info.activityInfo);
4781            }
4782        }
4783        return result;
4784    }
4785
4786    // Returns a packed value as a long:
4787    //
4788    // high 'int'-sized word: link status: undefined/ask/never/always.
4789    // low 'int'-sized word: relative priority among 'always' results.
4790    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4791        long result = ps.getDomainVerificationStatusForUser(userId);
4792        // if none available, get the master status
4793        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4794            if (ps.getIntentFilterVerificationInfo() != null) {
4795                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4796            }
4797        }
4798        return result;
4799    }
4800
4801    private ResolveInfo querySkipCurrentProfileIntents(
4802            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4803            int flags, int sourceUserId) {
4804        if (matchingFilters != null) {
4805            int size = matchingFilters.size();
4806            for (int i = 0; i < size; i ++) {
4807                CrossProfileIntentFilter filter = matchingFilters.get(i);
4808                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4809                    // Checking if there are activities in the target user that can handle the
4810                    // intent.
4811                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4812                            flags, sourceUserId);
4813                    if (resolveInfo != null) {
4814                        return resolveInfo;
4815                    }
4816                }
4817            }
4818        }
4819        return null;
4820    }
4821
4822    // Return matching ResolveInfo if any for skip current profile intent filters.
4823    private ResolveInfo queryCrossProfileIntents(
4824            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4825            int flags, int sourceUserId) {
4826        if (matchingFilters != null) {
4827            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4828            // match the same intent. For performance reasons, it is better not to
4829            // run queryIntent twice for the same userId
4830            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4831            int size = matchingFilters.size();
4832            for (int i = 0; i < size; i++) {
4833                CrossProfileIntentFilter filter = matchingFilters.get(i);
4834                int targetUserId = filter.getTargetUserId();
4835                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4836                        && !alreadyTriedUserIds.get(targetUserId)) {
4837                    // Checking if there are activities in the target user that can handle the
4838                    // intent.
4839                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4840                            flags, sourceUserId);
4841                    if (resolveInfo != null) return resolveInfo;
4842                    alreadyTriedUserIds.put(targetUserId, true);
4843                }
4844            }
4845        }
4846        return null;
4847    }
4848
4849    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4850            String resolvedType, int flags, int sourceUserId) {
4851        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4852                resolvedType, flags, filter.getTargetUserId());
4853        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4854            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4855        }
4856        return null;
4857    }
4858
4859    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4860            int sourceUserId, int targetUserId) {
4861        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4862        String className;
4863        if (targetUserId == UserHandle.USER_OWNER) {
4864            className = FORWARD_INTENT_TO_USER_OWNER;
4865        } else {
4866            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4867        }
4868        ComponentName forwardingActivityComponentName = new ComponentName(
4869                mAndroidApplication.packageName, className);
4870        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4871                sourceUserId);
4872        if (targetUserId == UserHandle.USER_OWNER) {
4873            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4874            forwardingResolveInfo.noResourceId = true;
4875        }
4876        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4877        forwardingResolveInfo.priority = 0;
4878        forwardingResolveInfo.preferredOrder = 0;
4879        forwardingResolveInfo.match = 0;
4880        forwardingResolveInfo.isDefault = true;
4881        forwardingResolveInfo.filter = filter;
4882        forwardingResolveInfo.targetUserId = targetUserId;
4883        return forwardingResolveInfo;
4884    }
4885
4886    @Override
4887    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4888            Intent[] specifics, String[] specificTypes, Intent intent,
4889            String resolvedType, int flags, int userId) {
4890        if (!sUserManager.exists(userId)) return Collections.emptyList();
4891        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4892                false, "query intent activity options");
4893        final String resultsAction = intent.getAction();
4894
4895        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4896                | PackageManager.GET_RESOLVED_FILTER, userId);
4897
4898        if (DEBUG_INTENT_MATCHING) {
4899            Log.v(TAG, "Query " + intent + ": " + results);
4900        }
4901
4902        int specificsPos = 0;
4903        int N;
4904
4905        // todo: note that the algorithm used here is O(N^2).  This
4906        // isn't a problem in our current environment, but if we start running
4907        // into situations where we have more than 5 or 10 matches then this
4908        // should probably be changed to something smarter...
4909
4910        // First we go through and resolve each of the specific items
4911        // that were supplied, taking care of removing any corresponding
4912        // duplicate items in the generic resolve list.
4913        if (specifics != null) {
4914            for (int i=0; i<specifics.length; i++) {
4915                final Intent sintent = specifics[i];
4916                if (sintent == null) {
4917                    continue;
4918                }
4919
4920                if (DEBUG_INTENT_MATCHING) {
4921                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4922                }
4923
4924                String action = sintent.getAction();
4925                if (resultsAction != null && resultsAction.equals(action)) {
4926                    // If this action was explicitly requested, then don't
4927                    // remove things that have it.
4928                    action = null;
4929                }
4930
4931                ResolveInfo ri = null;
4932                ActivityInfo ai = null;
4933
4934                ComponentName comp = sintent.getComponent();
4935                if (comp == null) {
4936                    ri = resolveIntent(
4937                        sintent,
4938                        specificTypes != null ? specificTypes[i] : null,
4939                            flags, userId);
4940                    if (ri == null) {
4941                        continue;
4942                    }
4943                    if (ri == mResolveInfo) {
4944                        // ACK!  Must do something better with this.
4945                    }
4946                    ai = ri.activityInfo;
4947                    comp = new ComponentName(ai.applicationInfo.packageName,
4948                            ai.name);
4949                } else {
4950                    ai = getActivityInfo(comp, flags, userId);
4951                    if (ai == null) {
4952                        continue;
4953                    }
4954                }
4955
4956                // Look for any generic query activities that are duplicates
4957                // of this specific one, and remove them from the results.
4958                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4959                N = results.size();
4960                int j;
4961                for (j=specificsPos; j<N; j++) {
4962                    ResolveInfo sri = results.get(j);
4963                    if ((sri.activityInfo.name.equals(comp.getClassName())
4964                            && sri.activityInfo.applicationInfo.packageName.equals(
4965                                    comp.getPackageName()))
4966                        || (action != null && sri.filter.matchAction(action))) {
4967                        results.remove(j);
4968                        if (DEBUG_INTENT_MATCHING) Log.v(
4969                            TAG, "Removing duplicate item from " + j
4970                            + " due to specific " + specificsPos);
4971                        if (ri == null) {
4972                            ri = sri;
4973                        }
4974                        j--;
4975                        N--;
4976                    }
4977                }
4978
4979                // Add this specific item to its proper place.
4980                if (ri == null) {
4981                    ri = new ResolveInfo();
4982                    ri.activityInfo = ai;
4983                }
4984                results.add(specificsPos, ri);
4985                ri.specificIndex = i;
4986                specificsPos++;
4987            }
4988        }
4989
4990        // Now we go through the remaining generic results and remove any
4991        // duplicate actions that are found here.
4992        N = results.size();
4993        for (int i=specificsPos; i<N-1; i++) {
4994            final ResolveInfo rii = results.get(i);
4995            if (rii.filter == null) {
4996                continue;
4997            }
4998
4999            // Iterate over all of the actions of this result's intent
5000            // filter...  typically this should be just one.
5001            final Iterator<String> it = rii.filter.actionsIterator();
5002            if (it == null) {
5003                continue;
5004            }
5005            while (it.hasNext()) {
5006                final String action = it.next();
5007                if (resultsAction != null && resultsAction.equals(action)) {
5008                    // If this action was explicitly requested, then don't
5009                    // remove things that have it.
5010                    continue;
5011                }
5012                for (int j=i+1; j<N; j++) {
5013                    final ResolveInfo rij = results.get(j);
5014                    if (rij.filter != null && rij.filter.hasAction(action)) {
5015                        results.remove(j);
5016                        if (DEBUG_INTENT_MATCHING) Log.v(
5017                            TAG, "Removing duplicate item from " + j
5018                            + " due to action " + action + " at " + i);
5019                        j--;
5020                        N--;
5021                    }
5022                }
5023            }
5024
5025            // If the caller didn't request filter information, drop it now
5026            // so we don't have to marshall/unmarshall it.
5027            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5028                rii.filter = null;
5029            }
5030        }
5031
5032        // Filter out the caller activity if so requested.
5033        if (caller != null) {
5034            N = results.size();
5035            for (int i=0; i<N; i++) {
5036                ActivityInfo ainfo = results.get(i).activityInfo;
5037                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5038                        && caller.getClassName().equals(ainfo.name)) {
5039                    results.remove(i);
5040                    break;
5041                }
5042            }
5043        }
5044
5045        // If the caller didn't request filter information,
5046        // drop them now so we don't have to
5047        // marshall/unmarshall it.
5048        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5049            N = results.size();
5050            for (int i=0; i<N; i++) {
5051                results.get(i).filter = null;
5052            }
5053        }
5054
5055        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5056        return results;
5057    }
5058
5059    @Override
5060    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5061            int userId) {
5062        if (!sUserManager.exists(userId)) return Collections.emptyList();
5063        ComponentName comp = intent.getComponent();
5064        if (comp == null) {
5065            if (intent.getSelector() != null) {
5066                intent = intent.getSelector();
5067                comp = intent.getComponent();
5068            }
5069        }
5070        if (comp != null) {
5071            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5072            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5073            if (ai != null) {
5074                ResolveInfo ri = new ResolveInfo();
5075                ri.activityInfo = ai;
5076                list.add(ri);
5077            }
5078            return list;
5079        }
5080
5081        // reader
5082        synchronized (mPackages) {
5083            String pkgName = intent.getPackage();
5084            if (pkgName == null) {
5085                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5086            }
5087            final PackageParser.Package pkg = mPackages.get(pkgName);
5088            if (pkg != null) {
5089                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5090                        userId);
5091            }
5092            return null;
5093        }
5094    }
5095
5096    @Override
5097    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5098        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5099        if (!sUserManager.exists(userId)) return null;
5100        if (query != null) {
5101            if (query.size() >= 1) {
5102                // If there is more than one service with the same priority,
5103                // just arbitrarily pick the first one.
5104                return query.get(0);
5105            }
5106        }
5107        return null;
5108    }
5109
5110    @Override
5111    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5112            int userId) {
5113        if (!sUserManager.exists(userId)) return Collections.emptyList();
5114        ComponentName comp = intent.getComponent();
5115        if (comp == null) {
5116            if (intent.getSelector() != null) {
5117                intent = intent.getSelector();
5118                comp = intent.getComponent();
5119            }
5120        }
5121        if (comp != null) {
5122            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5123            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5124            if (si != null) {
5125                final ResolveInfo ri = new ResolveInfo();
5126                ri.serviceInfo = si;
5127                list.add(ri);
5128            }
5129            return list;
5130        }
5131
5132        // reader
5133        synchronized (mPackages) {
5134            String pkgName = intent.getPackage();
5135            if (pkgName == null) {
5136                return mServices.queryIntent(intent, resolvedType, flags, userId);
5137            }
5138            final PackageParser.Package pkg = mPackages.get(pkgName);
5139            if (pkg != null) {
5140                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5141                        userId);
5142            }
5143            return null;
5144        }
5145    }
5146
5147    @Override
5148    public List<ResolveInfo> queryIntentContentProviders(
5149            Intent intent, String resolvedType, int flags, int userId) {
5150        if (!sUserManager.exists(userId)) return Collections.emptyList();
5151        ComponentName comp = intent.getComponent();
5152        if (comp == null) {
5153            if (intent.getSelector() != null) {
5154                intent = intent.getSelector();
5155                comp = intent.getComponent();
5156            }
5157        }
5158        if (comp != null) {
5159            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5160            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5161            if (pi != null) {
5162                final ResolveInfo ri = new ResolveInfo();
5163                ri.providerInfo = pi;
5164                list.add(ri);
5165            }
5166            return list;
5167        }
5168
5169        // reader
5170        synchronized (mPackages) {
5171            String pkgName = intent.getPackage();
5172            if (pkgName == null) {
5173                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5174            }
5175            final PackageParser.Package pkg = mPackages.get(pkgName);
5176            if (pkg != null) {
5177                return mProviders.queryIntentForPackage(
5178                        intent, resolvedType, flags, pkg.providers, userId);
5179            }
5180            return null;
5181        }
5182    }
5183
5184    @Override
5185    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5186        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5187
5188        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5189
5190        // writer
5191        synchronized (mPackages) {
5192            ArrayList<PackageInfo> list;
5193            if (listUninstalled) {
5194                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5195                for (PackageSetting ps : mSettings.mPackages.values()) {
5196                    PackageInfo pi;
5197                    if (ps.pkg != null) {
5198                        pi = generatePackageInfo(ps.pkg, flags, userId);
5199                    } else {
5200                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5201                    }
5202                    if (pi != null) {
5203                        list.add(pi);
5204                    }
5205                }
5206            } else {
5207                list = new ArrayList<PackageInfo>(mPackages.size());
5208                for (PackageParser.Package p : mPackages.values()) {
5209                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5210                    if (pi != null) {
5211                        list.add(pi);
5212                    }
5213                }
5214            }
5215
5216            return new ParceledListSlice<PackageInfo>(list);
5217        }
5218    }
5219
5220    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5221            String[] permissions, boolean[] tmp, int flags, int userId) {
5222        int numMatch = 0;
5223        final PermissionsState permissionsState = ps.getPermissionsState();
5224        for (int i=0; i<permissions.length; i++) {
5225            final String permission = permissions[i];
5226            if (permissionsState.hasPermission(permission, userId)) {
5227                tmp[i] = true;
5228                numMatch++;
5229            } else {
5230                tmp[i] = false;
5231            }
5232        }
5233        if (numMatch == 0) {
5234            return;
5235        }
5236        PackageInfo pi;
5237        if (ps.pkg != null) {
5238            pi = generatePackageInfo(ps.pkg, flags, userId);
5239        } else {
5240            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5241        }
5242        // The above might return null in cases of uninstalled apps or install-state
5243        // skew across users/profiles.
5244        if (pi != null) {
5245            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5246                if (numMatch == permissions.length) {
5247                    pi.requestedPermissions = permissions;
5248                } else {
5249                    pi.requestedPermissions = new String[numMatch];
5250                    numMatch = 0;
5251                    for (int i=0; i<permissions.length; i++) {
5252                        if (tmp[i]) {
5253                            pi.requestedPermissions[numMatch] = permissions[i];
5254                            numMatch++;
5255                        }
5256                    }
5257                }
5258            }
5259            list.add(pi);
5260        }
5261    }
5262
5263    @Override
5264    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5265            String[] permissions, int flags, int userId) {
5266        if (!sUserManager.exists(userId)) return null;
5267        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5268
5269        // writer
5270        synchronized (mPackages) {
5271            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5272            boolean[] tmpBools = new boolean[permissions.length];
5273            if (listUninstalled) {
5274                for (PackageSetting ps : mSettings.mPackages.values()) {
5275                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5276                }
5277            } else {
5278                for (PackageParser.Package pkg : mPackages.values()) {
5279                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5280                    if (ps != null) {
5281                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5282                                userId);
5283                    }
5284                }
5285            }
5286
5287            return new ParceledListSlice<PackageInfo>(list);
5288        }
5289    }
5290
5291    @Override
5292    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5293        if (!sUserManager.exists(userId)) return null;
5294        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5295
5296        // writer
5297        synchronized (mPackages) {
5298            ArrayList<ApplicationInfo> list;
5299            if (listUninstalled) {
5300                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5301                for (PackageSetting ps : mSettings.mPackages.values()) {
5302                    ApplicationInfo ai;
5303                    if (ps.pkg != null) {
5304                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5305                                ps.readUserState(userId), userId);
5306                    } else {
5307                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5308                    }
5309                    if (ai != null) {
5310                        list.add(ai);
5311                    }
5312                }
5313            } else {
5314                list = new ArrayList<ApplicationInfo>(mPackages.size());
5315                for (PackageParser.Package p : mPackages.values()) {
5316                    if (p.mExtras != null) {
5317                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5318                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5319                        if (ai != null) {
5320                            list.add(ai);
5321                        }
5322                    }
5323                }
5324            }
5325
5326            return new ParceledListSlice<ApplicationInfo>(list);
5327        }
5328    }
5329
5330    public List<ApplicationInfo> getPersistentApplications(int flags) {
5331        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5332
5333        // reader
5334        synchronized (mPackages) {
5335            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5336            final int userId = UserHandle.getCallingUserId();
5337            while (i.hasNext()) {
5338                final PackageParser.Package p = i.next();
5339                if (p.applicationInfo != null
5340                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5341                        && (!mSafeMode || isSystemApp(p))) {
5342                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5343                    if (ps != null) {
5344                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5345                                ps.readUserState(userId), userId);
5346                        if (ai != null) {
5347                            finalList.add(ai);
5348                        }
5349                    }
5350                }
5351            }
5352        }
5353
5354        return finalList;
5355    }
5356
5357    @Override
5358    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5359        if (!sUserManager.exists(userId)) return null;
5360        // reader
5361        synchronized (mPackages) {
5362            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5363            PackageSetting ps = provider != null
5364                    ? mSettings.mPackages.get(provider.owner.packageName)
5365                    : null;
5366            return ps != null
5367                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5368                    && (!mSafeMode || (provider.info.applicationInfo.flags
5369                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5370                    ? PackageParser.generateProviderInfo(provider, flags,
5371                            ps.readUserState(userId), userId)
5372                    : null;
5373        }
5374    }
5375
5376    /**
5377     * @deprecated
5378     */
5379    @Deprecated
5380    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5381        // reader
5382        synchronized (mPackages) {
5383            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5384                    .entrySet().iterator();
5385            final int userId = UserHandle.getCallingUserId();
5386            while (i.hasNext()) {
5387                Map.Entry<String, PackageParser.Provider> entry = i.next();
5388                PackageParser.Provider p = entry.getValue();
5389                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5390
5391                if (ps != null && p.syncable
5392                        && (!mSafeMode || (p.info.applicationInfo.flags
5393                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5394                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5395                            ps.readUserState(userId), userId);
5396                    if (info != null) {
5397                        outNames.add(entry.getKey());
5398                        outInfo.add(info);
5399                    }
5400                }
5401            }
5402        }
5403    }
5404
5405    @Override
5406    public List<ProviderInfo> queryContentProviders(String processName,
5407            int uid, int flags) {
5408        ArrayList<ProviderInfo> finalList = null;
5409        // reader
5410        synchronized (mPackages) {
5411            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5412            final int userId = processName != null ?
5413                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5414            while (i.hasNext()) {
5415                final PackageParser.Provider p = i.next();
5416                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5417                if (ps != null && p.info.authority != null
5418                        && (processName == null
5419                                || (p.info.processName.equals(processName)
5420                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5421                        && mSettings.isEnabledLPr(p.info, flags, userId)
5422                        && (!mSafeMode
5423                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5424                    if (finalList == null) {
5425                        finalList = new ArrayList<ProviderInfo>(3);
5426                    }
5427                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5428                            ps.readUserState(userId), userId);
5429                    if (info != null) {
5430                        finalList.add(info);
5431                    }
5432                }
5433            }
5434        }
5435
5436        if (finalList != null) {
5437            Collections.sort(finalList, mProviderInitOrderSorter);
5438        }
5439
5440        return finalList;
5441    }
5442
5443    @Override
5444    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5445            int flags) {
5446        // reader
5447        synchronized (mPackages) {
5448            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5449            return PackageParser.generateInstrumentationInfo(i, flags);
5450        }
5451    }
5452
5453    @Override
5454    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5455            int flags) {
5456        ArrayList<InstrumentationInfo> finalList =
5457            new ArrayList<InstrumentationInfo>();
5458
5459        // reader
5460        synchronized (mPackages) {
5461            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5462            while (i.hasNext()) {
5463                final PackageParser.Instrumentation p = i.next();
5464                if (targetPackage == null
5465                        || targetPackage.equals(p.info.targetPackage)) {
5466                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5467                            flags);
5468                    if (ii != null) {
5469                        finalList.add(ii);
5470                    }
5471                }
5472            }
5473        }
5474
5475        return finalList;
5476    }
5477
5478    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5479        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5480        if (overlays == null) {
5481            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5482            return;
5483        }
5484        for (PackageParser.Package opkg : overlays.values()) {
5485            // Not much to do if idmap fails: we already logged the error
5486            // and we certainly don't want to abort installation of pkg simply
5487            // because an overlay didn't fit properly. For these reasons,
5488            // ignore the return value of createIdmapForPackagePairLI.
5489            createIdmapForPackagePairLI(pkg, opkg);
5490        }
5491    }
5492
5493    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5494            PackageParser.Package opkg) {
5495        if (!opkg.mTrustedOverlay) {
5496            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5497                    opkg.baseCodePath + ": overlay not trusted");
5498            return false;
5499        }
5500        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5501        if (overlaySet == null) {
5502            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5503                    opkg.baseCodePath + " but target package has no known overlays");
5504            return false;
5505        }
5506        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5507        // TODO: generate idmap for split APKs
5508        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5509            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5510                    + opkg.baseCodePath);
5511            return false;
5512        }
5513        PackageParser.Package[] overlayArray =
5514            overlaySet.values().toArray(new PackageParser.Package[0]);
5515        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5516            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5517                return p1.mOverlayPriority - p2.mOverlayPriority;
5518            }
5519        };
5520        Arrays.sort(overlayArray, cmp);
5521
5522        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5523        int i = 0;
5524        for (PackageParser.Package p : overlayArray) {
5525            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5526        }
5527        return true;
5528    }
5529
5530    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5531        final File[] files = dir.listFiles();
5532        if (ArrayUtils.isEmpty(files)) {
5533            Log.d(TAG, "No files in app dir " + dir);
5534            return;
5535        }
5536
5537        if (DEBUG_PACKAGE_SCANNING) {
5538            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5539                    + " flags=0x" + Integer.toHexString(parseFlags));
5540        }
5541
5542        for (File file : files) {
5543            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5544                    && !PackageInstallerService.isStageName(file.getName());
5545            if (!isPackage) {
5546                // Ignore entries which are not packages
5547                continue;
5548            }
5549            try {
5550                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5551                        scanFlags, currentTime, null);
5552            } catch (PackageManagerException e) {
5553                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5554
5555                // Delete invalid userdata apps
5556                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5557                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5558                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5559                    if (file.isDirectory()) {
5560                        mInstaller.rmPackageDir(file.getAbsolutePath());
5561                    } else {
5562                        file.delete();
5563                    }
5564                }
5565            }
5566        }
5567    }
5568
5569    private static File getSettingsProblemFile() {
5570        File dataDir = Environment.getDataDirectory();
5571        File systemDir = new File(dataDir, "system");
5572        File fname = new File(systemDir, "uiderrors.txt");
5573        return fname;
5574    }
5575
5576    static void reportSettingsProblem(int priority, String msg) {
5577        logCriticalInfo(priority, msg);
5578    }
5579
5580    static void logCriticalInfo(int priority, String msg) {
5581        Slog.println(priority, TAG, msg);
5582        EventLogTags.writePmCriticalInfo(msg);
5583        try {
5584            File fname = getSettingsProblemFile();
5585            FileOutputStream out = new FileOutputStream(fname, true);
5586            PrintWriter pw = new FastPrintWriter(out);
5587            SimpleDateFormat formatter = new SimpleDateFormat();
5588            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5589            pw.println(dateString + ": " + msg);
5590            pw.close();
5591            FileUtils.setPermissions(
5592                    fname.toString(),
5593                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5594                    -1, -1);
5595        } catch (java.io.IOException e) {
5596        }
5597    }
5598
5599    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5600            PackageParser.Package pkg, File srcFile, int parseFlags)
5601            throws PackageManagerException {
5602        if (ps != null
5603                && ps.codePath.equals(srcFile)
5604                && ps.timeStamp == srcFile.lastModified()
5605                && !isCompatSignatureUpdateNeeded(pkg)
5606                && !isRecoverSignatureUpdateNeeded(pkg)) {
5607            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5608            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5609            ArraySet<PublicKey> signingKs;
5610            synchronized (mPackages) {
5611                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5612            }
5613            if (ps.signatures.mSignatures != null
5614                    && ps.signatures.mSignatures.length != 0
5615                    && signingKs != null) {
5616                // Optimization: reuse the existing cached certificates
5617                // if the package appears to be unchanged.
5618                pkg.mSignatures = ps.signatures.mSignatures;
5619                pkg.mSigningKeys = signingKs;
5620                return;
5621            }
5622
5623            Slog.w(TAG, "PackageSetting for " + ps.name
5624                    + " is missing signatures.  Collecting certs again to recover them.");
5625        } else {
5626            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5627        }
5628
5629        try {
5630            pp.collectCertificates(pkg, parseFlags);
5631            pp.collectManifestDigest(pkg);
5632        } catch (PackageParserException e) {
5633            throw PackageManagerException.from(e);
5634        }
5635    }
5636
5637    /*
5638     *  Scan a package and return the newly parsed package.
5639     *  Returns null in case of errors and the error code is stored in mLastScanError
5640     */
5641    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5642            long currentTime, UserHandle user) throws PackageManagerException {
5643        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5644        parseFlags |= mDefParseFlags;
5645        PackageParser pp = new PackageParser();
5646        pp.setSeparateProcesses(mSeparateProcesses);
5647        pp.setOnlyCoreApps(mOnlyCore);
5648        pp.setDisplayMetrics(mMetrics);
5649
5650        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5651            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5652        }
5653
5654        final PackageParser.Package pkg;
5655        try {
5656            pkg = pp.parsePackage(scanFile, parseFlags);
5657        } catch (PackageParserException e) {
5658            throw PackageManagerException.from(e);
5659        }
5660
5661        PackageSetting ps = null;
5662        PackageSetting updatedPkg;
5663        // reader
5664        synchronized (mPackages) {
5665            // Look to see if we already know about this package.
5666            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5667            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5668                // This package has been renamed to its original name.  Let's
5669                // use that.
5670                ps = mSettings.peekPackageLPr(oldName);
5671            }
5672            // If there was no original package, see one for the real package name.
5673            if (ps == null) {
5674                ps = mSettings.peekPackageLPr(pkg.packageName);
5675            }
5676            // Check to see if this package could be hiding/updating a system
5677            // package.  Must look for it either under the original or real
5678            // package name depending on our state.
5679            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5680            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5681        }
5682        boolean updatedPkgBetter = false;
5683        // First check if this is a system package that may involve an update
5684        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5685            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5686            // it needs to drop FLAG_PRIVILEGED.
5687            if (locationIsPrivileged(scanFile)) {
5688                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5689            } else {
5690                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5691            }
5692
5693            if (ps != null && !ps.codePath.equals(scanFile)) {
5694                // The path has changed from what was last scanned...  check the
5695                // version of the new path against what we have stored to determine
5696                // what to do.
5697                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5698                if (pkg.mVersionCode <= ps.versionCode) {
5699                    // The system package has been updated and the code path does not match
5700                    // Ignore entry. Skip it.
5701                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5702                            + " ignored: updated version " + ps.versionCode
5703                            + " better than this " + pkg.mVersionCode);
5704                    if (!updatedPkg.codePath.equals(scanFile)) {
5705                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5706                                + ps.name + " changing from " + updatedPkg.codePathString
5707                                + " to " + scanFile);
5708                        updatedPkg.codePath = scanFile;
5709                        updatedPkg.codePathString = scanFile.toString();
5710                        updatedPkg.resourcePath = scanFile;
5711                        updatedPkg.resourcePathString = scanFile.toString();
5712                    }
5713                    updatedPkg.pkg = pkg;
5714                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5715                            "Package " + ps.name + " at " + scanFile
5716                                    + " ignored: updated version " + ps.versionCode
5717                                    + " better than this " + pkg.mVersionCode);
5718                } else {
5719                    // The current app on the system partition is better than
5720                    // what we have updated to on the data partition; switch
5721                    // back to the system partition version.
5722                    // At this point, its safely assumed that package installation for
5723                    // apps in system partition will go through. If not there won't be a working
5724                    // version of the app
5725                    // writer
5726                    synchronized (mPackages) {
5727                        // Just remove the loaded entries from package lists.
5728                        mPackages.remove(ps.name);
5729                    }
5730
5731                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5732                            + " reverting from " + ps.codePathString
5733                            + ": new version " + pkg.mVersionCode
5734                            + " better than installed " + ps.versionCode);
5735
5736                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5737                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5738                    synchronized (mInstallLock) {
5739                        args.cleanUpResourcesLI();
5740                    }
5741                    synchronized (mPackages) {
5742                        mSettings.enableSystemPackageLPw(ps.name);
5743                    }
5744                    updatedPkgBetter = true;
5745                }
5746            }
5747        }
5748
5749        if (updatedPkg != null) {
5750            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5751            // initially
5752            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5753
5754            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5755            // flag set initially
5756            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5757                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5758            }
5759        }
5760
5761        // Verify certificates against what was last scanned
5762        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5763
5764        /*
5765         * A new system app appeared, but we already had a non-system one of the
5766         * same name installed earlier.
5767         */
5768        boolean shouldHideSystemApp = false;
5769        if (updatedPkg == null && ps != null
5770                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5771            /*
5772             * Check to make sure the signatures match first. If they don't,
5773             * wipe the installed application and its data.
5774             */
5775            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5776                    != PackageManager.SIGNATURE_MATCH) {
5777                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5778                        + " signatures don't match existing userdata copy; removing");
5779                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5780                ps = null;
5781            } else {
5782                /*
5783                 * If the newly-added system app is an older version than the
5784                 * already installed version, hide it. It will be scanned later
5785                 * and re-added like an update.
5786                 */
5787                if (pkg.mVersionCode <= ps.versionCode) {
5788                    shouldHideSystemApp = true;
5789                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5790                            + " but new version " + pkg.mVersionCode + " better than installed "
5791                            + ps.versionCode + "; hiding system");
5792                } else {
5793                    /*
5794                     * The newly found system app is a newer version that the
5795                     * one previously installed. Simply remove the
5796                     * already-installed application and replace it with our own
5797                     * while keeping the application data.
5798                     */
5799                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5800                            + " reverting from " + ps.codePathString + ": new version "
5801                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5802                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5803                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5804                    synchronized (mInstallLock) {
5805                        args.cleanUpResourcesLI();
5806                    }
5807                }
5808            }
5809        }
5810
5811        // The apk is forward locked (not public) if its code and resources
5812        // are kept in different files. (except for app in either system or
5813        // vendor path).
5814        // TODO grab this value from PackageSettings
5815        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5816            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5817                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5818            }
5819        }
5820
5821        // TODO: extend to support forward-locked splits
5822        String resourcePath = null;
5823        String baseResourcePath = null;
5824        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5825            if (ps != null && ps.resourcePathString != null) {
5826                resourcePath = ps.resourcePathString;
5827                baseResourcePath = ps.resourcePathString;
5828            } else {
5829                // Should not happen at all. Just log an error.
5830                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5831            }
5832        } else {
5833            resourcePath = pkg.codePath;
5834            baseResourcePath = pkg.baseCodePath;
5835        }
5836
5837        // Set application objects path explicitly.
5838        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5839        pkg.applicationInfo.setCodePath(pkg.codePath);
5840        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5841        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5842        pkg.applicationInfo.setResourcePath(resourcePath);
5843        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5844        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5845
5846        // Note that we invoke the following method only if we are about to unpack an application
5847        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5848                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5849
5850        /*
5851         * If the system app should be overridden by a previously installed
5852         * data, hide the system app now and let the /data/app scan pick it up
5853         * again.
5854         */
5855        if (shouldHideSystemApp) {
5856            synchronized (mPackages) {
5857                /*
5858                 * We have to grant systems permissions before we hide, because
5859                 * grantPermissions will assume the package update is trying to
5860                 * expand its permissions.
5861                 */
5862                grantPermissionsLPw(pkg, true, pkg.packageName);
5863                mSettings.disableSystemPackageLPw(pkg.packageName);
5864            }
5865        }
5866
5867        return scannedPkg;
5868    }
5869
5870    private static String fixProcessName(String defProcessName,
5871            String processName, int uid) {
5872        if (processName == null) {
5873            return defProcessName;
5874        }
5875        return processName;
5876    }
5877
5878    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5879            throws PackageManagerException {
5880        if (pkgSetting.signatures.mSignatures != null) {
5881            // Already existing package. Make sure signatures match
5882            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5883                    == PackageManager.SIGNATURE_MATCH;
5884            if (!match) {
5885                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5886                        == PackageManager.SIGNATURE_MATCH;
5887            }
5888            if (!match) {
5889                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5890                        == PackageManager.SIGNATURE_MATCH;
5891            }
5892            if (!match) {
5893                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5894                        + pkg.packageName + " signatures do not match the "
5895                        + "previously installed version; ignoring!");
5896            }
5897        }
5898
5899        // Check for shared user signatures
5900        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5901            // Already existing package. Make sure signatures match
5902            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5903                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5904            if (!match) {
5905                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5906                        == PackageManager.SIGNATURE_MATCH;
5907            }
5908            if (!match) {
5909                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5910                        == PackageManager.SIGNATURE_MATCH;
5911            }
5912            if (!match) {
5913                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5914                        "Package " + pkg.packageName
5915                        + " has no signatures that match those in shared user "
5916                        + pkgSetting.sharedUser.name + "; ignoring!");
5917            }
5918        }
5919    }
5920
5921    /**
5922     * Enforces that only the system UID or root's UID can call a method exposed
5923     * via Binder.
5924     *
5925     * @param message used as message if SecurityException is thrown
5926     * @throws SecurityException if the caller is not system or root
5927     */
5928    private static final void enforceSystemOrRoot(String message) {
5929        final int uid = Binder.getCallingUid();
5930        if (uid != Process.SYSTEM_UID && uid != 0) {
5931            throw new SecurityException(message);
5932        }
5933    }
5934
5935    @Override
5936    public void performBootDexOpt() {
5937        enforceSystemOrRoot("Only the system can request dexopt be performed");
5938
5939        // Before everything else, see whether we need to fstrim.
5940        try {
5941            IMountService ms = PackageHelper.getMountService();
5942            if (ms != null) {
5943                final boolean isUpgrade = isUpgrade();
5944                boolean doTrim = isUpgrade;
5945                if (doTrim) {
5946                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5947                } else {
5948                    final long interval = android.provider.Settings.Global.getLong(
5949                            mContext.getContentResolver(),
5950                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5951                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5952                    if (interval > 0) {
5953                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5954                        if (timeSinceLast > interval) {
5955                            doTrim = true;
5956                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5957                                    + "; running immediately");
5958                        }
5959                    }
5960                }
5961                if (doTrim) {
5962                    if (!isFirstBoot()) {
5963                        try {
5964                            ActivityManagerNative.getDefault().showBootMessage(
5965                                    mContext.getResources().getString(
5966                                            R.string.android_upgrading_fstrim), true);
5967                        } catch (RemoteException e) {
5968                        }
5969                    }
5970                    ms.runMaintenance();
5971                }
5972            } else {
5973                Slog.e(TAG, "Mount service unavailable!");
5974            }
5975        } catch (RemoteException e) {
5976            // Can't happen; MountService is local
5977        }
5978
5979        final ArraySet<PackageParser.Package> pkgs;
5980        synchronized (mPackages) {
5981            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5982        }
5983
5984        if (pkgs != null) {
5985            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5986            // in case the device runs out of space.
5987            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5988            // Give priority to core apps.
5989            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5990                PackageParser.Package pkg = it.next();
5991                if (pkg.coreApp) {
5992                    if (DEBUG_DEXOPT) {
5993                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5994                    }
5995                    sortedPkgs.add(pkg);
5996                    it.remove();
5997                }
5998            }
5999            // Give priority to system apps that listen for pre boot complete.
6000            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6001            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6002            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6003                PackageParser.Package pkg = it.next();
6004                if (pkgNames.contains(pkg.packageName)) {
6005                    if (DEBUG_DEXOPT) {
6006                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6007                    }
6008                    sortedPkgs.add(pkg);
6009                    it.remove();
6010                }
6011            }
6012            // Give priority to system apps.
6013            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6014                PackageParser.Package pkg = it.next();
6015                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6016                    if (DEBUG_DEXOPT) {
6017                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6018                    }
6019                    sortedPkgs.add(pkg);
6020                    it.remove();
6021                }
6022            }
6023            // Give priority to updated system apps.
6024            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6025                PackageParser.Package pkg = it.next();
6026                if (pkg.isUpdatedSystemApp()) {
6027                    if (DEBUG_DEXOPT) {
6028                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6029                    }
6030                    sortedPkgs.add(pkg);
6031                    it.remove();
6032                }
6033            }
6034            // Give priority to apps that listen for boot complete.
6035            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6036            pkgNames = getPackageNamesForIntent(intent);
6037            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6038                PackageParser.Package pkg = it.next();
6039                if (pkgNames.contains(pkg.packageName)) {
6040                    if (DEBUG_DEXOPT) {
6041                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6042                    }
6043                    sortedPkgs.add(pkg);
6044                    it.remove();
6045                }
6046            }
6047            // Filter out packages that aren't recently used.
6048            filterRecentlyUsedApps(pkgs);
6049            // Add all remaining apps.
6050            for (PackageParser.Package pkg : pkgs) {
6051                if (DEBUG_DEXOPT) {
6052                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6053                }
6054                sortedPkgs.add(pkg);
6055            }
6056
6057            // If we want to be lazy, filter everything that wasn't recently used.
6058            if (mLazyDexOpt) {
6059                filterRecentlyUsedApps(sortedPkgs);
6060            }
6061
6062            int i = 0;
6063            int total = sortedPkgs.size();
6064            File dataDir = Environment.getDataDirectory();
6065            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6066            if (lowThreshold == 0) {
6067                throw new IllegalStateException("Invalid low memory threshold");
6068            }
6069            for (PackageParser.Package pkg : sortedPkgs) {
6070                long usableSpace = dataDir.getUsableSpace();
6071                if (usableSpace < lowThreshold) {
6072                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6073                    break;
6074                }
6075                performBootDexOpt(pkg, ++i, total);
6076            }
6077        }
6078    }
6079
6080    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6081        // Filter out packages that aren't recently used.
6082        //
6083        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6084        // should do a full dexopt.
6085        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6086            int total = pkgs.size();
6087            int skipped = 0;
6088            long now = System.currentTimeMillis();
6089            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6090                PackageParser.Package pkg = i.next();
6091                long then = pkg.mLastPackageUsageTimeInMills;
6092                if (then + mDexOptLRUThresholdInMills < now) {
6093                    if (DEBUG_DEXOPT) {
6094                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6095                              ((then == 0) ? "never" : new Date(then)));
6096                    }
6097                    i.remove();
6098                    skipped++;
6099                }
6100            }
6101            if (DEBUG_DEXOPT) {
6102                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6103            }
6104        }
6105    }
6106
6107    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6108        List<ResolveInfo> ris = null;
6109        try {
6110            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6111                    intent, null, 0, UserHandle.USER_OWNER);
6112        } catch (RemoteException e) {
6113        }
6114        ArraySet<String> pkgNames = new ArraySet<String>();
6115        if (ris != null) {
6116            for (ResolveInfo ri : ris) {
6117                pkgNames.add(ri.activityInfo.packageName);
6118            }
6119        }
6120        return pkgNames;
6121    }
6122
6123    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6124        if (DEBUG_DEXOPT) {
6125            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6126        }
6127        if (!isFirstBoot()) {
6128            try {
6129                ActivityManagerNative.getDefault().showBootMessage(
6130                        mContext.getResources().getString(R.string.android_upgrading_apk,
6131                                curr, total), true);
6132            } catch (RemoteException e) {
6133            }
6134        }
6135        PackageParser.Package p = pkg;
6136        synchronized (mInstallLock) {
6137            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6138                    false /* force dex */, false /* defer */, true /* include dependencies */);
6139        }
6140    }
6141
6142    @Override
6143    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6144        return performDexOpt(packageName, instructionSet, false);
6145    }
6146
6147    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6148        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6149        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6150        if (!dexopt && !updateUsage) {
6151            // We aren't going to dexopt or update usage, so bail early.
6152            return false;
6153        }
6154        PackageParser.Package p;
6155        final String targetInstructionSet;
6156        synchronized (mPackages) {
6157            p = mPackages.get(packageName);
6158            if (p == null) {
6159                return false;
6160            }
6161            if (updateUsage) {
6162                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6163            }
6164            mPackageUsage.write(false);
6165            if (!dexopt) {
6166                // We aren't going to dexopt, so bail early.
6167                return false;
6168            }
6169
6170            targetInstructionSet = instructionSet != null ? instructionSet :
6171                    getPrimaryInstructionSet(p.applicationInfo);
6172            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6173                return false;
6174            }
6175        }
6176        long callingId = Binder.clearCallingIdentity();
6177        try {
6178            synchronized (mInstallLock) {
6179                final String[] instructionSets = new String[] { targetInstructionSet };
6180                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6181                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6182                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6183            }
6184        } finally {
6185            Binder.restoreCallingIdentity(callingId);
6186        }
6187    }
6188
6189    public ArraySet<String> getPackagesThatNeedDexOpt() {
6190        ArraySet<String> pkgs = null;
6191        synchronized (mPackages) {
6192            for (PackageParser.Package p : mPackages.values()) {
6193                if (DEBUG_DEXOPT) {
6194                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6195                }
6196                if (!p.mDexOptPerformed.isEmpty()) {
6197                    continue;
6198                }
6199                if (pkgs == null) {
6200                    pkgs = new ArraySet<String>();
6201                }
6202                pkgs.add(p.packageName);
6203            }
6204        }
6205        return pkgs;
6206    }
6207
6208    public void shutdown() {
6209        mPackageUsage.write(true);
6210    }
6211
6212    @Override
6213    public void forceDexOpt(String packageName) {
6214        enforceSystemOrRoot("forceDexOpt");
6215
6216        PackageParser.Package pkg;
6217        synchronized (mPackages) {
6218            pkg = mPackages.get(packageName);
6219            if (pkg == null) {
6220                throw new IllegalArgumentException("Missing package: " + packageName);
6221            }
6222        }
6223
6224        synchronized (mInstallLock) {
6225            final String[] instructionSets = new String[] {
6226                    getPrimaryInstructionSet(pkg.applicationInfo) };
6227            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6228                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6229            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6230                throw new IllegalStateException("Failed to dexopt: " + res);
6231            }
6232        }
6233    }
6234
6235    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6236        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6237            Slog.w(TAG, "Unable to update from " + oldPkg.name
6238                    + " to " + newPkg.packageName
6239                    + ": old package not in system partition");
6240            return false;
6241        } else if (mPackages.get(oldPkg.name) != null) {
6242            Slog.w(TAG, "Unable to update from " + oldPkg.name
6243                    + " to " + newPkg.packageName
6244                    + ": old package still exists");
6245            return false;
6246        }
6247        return true;
6248    }
6249
6250    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6251        int[] users = sUserManager.getUserIds();
6252        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6253        if (res < 0) {
6254            return res;
6255        }
6256        for (int user : users) {
6257            if (user != 0) {
6258                res = mInstaller.createUserData(volumeUuid, packageName,
6259                        UserHandle.getUid(user, uid), user, seinfo);
6260                if (res < 0) {
6261                    return res;
6262                }
6263            }
6264        }
6265        return res;
6266    }
6267
6268    private int removeDataDirsLI(String volumeUuid, String packageName) {
6269        int[] users = sUserManager.getUserIds();
6270        int res = 0;
6271        for (int user : users) {
6272            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6273            if (resInner < 0) {
6274                res = resInner;
6275            }
6276        }
6277
6278        return res;
6279    }
6280
6281    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6282        int[] users = sUserManager.getUserIds();
6283        int res = 0;
6284        for (int user : users) {
6285            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6286            if (resInner < 0) {
6287                res = resInner;
6288            }
6289        }
6290        return res;
6291    }
6292
6293    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6294            PackageParser.Package changingLib) {
6295        if (file.path != null) {
6296            usesLibraryFiles.add(file.path);
6297            return;
6298        }
6299        PackageParser.Package p = mPackages.get(file.apk);
6300        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6301            // If we are doing this while in the middle of updating a library apk,
6302            // then we need to make sure to use that new apk for determining the
6303            // dependencies here.  (We haven't yet finished committing the new apk
6304            // to the package manager state.)
6305            if (p == null || p.packageName.equals(changingLib.packageName)) {
6306                p = changingLib;
6307            }
6308        }
6309        if (p != null) {
6310            usesLibraryFiles.addAll(p.getAllCodePaths());
6311        }
6312    }
6313
6314    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6315            PackageParser.Package changingLib) throws PackageManagerException {
6316        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6317            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6318            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6319            for (int i=0; i<N; i++) {
6320                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6321                if (file == null) {
6322                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6323                            "Package " + pkg.packageName + " requires unavailable shared library "
6324                            + pkg.usesLibraries.get(i) + "; failing!");
6325                }
6326                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6327            }
6328            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6329            for (int i=0; i<N; i++) {
6330                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6331                if (file == null) {
6332                    Slog.w(TAG, "Package " + pkg.packageName
6333                            + " desires unavailable shared library "
6334                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6335                } else {
6336                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6337                }
6338            }
6339            N = usesLibraryFiles.size();
6340            if (N > 0) {
6341                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6342            } else {
6343                pkg.usesLibraryFiles = null;
6344            }
6345        }
6346    }
6347
6348    private static boolean hasString(List<String> list, List<String> which) {
6349        if (list == null) {
6350            return false;
6351        }
6352        for (int i=list.size()-1; i>=0; i--) {
6353            for (int j=which.size()-1; j>=0; j--) {
6354                if (which.get(j).equals(list.get(i))) {
6355                    return true;
6356                }
6357            }
6358        }
6359        return false;
6360    }
6361
6362    private void updateAllSharedLibrariesLPw() {
6363        for (PackageParser.Package pkg : mPackages.values()) {
6364            try {
6365                updateSharedLibrariesLPw(pkg, null);
6366            } catch (PackageManagerException e) {
6367                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6368            }
6369        }
6370    }
6371
6372    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6373            PackageParser.Package changingPkg) {
6374        ArrayList<PackageParser.Package> res = null;
6375        for (PackageParser.Package pkg : mPackages.values()) {
6376            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6377                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6378                if (res == null) {
6379                    res = new ArrayList<PackageParser.Package>();
6380                }
6381                res.add(pkg);
6382                try {
6383                    updateSharedLibrariesLPw(pkg, changingPkg);
6384                } catch (PackageManagerException e) {
6385                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6386                }
6387            }
6388        }
6389        return res;
6390    }
6391
6392    /**
6393     * Derive the value of the {@code cpuAbiOverride} based on the provided
6394     * value and an optional stored value from the package settings.
6395     */
6396    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6397        String cpuAbiOverride = null;
6398
6399        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6400            cpuAbiOverride = null;
6401        } else if (abiOverride != null) {
6402            cpuAbiOverride = abiOverride;
6403        } else if (settings != null) {
6404            cpuAbiOverride = settings.cpuAbiOverrideString;
6405        }
6406
6407        return cpuAbiOverride;
6408    }
6409
6410    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6411            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6412        boolean success = false;
6413        try {
6414            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6415                    currentTime, user);
6416            success = true;
6417            return res;
6418        } finally {
6419            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6420                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6421            }
6422        }
6423    }
6424
6425    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6426            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6427        final File scanFile = new File(pkg.codePath);
6428        if (pkg.applicationInfo.getCodePath() == null ||
6429                pkg.applicationInfo.getResourcePath() == null) {
6430            // Bail out. The resource and code paths haven't been set.
6431            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6432                    "Code and resource paths haven't been set correctly");
6433        }
6434
6435        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6436            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6437        } else {
6438            // Only allow system apps to be flagged as core apps.
6439            pkg.coreApp = false;
6440        }
6441
6442        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6443            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6444        }
6445
6446        if (mCustomResolverComponentName != null &&
6447                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6448            setUpCustomResolverActivity(pkg);
6449        }
6450
6451        if (pkg.packageName.equals("android")) {
6452            synchronized (mPackages) {
6453                if (mAndroidApplication != null) {
6454                    Slog.w(TAG, "*************************************************");
6455                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6456                    Slog.w(TAG, " file=" + scanFile);
6457                    Slog.w(TAG, "*************************************************");
6458                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6459                            "Core android package being redefined.  Skipping.");
6460                }
6461
6462                // Set up information for our fall-back user intent resolution activity.
6463                mPlatformPackage = pkg;
6464                pkg.mVersionCode = mSdkVersion;
6465                mAndroidApplication = pkg.applicationInfo;
6466
6467                if (!mResolverReplaced) {
6468                    mResolveActivity.applicationInfo = mAndroidApplication;
6469                    mResolveActivity.name = ResolverActivity.class.getName();
6470                    mResolveActivity.packageName = mAndroidApplication.packageName;
6471                    mResolveActivity.processName = "system:ui";
6472                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6473                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6474                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6475                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6476                    mResolveActivity.exported = true;
6477                    mResolveActivity.enabled = true;
6478                    mResolveInfo.activityInfo = mResolveActivity;
6479                    mResolveInfo.priority = 0;
6480                    mResolveInfo.preferredOrder = 0;
6481                    mResolveInfo.match = 0;
6482                    mResolveComponentName = new ComponentName(
6483                            mAndroidApplication.packageName, mResolveActivity.name);
6484                }
6485            }
6486        }
6487
6488        if (DEBUG_PACKAGE_SCANNING) {
6489            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6490                Log.d(TAG, "Scanning package " + pkg.packageName);
6491        }
6492
6493        if (mPackages.containsKey(pkg.packageName)
6494                || mSharedLibraries.containsKey(pkg.packageName)) {
6495            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6496                    "Application package " + pkg.packageName
6497                    + " already installed.  Skipping duplicate.");
6498        }
6499
6500        // If we're only installing presumed-existing packages, require that the
6501        // scanned APK is both already known and at the path previously established
6502        // for it.  Previously unknown packages we pick up normally, but if we have an
6503        // a priori expectation about this package's install presence, enforce it.
6504        // With a singular exception for new system packages. When an OTA contains
6505        // a new system package, we allow the codepath to change from a system location
6506        // to the user-installed location. If we don't allow this change, any newer,
6507        // user-installed version of the application will be ignored.
6508        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6509            if (mExpectingBetter.containsKey(pkg.packageName)) {
6510                logCriticalInfo(Log.WARN,
6511                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6512            } else {
6513                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6514                if (known != null) {
6515                    if (DEBUG_PACKAGE_SCANNING) {
6516                        Log.d(TAG, "Examining " + pkg.codePath
6517                                + " and requiring known paths " + known.codePathString
6518                                + " & " + known.resourcePathString);
6519                    }
6520                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6521                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6522                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6523                                "Application package " + pkg.packageName
6524                                + " found at " + pkg.applicationInfo.getCodePath()
6525                                + " but expected at " + known.codePathString + "; ignoring.");
6526                    }
6527                }
6528            }
6529        }
6530
6531        // Initialize package source and resource directories
6532        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6533        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6534
6535        SharedUserSetting suid = null;
6536        PackageSetting pkgSetting = null;
6537
6538        if (!isSystemApp(pkg)) {
6539            // Only system apps can use these features.
6540            pkg.mOriginalPackages = null;
6541            pkg.mRealPackage = null;
6542            pkg.mAdoptPermissions = null;
6543        }
6544
6545        // writer
6546        synchronized (mPackages) {
6547            if (pkg.mSharedUserId != null) {
6548                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6549                if (suid == null) {
6550                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6551                            "Creating application package " + pkg.packageName
6552                            + " for shared user failed");
6553                }
6554                if (DEBUG_PACKAGE_SCANNING) {
6555                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6556                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6557                                + "): packages=" + suid.packages);
6558                }
6559            }
6560
6561            // Check if we are renaming from an original package name.
6562            PackageSetting origPackage = null;
6563            String realName = null;
6564            if (pkg.mOriginalPackages != null) {
6565                // This package may need to be renamed to a previously
6566                // installed name.  Let's check on that...
6567                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6568                if (pkg.mOriginalPackages.contains(renamed)) {
6569                    // This package had originally been installed as the
6570                    // original name, and we have already taken care of
6571                    // transitioning to the new one.  Just update the new
6572                    // one to continue using the old name.
6573                    realName = pkg.mRealPackage;
6574                    if (!pkg.packageName.equals(renamed)) {
6575                        // Callers into this function may have already taken
6576                        // care of renaming the package; only do it here if
6577                        // it is not already done.
6578                        pkg.setPackageName(renamed);
6579                    }
6580
6581                } else {
6582                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6583                        if ((origPackage = mSettings.peekPackageLPr(
6584                                pkg.mOriginalPackages.get(i))) != null) {
6585                            // We do have the package already installed under its
6586                            // original name...  should we use it?
6587                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6588                                // New package is not compatible with original.
6589                                origPackage = null;
6590                                continue;
6591                            } else if (origPackage.sharedUser != null) {
6592                                // Make sure uid is compatible between packages.
6593                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6594                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6595                                            + " to " + pkg.packageName + ": old uid "
6596                                            + origPackage.sharedUser.name
6597                                            + " differs from " + pkg.mSharedUserId);
6598                                    origPackage = null;
6599                                    continue;
6600                                }
6601                            } else {
6602                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6603                                        + pkg.packageName + " to old name " + origPackage.name);
6604                            }
6605                            break;
6606                        }
6607                    }
6608                }
6609            }
6610
6611            if (mTransferedPackages.contains(pkg.packageName)) {
6612                Slog.w(TAG, "Package " + pkg.packageName
6613                        + " was transferred to another, but its .apk remains");
6614            }
6615
6616            // Just create the setting, don't add it yet. For already existing packages
6617            // the PkgSetting exists already and doesn't have to be created.
6618            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6619                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6620                    pkg.applicationInfo.primaryCpuAbi,
6621                    pkg.applicationInfo.secondaryCpuAbi,
6622                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6623                    user, false);
6624            if (pkgSetting == null) {
6625                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6626                        "Creating application package " + pkg.packageName + " failed");
6627            }
6628
6629            if (pkgSetting.origPackage != null) {
6630                // If we are first transitioning from an original package,
6631                // fix up the new package's name now.  We need to do this after
6632                // looking up the package under its new name, so getPackageLP
6633                // can take care of fiddling things correctly.
6634                pkg.setPackageName(origPackage.name);
6635
6636                // File a report about this.
6637                String msg = "New package " + pkgSetting.realName
6638                        + " renamed to replace old package " + pkgSetting.name;
6639                reportSettingsProblem(Log.WARN, msg);
6640
6641                // Make a note of it.
6642                mTransferedPackages.add(origPackage.name);
6643
6644                // No longer need to retain this.
6645                pkgSetting.origPackage = null;
6646            }
6647
6648            if (realName != null) {
6649                // Make a note of it.
6650                mTransferedPackages.add(pkg.packageName);
6651            }
6652
6653            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6654                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6655            }
6656
6657            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6658                // Check all shared libraries and map to their actual file path.
6659                // We only do this here for apps not on a system dir, because those
6660                // are the only ones that can fail an install due to this.  We
6661                // will take care of the system apps by updating all of their
6662                // library paths after the scan is done.
6663                updateSharedLibrariesLPw(pkg, null);
6664            }
6665
6666            if (mFoundPolicyFile) {
6667                SELinuxMMAC.assignSeinfoValue(pkg);
6668            }
6669
6670            pkg.applicationInfo.uid = pkgSetting.appId;
6671            pkg.mExtras = pkgSetting;
6672            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6673                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6674                    // We just determined the app is signed correctly, so bring
6675                    // over the latest parsed certs.
6676                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6677                } else {
6678                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6679                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6680                                "Package " + pkg.packageName + " upgrade keys do not match the "
6681                                + "previously installed version");
6682                    } else {
6683                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6684                        String msg = "System package " + pkg.packageName
6685                            + " signature changed; retaining data.";
6686                        reportSettingsProblem(Log.WARN, msg);
6687                    }
6688                }
6689            } else {
6690                try {
6691                    verifySignaturesLP(pkgSetting, pkg);
6692                    // We just determined the app is signed correctly, so bring
6693                    // over the latest parsed certs.
6694                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6695                } catch (PackageManagerException e) {
6696                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6697                        throw e;
6698                    }
6699                    // The signature has changed, but this package is in the system
6700                    // image...  let's recover!
6701                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6702                    // However...  if this package is part of a shared user, but it
6703                    // doesn't match the signature of the shared user, let's fail.
6704                    // What this means is that you can't change the signatures
6705                    // associated with an overall shared user, which doesn't seem all
6706                    // that unreasonable.
6707                    if (pkgSetting.sharedUser != null) {
6708                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6709                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6710                            throw new PackageManagerException(
6711                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6712                                            "Signature mismatch for shared user : "
6713                                            + pkgSetting.sharedUser);
6714                        }
6715                    }
6716                    // File a report about this.
6717                    String msg = "System package " + pkg.packageName
6718                        + " signature changed; retaining data.";
6719                    reportSettingsProblem(Log.WARN, msg);
6720                }
6721            }
6722            // Verify that this new package doesn't have any content providers
6723            // that conflict with existing packages.  Only do this if the
6724            // package isn't already installed, since we don't want to break
6725            // things that are installed.
6726            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6727                final int N = pkg.providers.size();
6728                int i;
6729                for (i=0; i<N; i++) {
6730                    PackageParser.Provider p = pkg.providers.get(i);
6731                    if (p.info.authority != null) {
6732                        String names[] = p.info.authority.split(";");
6733                        for (int j = 0; j < names.length; j++) {
6734                            if (mProvidersByAuthority.containsKey(names[j])) {
6735                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6736                                final String otherPackageName =
6737                                        ((other != null && other.getComponentName() != null) ?
6738                                                other.getComponentName().getPackageName() : "?");
6739                                throw new PackageManagerException(
6740                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6741                                                "Can't install because provider name " + names[j]
6742                                                + " (in package " + pkg.applicationInfo.packageName
6743                                                + ") is already used by " + otherPackageName);
6744                            }
6745                        }
6746                    }
6747                }
6748            }
6749
6750            if (pkg.mAdoptPermissions != null) {
6751                // This package wants to adopt ownership of permissions from
6752                // another package.
6753                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6754                    final String origName = pkg.mAdoptPermissions.get(i);
6755                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6756                    if (orig != null) {
6757                        if (verifyPackageUpdateLPr(orig, pkg)) {
6758                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6759                                    + pkg.packageName);
6760                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6761                        }
6762                    }
6763                }
6764            }
6765        }
6766
6767        final String pkgName = pkg.packageName;
6768
6769        final long scanFileTime = scanFile.lastModified();
6770        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6771        pkg.applicationInfo.processName = fixProcessName(
6772                pkg.applicationInfo.packageName,
6773                pkg.applicationInfo.processName,
6774                pkg.applicationInfo.uid);
6775
6776        File dataPath;
6777        if (mPlatformPackage == pkg) {
6778            // The system package is special.
6779            dataPath = new File(Environment.getDataDirectory(), "system");
6780
6781            pkg.applicationInfo.dataDir = dataPath.getPath();
6782
6783        } else {
6784            // This is a normal package, need to make its data directory.
6785            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6786                    UserHandle.USER_OWNER, pkg.packageName);
6787
6788            boolean uidError = false;
6789            if (dataPath.exists()) {
6790                int currentUid = 0;
6791                try {
6792                    StructStat stat = Os.stat(dataPath.getPath());
6793                    currentUid = stat.st_uid;
6794                } catch (ErrnoException e) {
6795                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6796                }
6797
6798                // If we have mismatched owners for the data path, we have a problem.
6799                if (currentUid != pkg.applicationInfo.uid) {
6800                    boolean recovered = false;
6801                    if (currentUid == 0) {
6802                        // The directory somehow became owned by root.  Wow.
6803                        // This is probably because the system was stopped while
6804                        // installd was in the middle of messing with its libs
6805                        // directory.  Ask installd to fix that.
6806                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6807                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6808                        if (ret >= 0) {
6809                            recovered = true;
6810                            String msg = "Package " + pkg.packageName
6811                                    + " unexpectedly changed to uid 0; recovered to " +
6812                                    + pkg.applicationInfo.uid;
6813                            reportSettingsProblem(Log.WARN, msg);
6814                        }
6815                    }
6816                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6817                            || (scanFlags&SCAN_BOOTING) != 0)) {
6818                        // If this is a system app, we can at least delete its
6819                        // current data so the application will still work.
6820                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6821                        if (ret >= 0) {
6822                            // TODO: Kill the processes first
6823                            // Old data gone!
6824                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6825                                    ? "System package " : "Third party package ";
6826                            String msg = prefix + pkg.packageName
6827                                    + " has changed from uid: "
6828                                    + currentUid + " to "
6829                                    + pkg.applicationInfo.uid + "; old data erased";
6830                            reportSettingsProblem(Log.WARN, msg);
6831                            recovered = true;
6832
6833                            // And now re-install the app.
6834                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6835                                    pkg.applicationInfo.seinfo);
6836                            if (ret == -1) {
6837                                // Ack should not happen!
6838                                msg = prefix + pkg.packageName
6839                                        + " could not have data directory re-created after delete.";
6840                                reportSettingsProblem(Log.WARN, msg);
6841                                throw new PackageManagerException(
6842                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6843                            }
6844                        }
6845                        if (!recovered) {
6846                            mHasSystemUidErrors = true;
6847                        }
6848                    } else if (!recovered) {
6849                        // If we allow this install to proceed, we will be broken.
6850                        // Abort, abort!
6851                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6852                                "scanPackageLI");
6853                    }
6854                    if (!recovered) {
6855                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6856                            + pkg.applicationInfo.uid + "/fs_"
6857                            + currentUid;
6858                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6859                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6860                        String msg = "Package " + pkg.packageName
6861                                + " has mismatched uid: "
6862                                + currentUid + " on disk, "
6863                                + pkg.applicationInfo.uid + " in settings";
6864                        // writer
6865                        synchronized (mPackages) {
6866                            mSettings.mReadMessages.append(msg);
6867                            mSettings.mReadMessages.append('\n');
6868                            uidError = true;
6869                            if (!pkgSetting.uidError) {
6870                                reportSettingsProblem(Log.ERROR, msg);
6871                            }
6872                        }
6873                    }
6874                }
6875                pkg.applicationInfo.dataDir = dataPath.getPath();
6876                if (mShouldRestoreconData) {
6877                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6878                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6879                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6880                }
6881            } else {
6882                if (DEBUG_PACKAGE_SCANNING) {
6883                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6884                        Log.v(TAG, "Want this data dir: " + dataPath);
6885                }
6886                //invoke installer to do the actual installation
6887                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6888                        pkg.applicationInfo.seinfo);
6889                if (ret < 0) {
6890                    // Error from installer
6891                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6892                            "Unable to create data dirs [errorCode=" + ret + "]");
6893                }
6894
6895                if (dataPath.exists()) {
6896                    pkg.applicationInfo.dataDir = dataPath.getPath();
6897                } else {
6898                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6899                    pkg.applicationInfo.dataDir = null;
6900                }
6901            }
6902
6903            pkgSetting.uidError = uidError;
6904        }
6905
6906        final String path = scanFile.getPath();
6907        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6908
6909        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6910            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6911
6912            // Some system apps still use directory structure for native libraries
6913            // in which case we might end up not detecting abi solely based on apk
6914            // structure. Try to detect abi based on directory structure.
6915            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6916                    pkg.applicationInfo.primaryCpuAbi == null) {
6917                setBundledAppAbisAndRoots(pkg, pkgSetting);
6918                setNativeLibraryPaths(pkg);
6919            }
6920
6921        } else {
6922            if ((scanFlags & SCAN_MOVE) != 0) {
6923                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6924                // but we already have this packages package info in the PackageSetting. We just
6925                // use that and derive the native library path based on the new codepath.
6926                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6927                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6928            }
6929
6930            // Set native library paths again. For moves, the path will be updated based on the
6931            // ABIs we've determined above. For non-moves, the path will be updated based on the
6932            // ABIs we determined during compilation, but the path will depend on the final
6933            // package path (after the rename away from the stage path).
6934            setNativeLibraryPaths(pkg);
6935        }
6936
6937        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6938        final int[] userIds = sUserManager.getUserIds();
6939        synchronized (mInstallLock) {
6940            // Make sure all user data directories are ready to roll; we're okay
6941            // if they already exist
6942            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6943                for (int userId : userIds) {
6944                    if (userId != 0) {
6945                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6946                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6947                                pkg.applicationInfo.seinfo);
6948                    }
6949                }
6950            }
6951
6952            // Create a native library symlink only if we have native libraries
6953            // and if the native libraries are 32 bit libraries. We do not provide
6954            // this symlink for 64 bit libraries.
6955            if (pkg.applicationInfo.primaryCpuAbi != null &&
6956                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6957                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6958                for (int userId : userIds) {
6959                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6960                            nativeLibPath, userId) < 0) {
6961                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6962                                "Failed linking native library dir (user=" + userId + ")");
6963                    }
6964                }
6965            }
6966        }
6967
6968        // This is a special case for the "system" package, where the ABI is
6969        // dictated by the zygote configuration (and init.rc). We should keep track
6970        // of this ABI so that we can deal with "normal" applications that run under
6971        // the same UID correctly.
6972        if (mPlatformPackage == pkg) {
6973            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6974                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6975        }
6976
6977        // If there's a mismatch between the abi-override in the package setting
6978        // and the abiOverride specified for the install. Warn about this because we
6979        // would've already compiled the app without taking the package setting into
6980        // account.
6981        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6982            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6983                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6984                        " for package: " + pkg.packageName);
6985            }
6986        }
6987
6988        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6989        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6990        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6991
6992        // Copy the derived override back to the parsed package, so that we can
6993        // update the package settings accordingly.
6994        pkg.cpuAbiOverride = cpuAbiOverride;
6995
6996        if (DEBUG_ABI_SELECTION) {
6997            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6998                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6999                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7000        }
7001
7002        // Push the derived path down into PackageSettings so we know what to
7003        // clean up at uninstall time.
7004        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7005
7006        if (DEBUG_ABI_SELECTION) {
7007            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7008                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7009                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7010        }
7011
7012        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7013            // We don't do this here during boot because we can do it all
7014            // at once after scanning all existing packages.
7015            //
7016            // We also do this *before* we perform dexopt on this package, so that
7017            // we can avoid redundant dexopts, and also to make sure we've got the
7018            // code and package path correct.
7019            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7020                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7021        }
7022
7023        if ((scanFlags & SCAN_NO_DEX) == 0) {
7024            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7025                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7026            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7027                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7028            }
7029        }
7030        if (mFactoryTest && pkg.requestedPermissions.contains(
7031                android.Manifest.permission.FACTORY_TEST)) {
7032            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7033        }
7034
7035        ArrayList<PackageParser.Package> clientLibPkgs = null;
7036
7037        // writer
7038        synchronized (mPackages) {
7039            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7040                // Only system apps can add new shared libraries.
7041                if (pkg.libraryNames != null) {
7042                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7043                        String name = pkg.libraryNames.get(i);
7044                        boolean allowed = false;
7045                        if (pkg.isUpdatedSystemApp()) {
7046                            // New library entries can only be added through the
7047                            // system image.  This is important to get rid of a lot
7048                            // of nasty edge cases: for example if we allowed a non-
7049                            // system update of the app to add a library, then uninstalling
7050                            // the update would make the library go away, and assumptions
7051                            // we made such as through app install filtering would now
7052                            // have allowed apps on the device which aren't compatible
7053                            // with it.  Better to just have the restriction here, be
7054                            // conservative, and create many fewer cases that can negatively
7055                            // impact the user experience.
7056                            final PackageSetting sysPs = mSettings
7057                                    .getDisabledSystemPkgLPr(pkg.packageName);
7058                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7059                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7060                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7061                                        allowed = true;
7062                                        allowed = true;
7063                                        break;
7064                                    }
7065                                }
7066                            }
7067                        } else {
7068                            allowed = true;
7069                        }
7070                        if (allowed) {
7071                            if (!mSharedLibraries.containsKey(name)) {
7072                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7073                            } else if (!name.equals(pkg.packageName)) {
7074                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7075                                        + name + " already exists; skipping");
7076                            }
7077                        } else {
7078                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7079                                    + name + " that is not declared on system image; skipping");
7080                        }
7081                    }
7082                    if ((scanFlags&SCAN_BOOTING) == 0) {
7083                        // If we are not booting, we need to update any applications
7084                        // that are clients of our shared library.  If we are booting,
7085                        // this will all be done once the scan is complete.
7086                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7087                    }
7088                }
7089            }
7090        }
7091
7092        // We also need to dexopt any apps that are dependent on this library.  Note that
7093        // if these fail, we should abort the install since installing the library will
7094        // result in some apps being broken.
7095        if (clientLibPkgs != null) {
7096            if ((scanFlags & SCAN_NO_DEX) == 0) {
7097                for (int i = 0; i < clientLibPkgs.size(); i++) {
7098                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7099                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7100                            null /* instruction sets */, forceDex,
7101                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7102                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7103                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7104                                "scanPackageLI failed to dexopt clientLibPkgs");
7105                    }
7106                }
7107            }
7108        }
7109
7110        // Also need to kill any apps that are dependent on the library.
7111        if (clientLibPkgs != null) {
7112            for (int i=0; i<clientLibPkgs.size(); i++) {
7113                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7114                killApplication(clientPkg.applicationInfo.packageName,
7115                        clientPkg.applicationInfo.uid, "update lib");
7116            }
7117        }
7118
7119        // Make sure we're not adding any bogus keyset info
7120        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7121        ksms.assertScannedPackageValid(pkg);
7122
7123        // writer
7124        synchronized (mPackages) {
7125            // We don't expect installation to fail beyond this point
7126
7127            // Add the new setting to mSettings
7128            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7129            // Add the new setting to mPackages
7130            mPackages.put(pkg.applicationInfo.packageName, pkg);
7131            // Make sure we don't accidentally delete its data.
7132            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7133            while (iter.hasNext()) {
7134                PackageCleanItem item = iter.next();
7135                if (pkgName.equals(item.packageName)) {
7136                    iter.remove();
7137                }
7138            }
7139
7140            // Take care of first install / last update times.
7141            if (currentTime != 0) {
7142                if (pkgSetting.firstInstallTime == 0) {
7143                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7144                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7145                    pkgSetting.lastUpdateTime = currentTime;
7146                }
7147            } else if (pkgSetting.firstInstallTime == 0) {
7148                // We need *something*.  Take time time stamp of the file.
7149                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7150            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7151                if (scanFileTime != pkgSetting.timeStamp) {
7152                    // A package on the system image has changed; consider this
7153                    // to be an update.
7154                    pkgSetting.lastUpdateTime = scanFileTime;
7155                }
7156            }
7157
7158            // Add the package's KeySets to the global KeySetManagerService
7159            ksms.addScannedPackageLPw(pkg);
7160
7161            int N = pkg.providers.size();
7162            StringBuilder r = null;
7163            int i;
7164            for (i=0; i<N; i++) {
7165                PackageParser.Provider p = pkg.providers.get(i);
7166                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7167                        p.info.processName, pkg.applicationInfo.uid);
7168                mProviders.addProvider(p);
7169                p.syncable = p.info.isSyncable;
7170                if (p.info.authority != null) {
7171                    String names[] = p.info.authority.split(";");
7172                    p.info.authority = null;
7173                    for (int j = 0; j < names.length; j++) {
7174                        if (j == 1 && p.syncable) {
7175                            // We only want the first authority for a provider to possibly be
7176                            // syncable, so if we already added this provider using a different
7177                            // authority clear the syncable flag. We copy the provider before
7178                            // changing it because the mProviders object contains a reference
7179                            // to a provider that we don't want to change.
7180                            // Only do this for the second authority since the resulting provider
7181                            // object can be the same for all future authorities for this provider.
7182                            p = new PackageParser.Provider(p);
7183                            p.syncable = false;
7184                        }
7185                        if (!mProvidersByAuthority.containsKey(names[j])) {
7186                            mProvidersByAuthority.put(names[j], p);
7187                            if (p.info.authority == null) {
7188                                p.info.authority = names[j];
7189                            } else {
7190                                p.info.authority = p.info.authority + ";" + names[j];
7191                            }
7192                            if (DEBUG_PACKAGE_SCANNING) {
7193                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7194                                    Log.d(TAG, "Registered content provider: " + names[j]
7195                                            + ", className = " + p.info.name + ", isSyncable = "
7196                                            + p.info.isSyncable);
7197                            }
7198                        } else {
7199                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7200                            Slog.w(TAG, "Skipping provider name " + names[j] +
7201                                    " (in package " + pkg.applicationInfo.packageName +
7202                                    "): name already used by "
7203                                    + ((other != null && other.getComponentName() != null)
7204                                            ? other.getComponentName().getPackageName() : "?"));
7205                        }
7206                    }
7207                }
7208                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7209                    if (r == null) {
7210                        r = new StringBuilder(256);
7211                    } else {
7212                        r.append(' ');
7213                    }
7214                    r.append(p.info.name);
7215                }
7216            }
7217            if (r != null) {
7218                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7219            }
7220
7221            N = pkg.services.size();
7222            r = null;
7223            for (i=0; i<N; i++) {
7224                PackageParser.Service s = pkg.services.get(i);
7225                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7226                        s.info.processName, pkg.applicationInfo.uid);
7227                mServices.addService(s);
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(s.info.name);
7235                }
7236            }
7237            if (r != null) {
7238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7239            }
7240
7241            N = pkg.receivers.size();
7242            r = null;
7243            for (i=0; i<N; i++) {
7244                PackageParser.Activity a = pkg.receivers.get(i);
7245                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7246                        a.info.processName, pkg.applicationInfo.uid);
7247                mReceivers.addActivity(a, "receiver");
7248                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7249                    if (r == null) {
7250                        r = new StringBuilder(256);
7251                    } else {
7252                        r.append(' ');
7253                    }
7254                    r.append(a.info.name);
7255                }
7256            }
7257            if (r != null) {
7258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7259            }
7260
7261            N = pkg.activities.size();
7262            r = null;
7263            for (i=0; i<N; i++) {
7264                PackageParser.Activity a = pkg.activities.get(i);
7265                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7266                        a.info.processName, pkg.applicationInfo.uid);
7267                mActivities.addActivity(a, "activity");
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, "  Activities: " + r);
7279            }
7280
7281            N = pkg.permissionGroups.size();
7282            r = null;
7283            for (i=0; i<N; i++) {
7284                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7285                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7286                if (cur == null) {
7287                    mPermissionGroups.put(pg.info.name, pg);
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(pg.info.name);
7295                    }
7296                } else {
7297                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7298                            + pg.info.packageName + " ignored: original from "
7299                            + cur.info.packageName);
7300                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7301                        if (r == null) {
7302                            r = new StringBuilder(256);
7303                        } else {
7304                            r.append(' ');
7305                        }
7306                        r.append("DUP:");
7307                        r.append(pg.info.name);
7308                    }
7309                }
7310            }
7311            if (r != null) {
7312                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7313            }
7314
7315            N = pkg.permissions.size();
7316            r = null;
7317            for (i=0; i<N; i++) {
7318                PackageParser.Permission p = pkg.permissions.get(i);
7319
7320                // Now that permission groups have a special meaning, we ignore permission
7321                // groups for legacy apps to prevent unexpected behavior. In particular,
7322                // permissions for one app being granted to someone just becuase they happen
7323                // to be in a group defined by another app (before this had no implications).
7324                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7325                    p.group = mPermissionGroups.get(p.info.group);
7326                    // Warn for a permission in an unknown group.
7327                    if (p.info.group != null && p.group == null) {
7328                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7329                                + p.info.packageName + " in an unknown group " + p.info.group);
7330                    }
7331                }
7332
7333                ArrayMap<String, BasePermission> permissionMap =
7334                        p.tree ? mSettings.mPermissionTrees
7335                                : mSettings.mPermissions;
7336                BasePermission bp = permissionMap.get(p.info.name);
7337
7338                // Allow system apps to redefine non-system permissions
7339                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7340                    final boolean currentOwnerIsSystem = (bp.perm != null
7341                            && isSystemApp(bp.perm.owner));
7342                    if (isSystemApp(p.owner)) {
7343                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7344                            // It's a built-in permission and no owner, take ownership now
7345                            bp.packageSetting = pkgSetting;
7346                            bp.perm = p;
7347                            bp.uid = pkg.applicationInfo.uid;
7348                            bp.sourcePackage = p.info.packageName;
7349                        } else if (!currentOwnerIsSystem) {
7350                            String msg = "New decl " + p.owner + " of permission  "
7351                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7352                            reportSettingsProblem(Log.WARN, msg);
7353                            bp = null;
7354                        }
7355                    }
7356                }
7357
7358                if (bp == null) {
7359                    bp = new BasePermission(p.info.name, p.info.packageName,
7360                            BasePermission.TYPE_NORMAL);
7361                    permissionMap.put(p.info.name, bp);
7362                }
7363
7364                if (bp.perm == null) {
7365                    if (bp.sourcePackage == null
7366                            || bp.sourcePackage.equals(p.info.packageName)) {
7367                        BasePermission tree = findPermissionTreeLP(p.info.name);
7368                        if (tree == null
7369                                || tree.sourcePackage.equals(p.info.packageName)) {
7370                            bp.packageSetting = pkgSetting;
7371                            bp.perm = p;
7372                            bp.uid = pkg.applicationInfo.uid;
7373                            bp.sourcePackage = p.info.packageName;
7374                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7375                                if (r == null) {
7376                                    r = new StringBuilder(256);
7377                                } else {
7378                                    r.append(' ');
7379                                }
7380                                r.append(p.info.name);
7381                            }
7382                        } else {
7383                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7384                                    + p.info.packageName + " ignored: base tree "
7385                                    + tree.name + " is from package "
7386                                    + tree.sourcePackage);
7387                        }
7388                    } else {
7389                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7390                                + p.info.packageName + " ignored: original from "
7391                                + bp.sourcePackage);
7392                    }
7393                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7394                    if (r == null) {
7395                        r = new StringBuilder(256);
7396                    } else {
7397                        r.append(' ');
7398                    }
7399                    r.append("DUP:");
7400                    r.append(p.info.name);
7401                }
7402                if (bp.perm == p) {
7403                    bp.protectionLevel = p.info.protectionLevel;
7404                }
7405            }
7406
7407            if (r != null) {
7408                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7409            }
7410
7411            N = pkg.instrumentation.size();
7412            r = null;
7413            for (i=0; i<N; i++) {
7414                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7415                a.info.packageName = pkg.applicationInfo.packageName;
7416                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7417                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7418                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7419                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7420                a.info.dataDir = pkg.applicationInfo.dataDir;
7421
7422                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7423                // need other information about the application, like the ABI and what not ?
7424                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7425                mInstrumentation.put(a.getComponentName(), a);
7426                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7427                    if (r == null) {
7428                        r = new StringBuilder(256);
7429                    } else {
7430                        r.append(' ');
7431                    }
7432                    r.append(a.info.name);
7433                }
7434            }
7435            if (r != null) {
7436                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7437            }
7438
7439            if (pkg.protectedBroadcasts != null) {
7440                N = pkg.protectedBroadcasts.size();
7441                for (i=0; i<N; i++) {
7442                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7443                }
7444            }
7445
7446            pkgSetting.setTimeStamp(scanFileTime);
7447
7448            // Create idmap files for pairs of (packages, overlay packages).
7449            // Note: "android", ie framework-res.apk, is handled by native layers.
7450            if (pkg.mOverlayTarget != null) {
7451                // This is an overlay package.
7452                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7453                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7454                        mOverlays.put(pkg.mOverlayTarget,
7455                                new ArrayMap<String, PackageParser.Package>());
7456                    }
7457                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7458                    map.put(pkg.packageName, pkg);
7459                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7460                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7461                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7462                                "scanPackageLI failed to createIdmap");
7463                    }
7464                }
7465            } else if (mOverlays.containsKey(pkg.packageName) &&
7466                    !pkg.packageName.equals("android")) {
7467                // This is a regular package, with one or more known overlay packages.
7468                createIdmapsForPackageLI(pkg);
7469            }
7470        }
7471
7472        return pkg;
7473    }
7474
7475    /**
7476     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7477     * is derived purely on the basis of the contents of {@code scanFile} and
7478     * {@code cpuAbiOverride}.
7479     *
7480     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7481     */
7482    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7483                                 String cpuAbiOverride, boolean extractLibs)
7484            throws PackageManagerException {
7485        // TODO: We can probably be smarter about this stuff. For installed apps,
7486        // we can calculate this information at install time once and for all. For
7487        // system apps, we can probably assume that this information doesn't change
7488        // after the first boot scan. As things stand, we do lots of unnecessary work.
7489
7490        // Give ourselves some initial paths; we'll come back for another
7491        // pass once we've determined ABI below.
7492        setNativeLibraryPaths(pkg);
7493
7494        // We would never need to extract libs for forward-locked and external packages,
7495        // since the container service will do it for us. We shouldn't attempt to
7496        // extract libs from system app when it was not updated.
7497        if (pkg.isForwardLocked() || isExternal(pkg) ||
7498            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7499            extractLibs = false;
7500        }
7501
7502        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7503        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7504
7505        NativeLibraryHelper.Handle handle = null;
7506        try {
7507            handle = NativeLibraryHelper.Handle.create(scanFile);
7508            // TODO(multiArch): This can be null for apps that didn't go through the
7509            // usual installation process. We can calculate it again, like we
7510            // do during install time.
7511            //
7512            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7513            // unnecessary.
7514            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7515
7516            // Null out the abis so that they can be recalculated.
7517            pkg.applicationInfo.primaryCpuAbi = null;
7518            pkg.applicationInfo.secondaryCpuAbi = null;
7519            if (isMultiArch(pkg.applicationInfo)) {
7520                // Warn if we've set an abiOverride for multi-lib packages..
7521                // By definition, we need to copy both 32 and 64 bit libraries for
7522                // such packages.
7523                if (pkg.cpuAbiOverride != null
7524                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7525                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7526                }
7527
7528                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7529                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7530                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7531                    if (extractLibs) {
7532                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7533                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7534                                useIsaSpecificSubdirs);
7535                    } else {
7536                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7537                    }
7538                }
7539
7540                maybeThrowExceptionForMultiArchCopy(
7541                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7542
7543                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7544                    if (extractLibs) {
7545                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7546                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7547                                useIsaSpecificSubdirs);
7548                    } else {
7549                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7550                    }
7551                }
7552
7553                maybeThrowExceptionForMultiArchCopy(
7554                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7555
7556                if (abi64 >= 0) {
7557                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7558                }
7559
7560                if (abi32 >= 0) {
7561                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7562                    if (abi64 >= 0) {
7563                        pkg.applicationInfo.secondaryCpuAbi = abi;
7564                    } else {
7565                        pkg.applicationInfo.primaryCpuAbi = abi;
7566                    }
7567                }
7568            } else {
7569                String[] abiList = (cpuAbiOverride != null) ?
7570                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7571
7572                // Enable gross and lame hacks for apps that are built with old
7573                // SDK tools. We must scan their APKs for renderscript bitcode and
7574                // not launch them if it's present. Don't bother checking on devices
7575                // that don't have 64 bit support.
7576                boolean needsRenderScriptOverride = false;
7577                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7578                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7579                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7580                    needsRenderScriptOverride = true;
7581                }
7582
7583                final int copyRet;
7584                if (extractLibs) {
7585                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7586                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7587                } else {
7588                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7589                }
7590
7591                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7592                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7593                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7594                }
7595
7596                if (copyRet >= 0) {
7597                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7598                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7599                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7600                } else if (needsRenderScriptOverride) {
7601                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7602                }
7603            }
7604        } catch (IOException ioe) {
7605            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7606        } finally {
7607            IoUtils.closeQuietly(handle);
7608        }
7609
7610        // Now that we've calculated the ABIs and determined if it's an internal app,
7611        // we will go ahead and populate the nativeLibraryPath.
7612        setNativeLibraryPaths(pkg);
7613    }
7614
7615    /**
7616     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7617     * i.e, so that all packages can be run inside a single process if required.
7618     *
7619     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7620     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7621     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7622     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7623     * updating a package that belongs to a shared user.
7624     *
7625     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7626     * adds unnecessary complexity.
7627     */
7628    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7629            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7630        String requiredInstructionSet = null;
7631        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7632            requiredInstructionSet = VMRuntime.getInstructionSet(
7633                     scannedPackage.applicationInfo.primaryCpuAbi);
7634        }
7635
7636        PackageSetting requirer = null;
7637        for (PackageSetting ps : packagesForUser) {
7638            // If packagesForUser contains scannedPackage, we skip it. This will happen
7639            // when scannedPackage is an update of an existing package. Without this check,
7640            // we will never be able to change the ABI of any package belonging to a shared
7641            // user, even if it's compatible with other packages.
7642            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7643                if (ps.primaryCpuAbiString == null) {
7644                    continue;
7645                }
7646
7647                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7648                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7649                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7650                    // this but there's not much we can do.
7651                    String errorMessage = "Instruction set mismatch, "
7652                            + ((requirer == null) ? "[caller]" : requirer)
7653                            + " requires " + requiredInstructionSet + " whereas " + ps
7654                            + " requires " + instructionSet;
7655                    Slog.w(TAG, errorMessage);
7656                }
7657
7658                if (requiredInstructionSet == null) {
7659                    requiredInstructionSet = instructionSet;
7660                    requirer = ps;
7661                }
7662            }
7663        }
7664
7665        if (requiredInstructionSet != null) {
7666            String adjustedAbi;
7667            if (requirer != null) {
7668                // requirer != null implies that either scannedPackage was null or that scannedPackage
7669                // did not require an ABI, in which case we have to adjust scannedPackage to match
7670                // the ABI of the set (which is the same as requirer's ABI)
7671                adjustedAbi = requirer.primaryCpuAbiString;
7672                if (scannedPackage != null) {
7673                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7674                }
7675            } else {
7676                // requirer == null implies that we're updating all ABIs in the set to
7677                // match scannedPackage.
7678                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7679            }
7680
7681            for (PackageSetting ps : packagesForUser) {
7682                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7683                    if (ps.primaryCpuAbiString != null) {
7684                        continue;
7685                    }
7686
7687                    ps.primaryCpuAbiString = adjustedAbi;
7688                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7689                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7690                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7691
7692                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7693                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7694                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7695                            ps.primaryCpuAbiString = null;
7696                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7697                            return;
7698                        } else {
7699                            mInstaller.rmdex(ps.codePathString,
7700                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7701                        }
7702                    }
7703                }
7704            }
7705        }
7706    }
7707
7708    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7709        synchronized (mPackages) {
7710            mResolverReplaced = true;
7711            // Set up information for custom user intent resolution activity.
7712            mResolveActivity.applicationInfo = pkg.applicationInfo;
7713            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7714            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7715            mResolveActivity.processName = pkg.applicationInfo.packageName;
7716            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7717            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7718                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7719            mResolveActivity.theme = 0;
7720            mResolveActivity.exported = true;
7721            mResolveActivity.enabled = true;
7722            mResolveInfo.activityInfo = mResolveActivity;
7723            mResolveInfo.priority = 0;
7724            mResolveInfo.preferredOrder = 0;
7725            mResolveInfo.match = 0;
7726            mResolveComponentName = mCustomResolverComponentName;
7727            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7728                    mResolveComponentName);
7729        }
7730    }
7731
7732    private static String calculateBundledApkRoot(final String codePathString) {
7733        final File codePath = new File(codePathString);
7734        final File codeRoot;
7735        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7736            codeRoot = Environment.getRootDirectory();
7737        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7738            codeRoot = Environment.getOemDirectory();
7739        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7740            codeRoot = Environment.getVendorDirectory();
7741        } else {
7742            // Unrecognized code path; take its top real segment as the apk root:
7743            // e.g. /something/app/blah.apk => /something
7744            try {
7745                File f = codePath.getCanonicalFile();
7746                File parent = f.getParentFile();    // non-null because codePath is a file
7747                File tmp;
7748                while ((tmp = parent.getParentFile()) != null) {
7749                    f = parent;
7750                    parent = tmp;
7751                }
7752                codeRoot = f;
7753                Slog.w(TAG, "Unrecognized code path "
7754                        + codePath + " - using " + codeRoot);
7755            } catch (IOException e) {
7756                // Can't canonicalize the code path -- shenanigans?
7757                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7758                return Environment.getRootDirectory().getPath();
7759            }
7760        }
7761        return codeRoot.getPath();
7762    }
7763
7764    /**
7765     * Derive and set the location of native libraries for the given package,
7766     * which varies depending on where and how the package was installed.
7767     */
7768    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7769        final ApplicationInfo info = pkg.applicationInfo;
7770        final String codePath = pkg.codePath;
7771        final File codeFile = new File(codePath);
7772        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7773        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7774
7775        info.nativeLibraryRootDir = null;
7776        info.nativeLibraryRootRequiresIsa = false;
7777        info.nativeLibraryDir = null;
7778        info.secondaryNativeLibraryDir = null;
7779
7780        if (isApkFile(codeFile)) {
7781            // Monolithic install
7782            if (bundledApp) {
7783                // If "/system/lib64/apkname" exists, assume that is the per-package
7784                // native library directory to use; otherwise use "/system/lib/apkname".
7785                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7786                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7787                        getPrimaryInstructionSet(info));
7788
7789                // This is a bundled system app so choose the path based on the ABI.
7790                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7791                // is just the default path.
7792                final String apkName = deriveCodePathName(codePath);
7793                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7794                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7795                        apkName).getAbsolutePath();
7796
7797                if (info.secondaryCpuAbi != null) {
7798                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7799                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7800                            secondaryLibDir, apkName).getAbsolutePath();
7801                }
7802            } else if (asecApp) {
7803                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7804                        .getAbsolutePath();
7805            } else {
7806                final String apkName = deriveCodePathName(codePath);
7807                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7808                        .getAbsolutePath();
7809            }
7810
7811            info.nativeLibraryRootRequiresIsa = false;
7812            info.nativeLibraryDir = info.nativeLibraryRootDir;
7813        } else {
7814            // Cluster install
7815            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7816            info.nativeLibraryRootRequiresIsa = true;
7817
7818            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7819                    getPrimaryInstructionSet(info)).getAbsolutePath();
7820
7821            if (info.secondaryCpuAbi != null) {
7822                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7823                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7824            }
7825        }
7826    }
7827
7828    /**
7829     * Calculate the abis and roots for a bundled app. These can uniquely
7830     * be determined from the contents of the system partition, i.e whether
7831     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7832     * of this information, and instead assume that the system was built
7833     * sensibly.
7834     */
7835    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7836                                           PackageSetting pkgSetting) {
7837        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7838
7839        // If "/system/lib64/apkname" exists, assume that is the per-package
7840        // native library directory to use; otherwise use "/system/lib/apkname".
7841        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7842        setBundledAppAbi(pkg, apkRoot, apkName);
7843        // pkgSetting might be null during rescan following uninstall of updates
7844        // to a bundled app, so accommodate that possibility.  The settings in
7845        // that case will be established later from the parsed package.
7846        //
7847        // If the settings aren't null, sync them up with what we've just derived.
7848        // note that apkRoot isn't stored in the package settings.
7849        if (pkgSetting != null) {
7850            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7851            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7852        }
7853    }
7854
7855    /**
7856     * Deduces the ABI of a bundled app and sets the relevant fields on the
7857     * parsed pkg object.
7858     *
7859     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7860     *        under which system libraries are installed.
7861     * @param apkName the name of the installed package.
7862     */
7863    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7864        final File codeFile = new File(pkg.codePath);
7865
7866        final boolean has64BitLibs;
7867        final boolean has32BitLibs;
7868        if (isApkFile(codeFile)) {
7869            // Monolithic install
7870            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7871            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7872        } else {
7873            // Cluster install
7874            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7875            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7876                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7877                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7878                has64BitLibs = (new File(rootDir, isa)).exists();
7879            } else {
7880                has64BitLibs = false;
7881            }
7882            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7883                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7884                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7885                has32BitLibs = (new File(rootDir, isa)).exists();
7886            } else {
7887                has32BitLibs = false;
7888            }
7889        }
7890
7891        if (has64BitLibs && !has32BitLibs) {
7892            // The package has 64 bit libs, but not 32 bit libs. Its primary
7893            // ABI should be 64 bit. We can safely assume here that the bundled
7894            // native libraries correspond to the most preferred ABI in the list.
7895
7896            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7897            pkg.applicationInfo.secondaryCpuAbi = null;
7898        } else if (has32BitLibs && !has64BitLibs) {
7899            // The package has 32 bit libs but not 64 bit libs. Its primary
7900            // ABI should be 32 bit.
7901
7902            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7903            pkg.applicationInfo.secondaryCpuAbi = null;
7904        } else if (has32BitLibs && has64BitLibs) {
7905            // The application has both 64 and 32 bit bundled libraries. We check
7906            // here that the app declares multiArch support, and warn if it doesn't.
7907            //
7908            // We will be lenient here and record both ABIs. The primary will be the
7909            // ABI that's higher on the list, i.e, a device that's configured to prefer
7910            // 64 bit apps will see a 64 bit primary ABI,
7911
7912            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7913                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7914            }
7915
7916            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7917                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7918                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7919            } else {
7920                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7921                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7922            }
7923        } else {
7924            pkg.applicationInfo.primaryCpuAbi = null;
7925            pkg.applicationInfo.secondaryCpuAbi = null;
7926        }
7927    }
7928
7929    private void killApplication(String pkgName, int appId, String reason) {
7930        // Request the ActivityManager to kill the process(only for existing packages)
7931        // so that we do not end up in a confused state while the user is still using the older
7932        // version of the application while the new one gets installed.
7933        IActivityManager am = ActivityManagerNative.getDefault();
7934        if (am != null) {
7935            try {
7936                am.killApplicationWithAppId(pkgName, appId, reason);
7937            } catch (RemoteException e) {
7938            }
7939        }
7940    }
7941
7942    void removePackageLI(PackageSetting ps, boolean chatty) {
7943        if (DEBUG_INSTALL) {
7944            if (chatty)
7945                Log.d(TAG, "Removing package " + ps.name);
7946        }
7947
7948        // writer
7949        synchronized (mPackages) {
7950            mPackages.remove(ps.name);
7951            final PackageParser.Package pkg = ps.pkg;
7952            if (pkg != null) {
7953                cleanPackageDataStructuresLILPw(pkg, chatty);
7954            }
7955        }
7956    }
7957
7958    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7959        if (DEBUG_INSTALL) {
7960            if (chatty)
7961                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7962        }
7963
7964        // writer
7965        synchronized (mPackages) {
7966            mPackages.remove(pkg.applicationInfo.packageName);
7967            cleanPackageDataStructuresLILPw(pkg, chatty);
7968        }
7969    }
7970
7971    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7972        int N = pkg.providers.size();
7973        StringBuilder r = null;
7974        int i;
7975        for (i=0; i<N; i++) {
7976            PackageParser.Provider p = pkg.providers.get(i);
7977            mProviders.removeProvider(p);
7978            if (p.info.authority == null) {
7979
7980                /* There was another ContentProvider with this authority when
7981                 * this app was installed so this authority is null,
7982                 * Ignore it as we don't have to unregister the provider.
7983                 */
7984                continue;
7985            }
7986            String names[] = p.info.authority.split(";");
7987            for (int j = 0; j < names.length; j++) {
7988                if (mProvidersByAuthority.get(names[j]) == p) {
7989                    mProvidersByAuthority.remove(names[j]);
7990                    if (DEBUG_REMOVE) {
7991                        if (chatty)
7992                            Log.d(TAG, "Unregistered content provider: " + names[j]
7993                                    + ", className = " + p.info.name + ", isSyncable = "
7994                                    + p.info.isSyncable);
7995                    }
7996                }
7997            }
7998            if (DEBUG_REMOVE && chatty) {
7999                if (r == null) {
8000                    r = new StringBuilder(256);
8001                } else {
8002                    r.append(' ');
8003                }
8004                r.append(p.info.name);
8005            }
8006        }
8007        if (r != null) {
8008            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8009        }
8010
8011        N = pkg.services.size();
8012        r = null;
8013        for (i=0; i<N; i++) {
8014            PackageParser.Service s = pkg.services.get(i);
8015            mServices.removeService(s);
8016            if (chatty) {
8017                if (r == null) {
8018                    r = new StringBuilder(256);
8019                } else {
8020                    r.append(' ');
8021                }
8022                r.append(s.info.name);
8023            }
8024        }
8025        if (r != null) {
8026            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8027        }
8028
8029        N = pkg.receivers.size();
8030        r = null;
8031        for (i=0; i<N; i++) {
8032            PackageParser.Activity a = pkg.receivers.get(i);
8033            mReceivers.removeActivity(a, "receiver");
8034            if (DEBUG_REMOVE && chatty) {
8035                if (r == null) {
8036                    r = new StringBuilder(256);
8037                } else {
8038                    r.append(' ');
8039                }
8040                r.append(a.info.name);
8041            }
8042        }
8043        if (r != null) {
8044            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8045        }
8046
8047        N = pkg.activities.size();
8048        r = null;
8049        for (i=0; i<N; i++) {
8050            PackageParser.Activity a = pkg.activities.get(i);
8051            mActivities.removeActivity(a, "activity");
8052            if (DEBUG_REMOVE && chatty) {
8053                if (r == null) {
8054                    r = new StringBuilder(256);
8055                } else {
8056                    r.append(' ');
8057                }
8058                r.append(a.info.name);
8059            }
8060        }
8061        if (r != null) {
8062            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8063        }
8064
8065        N = pkg.permissions.size();
8066        r = null;
8067        for (i=0; i<N; i++) {
8068            PackageParser.Permission p = pkg.permissions.get(i);
8069            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8070            if (bp == null) {
8071                bp = mSettings.mPermissionTrees.get(p.info.name);
8072            }
8073            if (bp != null && bp.perm == p) {
8074                bp.perm = null;
8075                if (DEBUG_REMOVE && chatty) {
8076                    if (r == null) {
8077                        r = new StringBuilder(256);
8078                    } else {
8079                        r.append(' ');
8080                    }
8081                    r.append(p.info.name);
8082                }
8083            }
8084            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8085                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8086                if (appOpPerms != null) {
8087                    appOpPerms.remove(pkg.packageName);
8088                }
8089            }
8090        }
8091        if (r != null) {
8092            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8093        }
8094
8095        N = pkg.requestedPermissions.size();
8096        r = null;
8097        for (i=0; i<N; i++) {
8098            String perm = pkg.requestedPermissions.get(i);
8099            BasePermission bp = mSettings.mPermissions.get(perm);
8100            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8101                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8102                if (appOpPerms != null) {
8103                    appOpPerms.remove(pkg.packageName);
8104                    if (appOpPerms.isEmpty()) {
8105                        mAppOpPermissionPackages.remove(perm);
8106                    }
8107                }
8108            }
8109        }
8110        if (r != null) {
8111            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8112        }
8113
8114        N = pkg.instrumentation.size();
8115        r = null;
8116        for (i=0; i<N; i++) {
8117            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8118            mInstrumentation.remove(a.getComponentName());
8119            if (DEBUG_REMOVE && chatty) {
8120                if (r == null) {
8121                    r = new StringBuilder(256);
8122                } else {
8123                    r.append(' ');
8124                }
8125                r.append(a.info.name);
8126            }
8127        }
8128        if (r != null) {
8129            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8130        }
8131
8132        r = null;
8133        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8134            // Only system apps can hold shared libraries.
8135            if (pkg.libraryNames != null) {
8136                for (i=0; i<pkg.libraryNames.size(); i++) {
8137                    String name = pkg.libraryNames.get(i);
8138                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8139                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8140                        mSharedLibraries.remove(name);
8141                        if (DEBUG_REMOVE && chatty) {
8142                            if (r == null) {
8143                                r = new StringBuilder(256);
8144                            } else {
8145                                r.append(' ');
8146                            }
8147                            r.append(name);
8148                        }
8149                    }
8150                }
8151            }
8152        }
8153        if (r != null) {
8154            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8155        }
8156    }
8157
8158    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8159        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8160            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8161                return true;
8162            }
8163        }
8164        return false;
8165    }
8166
8167    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8168    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8169    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8170
8171    private void updatePermissionsLPw(String changingPkg,
8172            PackageParser.Package pkgInfo, int flags) {
8173        // Make sure there are no dangling permission trees.
8174        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8175        while (it.hasNext()) {
8176            final BasePermission bp = it.next();
8177            if (bp.packageSetting == null) {
8178                // We may not yet have parsed the package, so just see if
8179                // we still know about its settings.
8180                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8181            }
8182            if (bp.packageSetting == null) {
8183                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8184                        + " from package " + bp.sourcePackage);
8185                it.remove();
8186            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8187                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8188                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8189                            + " from package " + bp.sourcePackage);
8190                    flags |= UPDATE_PERMISSIONS_ALL;
8191                    it.remove();
8192                }
8193            }
8194        }
8195
8196        // Make sure all dynamic permissions have been assigned to a package,
8197        // and make sure there are no dangling permissions.
8198        it = mSettings.mPermissions.values().iterator();
8199        while (it.hasNext()) {
8200            final BasePermission bp = it.next();
8201            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8202                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8203                        + bp.name + " pkg=" + bp.sourcePackage
8204                        + " info=" + bp.pendingInfo);
8205                if (bp.packageSetting == null && bp.pendingInfo != null) {
8206                    final BasePermission tree = findPermissionTreeLP(bp.name);
8207                    if (tree != null && tree.perm != null) {
8208                        bp.packageSetting = tree.packageSetting;
8209                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8210                                new PermissionInfo(bp.pendingInfo));
8211                        bp.perm.info.packageName = tree.perm.info.packageName;
8212                        bp.perm.info.name = bp.name;
8213                        bp.uid = tree.uid;
8214                    }
8215                }
8216            }
8217            if (bp.packageSetting == null) {
8218                // We may not yet have parsed the package, so just see if
8219                // we still know about its settings.
8220                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8221            }
8222            if (bp.packageSetting == null) {
8223                Slog.w(TAG, "Removing dangling permission: " + bp.name
8224                        + " from package " + bp.sourcePackage);
8225                it.remove();
8226            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8227                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8228                    Slog.i(TAG, "Removing old permission: " + bp.name
8229                            + " from package " + bp.sourcePackage);
8230                    flags |= UPDATE_PERMISSIONS_ALL;
8231                    it.remove();
8232                }
8233            }
8234        }
8235
8236        // Now update the permissions for all packages, in particular
8237        // replace the granted permissions of the system packages.
8238        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8239            for (PackageParser.Package pkg : mPackages.values()) {
8240                if (pkg != pkgInfo) {
8241                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8242                            changingPkg);
8243                }
8244            }
8245        }
8246
8247        if (pkgInfo != null) {
8248            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8249        }
8250    }
8251
8252    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8253            String packageOfInterest) {
8254        // IMPORTANT: There are two types of permissions: install and runtime.
8255        // Install time permissions are granted when the app is installed to
8256        // all device users and users added in the future. Runtime permissions
8257        // are granted at runtime explicitly to specific users. Normal and signature
8258        // protected permissions are install time permissions. Dangerous permissions
8259        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8260        // otherwise they are runtime permissions. This function does not manage
8261        // runtime permissions except for the case an app targeting Lollipop MR1
8262        // being upgraded to target a newer SDK, in which case dangerous permissions
8263        // are transformed from install time to runtime ones.
8264
8265        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8266        if (ps == null) {
8267            return;
8268        }
8269
8270        PermissionsState permissionsState = ps.getPermissionsState();
8271        PermissionsState origPermissions = permissionsState;
8272
8273        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8274
8275        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8276
8277        boolean changedInstallPermission = false;
8278
8279        if (replace) {
8280            ps.installPermissionsFixed = false;
8281            if (!ps.isSharedUser()) {
8282                origPermissions = new PermissionsState(permissionsState);
8283                permissionsState.reset();
8284            }
8285        }
8286
8287        permissionsState.setGlobalGids(mGlobalGids);
8288
8289        final int N = pkg.requestedPermissions.size();
8290        for (int i=0; i<N; i++) {
8291            final String name = pkg.requestedPermissions.get(i);
8292            final BasePermission bp = mSettings.mPermissions.get(name);
8293
8294            if (DEBUG_INSTALL) {
8295                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8296            }
8297
8298            if (bp == null || bp.packageSetting == null) {
8299                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8300                    Slog.w(TAG, "Unknown permission " + name
8301                            + " in package " + pkg.packageName);
8302                }
8303                continue;
8304            }
8305
8306            final String perm = bp.name;
8307            boolean allowedSig = false;
8308            int grant = GRANT_DENIED;
8309
8310            // Keep track of app op permissions.
8311            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8312                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8313                if (pkgs == null) {
8314                    pkgs = new ArraySet<>();
8315                    mAppOpPermissionPackages.put(bp.name, pkgs);
8316                }
8317                pkgs.add(pkg.packageName);
8318            }
8319
8320            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8321            switch (level) {
8322                case PermissionInfo.PROTECTION_NORMAL: {
8323                    // For all apps normal permissions are install time ones.
8324                    grant = GRANT_INSTALL;
8325                } break;
8326
8327                case PermissionInfo.PROTECTION_DANGEROUS: {
8328                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8329                        // For legacy apps dangerous permissions are install time ones.
8330                        grant = GRANT_INSTALL_LEGACY;
8331                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8332                        // For legacy apps that became modern, install becomes runtime.
8333                        grant = GRANT_UPGRADE;
8334                    } else {
8335                        // For modern apps keep runtime permissions unchanged.
8336                        grant = GRANT_RUNTIME;
8337                    }
8338                } break;
8339
8340                case PermissionInfo.PROTECTION_SIGNATURE: {
8341                    // For all apps signature permissions are install time ones.
8342                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8343                    if (allowedSig) {
8344                        grant = GRANT_INSTALL;
8345                    }
8346                } break;
8347            }
8348
8349            if (DEBUG_INSTALL) {
8350                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8351            }
8352
8353            if (grant != GRANT_DENIED) {
8354                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8355                    // If this is an existing, non-system package, then
8356                    // we can't add any new permissions to it.
8357                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8358                        // Except...  if this is a permission that was added
8359                        // to the platform (note: need to only do this when
8360                        // updating the platform).
8361                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8362                            grant = GRANT_DENIED;
8363                        }
8364                    }
8365                }
8366
8367                switch (grant) {
8368                    case GRANT_INSTALL: {
8369                        // Revoke this as runtime permission to handle the case of
8370                        // a runtime permission being downgraded to an install one.
8371                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8372                            if (origPermissions.getRuntimePermissionState(
8373                                    bp.name, userId) != null) {
8374                                // Revoke the runtime permission and clear the flags.
8375                                origPermissions.revokeRuntimePermission(bp, userId);
8376                                origPermissions.updatePermissionFlags(bp, userId,
8377                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8378                                // If we revoked a permission permission, we have to write.
8379                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8380                                        changedRuntimePermissionUserIds, userId);
8381                            }
8382                        }
8383                        // Grant an install permission.
8384                        if (permissionsState.grantInstallPermission(bp) !=
8385                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8386                            changedInstallPermission = true;
8387                        }
8388                    } break;
8389
8390                    case GRANT_INSTALL_LEGACY: {
8391                        // Grant an install permission.
8392                        if (permissionsState.grantInstallPermission(bp) !=
8393                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8394                            changedInstallPermission = true;
8395                        }
8396                    } break;
8397
8398                    case GRANT_RUNTIME: {
8399                        // Grant previously granted runtime permissions.
8400                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8401                            PermissionState permissionState = origPermissions
8402                                    .getRuntimePermissionState(bp.name, userId);
8403                            final int flags = permissionState != null
8404                                    ? permissionState.getFlags() : 0;
8405                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8406                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8407                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8408                                    // If we cannot put the permission as it was, we have to write.
8409                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8410                                            changedRuntimePermissionUserIds, userId);
8411                                }
8412                            }
8413                            // Propagate the permission flags.
8414                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8415                        }
8416                    } break;
8417
8418                    case GRANT_UPGRADE: {
8419                        // Grant runtime permissions for a previously held install permission.
8420                        PermissionState permissionState = origPermissions
8421                                .getInstallPermissionState(bp.name);
8422                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8423
8424                        if (origPermissions.revokeInstallPermission(bp)
8425                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8426                            // We will be transferring the permission flags, so clear them.
8427                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8428                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8429                            changedInstallPermission = true;
8430                        }
8431
8432                        // If the permission is not to be promoted to runtime we ignore it and
8433                        // also its other flags as they are not applicable to install permissions.
8434                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8435                            for (int userId : currentUserIds) {
8436                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8437                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8438                                    // Transfer the permission flags.
8439                                    permissionsState.updatePermissionFlags(bp, userId,
8440                                            flags, flags);
8441                                    // If we granted the permission, we have to write.
8442                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8443                                            changedRuntimePermissionUserIds, userId);
8444                                }
8445                            }
8446                        }
8447                    } break;
8448
8449                    default: {
8450                        if (packageOfInterest == null
8451                                || packageOfInterest.equals(pkg.packageName)) {
8452                            Slog.w(TAG, "Not granting permission " + perm
8453                                    + " to package " + pkg.packageName
8454                                    + " because it was previously installed without");
8455                        }
8456                    } break;
8457                }
8458            } else {
8459                if (permissionsState.revokeInstallPermission(bp) !=
8460                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8461                    // Also drop the permission flags.
8462                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8463                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8464                    changedInstallPermission = true;
8465                    Slog.i(TAG, "Un-granting permission " + perm
8466                            + " from package " + pkg.packageName
8467                            + " (protectionLevel=" + bp.protectionLevel
8468                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8469                            + ")");
8470                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8471                    // Don't print warning for app op permissions, since it is fine for them
8472                    // not to be granted, there is a UI for the user to decide.
8473                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8474                        Slog.w(TAG, "Not granting permission " + perm
8475                                + " to package " + pkg.packageName
8476                                + " (protectionLevel=" + bp.protectionLevel
8477                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8478                                + ")");
8479                    }
8480                }
8481            }
8482        }
8483
8484        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8485                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8486            // This is the first that we have heard about this package, so the
8487            // permissions we have now selected are fixed until explicitly
8488            // changed.
8489            ps.installPermissionsFixed = true;
8490        }
8491
8492        // Persist the runtime permissions state for users with changes.
8493        for (int userId : changedRuntimePermissionUserIds) {
8494            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8495        }
8496    }
8497
8498    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8499        boolean allowed = false;
8500        final int NP = PackageParser.NEW_PERMISSIONS.length;
8501        for (int ip=0; ip<NP; ip++) {
8502            final PackageParser.NewPermissionInfo npi
8503                    = PackageParser.NEW_PERMISSIONS[ip];
8504            if (npi.name.equals(perm)
8505                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8506                allowed = true;
8507                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8508                        + pkg.packageName);
8509                break;
8510            }
8511        }
8512        return allowed;
8513    }
8514
8515    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8516            BasePermission bp, PermissionsState origPermissions) {
8517        boolean allowed;
8518        allowed = (compareSignatures(
8519                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8520                        == PackageManager.SIGNATURE_MATCH)
8521                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8522                        == PackageManager.SIGNATURE_MATCH);
8523        if (!allowed && (bp.protectionLevel
8524                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8525            if (isSystemApp(pkg)) {
8526                // For updated system applications, a system permission
8527                // is granted only if it had been defined by the original application.
8528                if (pkg.isUpdatedSystemApp()) {
8529                    final PackageSetting sysPs = mSettings
8530                            .getDisabledSystemPkgLPr(pkg.packageName);
8531                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8532                        // If the original was granted this permission, we take
8533                        // that grant decision as read and propagate it to the
8534                        // update.
8535                        if (sysPs.isPrivileged()) {
8536                            allowed = true;
8537                        }
8538                    } else {
8539                        // The system apk may have been updated with an older
8540                        // version of the one on the data partition, but which
8541                        // granted a new system permission that it didn't have
8542                        // before.  In this case we do want to allow the app to
8543                        // now get the new permission if the ancestral apk is
8544                        // privileged to get it.
8545                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8546                            for (int j=0;
8547                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8548                                if (perm.equals(
8549                                        sysPs.pkg.requestedPermissions.get(j))) {
8550                                    allowed = true;
8551                                    break;
8552                                }
8553                            }
8554                        }
8555                    }
8556                } else {
8557                    allowed = isPrivilegedApp(pkg);
8558                }
8559            }
8560        }
8561        if (!allowed) {
8562            if (!allowed && (bp.protectionLevel
8563                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8564                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8565                // If this was a previously normal/dangerous permission that got moved
8566                // to a system permission as part of the runtime permission redesign, then
8567                // we still want to blindly grant it to old apps.
8568                allowed = true;
8569            }
8570            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8571                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8572                // If this permission is to be granted to the system installer and
8573                // this app is an installer, then it gets the permission.
8574                allowed = true;
8575            }
8576            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8577                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8578                // If this permission is to be granted to the system verifier and
8579                // this app is a verifier, then it gets the permission.
8580                allowed = true;
8581            }
8582            if (!allowed && (bp.protectionLevel
8583                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8584                    && isSystemApp(pkg)) {
8585                // Any pre-installed system app is allowed to get this permission.
8586                allowed = true;
8587            }
8588            if (!allowed && (bp.protectionLevel
8589                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8590                // For development permissions, a development permission
8591                // is granted only if it was already granted.
8592                allowed = origPermissions.hasInstallPermission(perm);
8593            }
8594        }
8595        return allowed;
8596    }
8597
8598    final class ActivityIntentResolver
8599            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8600        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8601                boolean defaultOnly, int userId) {
8602            if (!sUserManager.exists(userId)) return null;
8603            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8604            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8605        }
8606
8607        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8608                int userId) {
8609            if (!sUserManager.exists(userId)) return null;
8610            mFlags = flags;
8611            return super.queryIntent(intent, resolvedType,
8612                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8613        }
8614
8615        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8616                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8617            if (!sUserManager.exists(userId)) return null;
8618            if (packageActivities == null) {
8619                return null;
8620            }
8621            mFlags = flags;
8622            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8623            final int N = packageActivities.size();
8624            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8625                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8626
8627            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8628            for (int i = 0; i < N; ++i) {
8629                intentFilters = packageActivities.get(i).intents;
8630                if (intentFilters != null && intentFilters.size() > 0) {
8631                    PackageParser.ActivityIntentInfo[] array =
8632                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8633                    intentFilters.toArray(array);
8634                    listCut.add(array);
8635                }
8636            }
8637            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8638        }
8639
8640        public final void addActivity(PackageParser.Activity a, String type) {
8641            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8642            mActivities.put(a.getComponentName(), a);
8643            if (DEBUG_SHOW_INFO)
8644                Log.v(
8645                TAG, "  " + type + " " +
8646                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8647            if (DEBUG_SHOW_INFO)
8648                Log.v(TAG, "    Class=" + a.info.name);
8649            final int NI = a.intents.size();
8650            for (int j=0; j<NI; j++) {
8651                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8652                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8653                    intent.setPriority(0);
8654                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8655                            + a.className + " with priority > 0, forcing to 0");
8656                }
8657                if (DEBUG_SHOW_INFO) {
8658                    Log.v(TAG, "    IntentFilter:");
8659                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8660                }
8661                if (!intent.debugCheck()) {
8662                    Log.w(TAG, "==> For Activity " + a.info.name);
8663                }
8664                addFilter(intent);
8665            }
8666        }
8667
8668        public final void removeActivity(PackageParser.Activity a, String type) {
8669            mActivities.remove(a.getComponentName());
8670            if (DEBUG_SHOW_INFO) {
8671                Log.v(TAG, "  " + type + " "
8672                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8673                                : a.info.name) + ":");
8674                Log.v(TAG, "    Class=" + a.info.name);
8675            }
8676            final int NI = a.intents.size();
8677            for (int j=0; j<NI; j++) {
8678                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8679                if (DEBUG_SHOW_INFO) {
8680                    Log.v(TAG, "    IntentFilter:");
8681                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8682                }
8683                removeFilter(intent);
8684            }
8685        }
8686
8687        @Override
8688        protected boolean allowFilterResult(
8689                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8690            ActivityInfo filterAi = filter.activity.info;
8691            for (int i=dest.size()-1; i>=0; i--) {
8692                ActivityInfo destAi = dest.get(i).activityInfo;
8693                if (destAi.name == filterAi.name
8694                        && destAi.packageName == filterAi.packageName) {
8695                    return false;
8696                }
8697            }
8698            return true;
8699        }
8700
8701        @Override
8702        protected ActivityIntentInfo[] newArray(int size) {
8703            return new ActivityIntentInfo[size];
8704        }
8705
8706        @Override
8707        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8708            if (!sUserManager.exists(userId)) return true;
8709            PackageParser.Package p = filter.activity.owner;
8710            if (p != null) {
8711                PackageSetting ps = (PackageSetting)p.mExtras;
8712                if (ps != null) {
8713                    // System apps are never considered stopped for purposes of
8714                    // filtering, because there may be no way for the user to
8715                    // actually re-launch them.
8716                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8717                            && ps.getStopped(userId);
8718                }
8719            }
8720            return false;
8721        }
8722
8723        @Override
8724        protected boolean isPackageForFilter(String packageName,
8725                PackageParser.ActivityIntentInfo info) {
8726            return packageName.equals(info.activity.owner.packageName);
8727        }
8728
8729        @Override
8730        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8731                int match, int userId) {
8732            if (!sUserManager.exists(userId)) return null;
8733            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8734                return null;
8735            }
8736            final PackageParser.Activity activity = info.activity;
8737            if (mSafeMode && (activity.info.applicationInfo.flags
8738                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8739                return null;
8740            }
8741            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8742            if (ps == null) {
8743                return null;
8744            }
8745            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8746                    ps.readUserState(userId), userId);
8747            if (ai == null) {
8748                return null;
8749            }
8750            final ResolveInfo res = new ResolveInfo();
8751            res.activityInfo = ai;
8752            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8753                res.filter = info;
8754            }
8755            if (info != null) {
8756                res.handleAllWebDataURI = info.handleAllWebDataURI();
8757            }
8758            res.priority = info.getPriority();
8759            res.preferredOrder = activity.owner.mPreferredOrder;
8760            //System.out.println("Result: " + res.activityInfo.className +
8761            //                   " = " + res.priority);
8762            res.match = match;
8763            res.isDefault = info.hasDefault;
8764            res.labelRes = info.labelRes;
8765            res.nonLocalizedLabel = info.nonLocalizedLabel;
8766            if (userNeedsBadging(userId)) {
8767                res.noResourceId = true;
8768            } else {
8769                res.icon = info.icon;
8770            }
8771            res.iconResourceId = info.icon;
8772            res.system = res.activityInfo.applicationInfo.isSystemApp();
8773            return res;
8774        }
8775
8776        @Override
8777        protected void sortResults(List<ResolveInfo> results) {
8778            Collections.sort(results, mResolvePrioritySorter);
8779        }
8780
8781        @Override
8782        protected void dumpFilter(PrintWriter out, String prefix,
8783                PackageParser.ActivityIntentInfo filter) {
8784            out.print(prefix); out.print(
8785                    Integer.toHexString(System.identityHashCode(filter.activity)));
8786                    out.print(' ');
8787                    filter.activity.printComponentShortName(out);
8788                    out.print(" filter ");
8789                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8790        }
8791
8792        @Override
8793        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8794            return filter.activity;
8795        }
8796
8797        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8798            PackageParser.Activity activity = (PackageParser.Activity)label;
8799            out.print(prefix); out.print(
8800                    Integer.toHexString(System.identityHashCode(activity)));
8801                    out.print(' ');
8802                    activity.printComponentShortName(out);
8803            if (count > 1) {
8804                out.print(" ("); out.print(count); out.print(" filters)");
8805            }
8806            out.println();
8807        }
8808
8809//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8810//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8811//            final List<ResolveInfo> retList = Lists.newArrayList();
8812//            while (i.hasNext()) {
8813//                final ResolveInfo resolveInfo = i.next();
8814//                if (isEnabledLP(resolveInfo.activityInfo)) {
8815//                    retList.add(resolveInfo);
8816//                }
8817//            }
8818//            return retList;
8819//        }
8820
8821        // Keys are String (activity class name), values are Activity.
8822        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8823                = new ArrayMap<ComponentName, PackageParser.Activity>();
8824        private int mFlags;
8825    }
8826
8827    private final class ServiceIntentResolver
8828            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8829        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8830                boolean defaultOnly, int userId) {
8831            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8832            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8833        }
8834
8835        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8836                int userId) {
8837            if (!sUserManager.exists(userId)) return null;
8838            mFlags = flags;
8839            return super.queryIntent(intent, resolvedType,
8840                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8841        }
8842
8843        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8844                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8845            if (!sUserManager.exists(userId)) return null;
8846            if (packageServices == null) {
8847                return null;
8848            }
8849            mFlags = flags;
8850            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8851            final int N = packageServices.size();
8852            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8853                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8854
8855            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8856            for (int i = 0; i < N; ++i) {
8857                intentFilters = packageServices.get(i).intents;
8858                if (intentFilters != null && intentFilters.size() > 0) {
8859                    PackageParser.ServiceIntentInfo[] array =
8860                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8861                    intentFilters.toArray(array);
8862                    listCut.add(array);
8863                }
8864            }
8865            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8866        }
8867
8868        public final void addService(PackageParser.Service s) {
8869            mServices.put(s.getComponentName(), s);
8870            if (DEBUG_SHOW_INFO) {
8871                Log.v(TAG, "  "
8872                        + (s.info.nonLocalizedLabel != null
8873                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8874                Log.v(TAG, "    Class=" + s.info.name);
8875            }
8876            final int NI = s.intents.size();
8877            int j;
8878            for (j=0; j<NI; j++) {
8879                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8880                if (DEBUG_SHOW_INFO) {
8881                    Log.v(TAG, "    IntentFilter:");
8882                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8883                }
8884                if (!intent.debugCheck()) {
8885                    Log.w(TAG, "==> For Service " + s.info.name);
8886                }
8887                addFilter(intent);
8888            }
8889        }
8890
8891        public final void removeService(PackageParser.Service s) {
8892            mServices.remove(s.getComponentName());
8893            if (DEBUG_SHOW_INFO) {
8894                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8895                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8896                Log.v(TAG, "    Class=" + s.info.name);
8897            }
8898            final int NI = s.intents.size();
8899            int j;
8900            for (j=0; j<NI; j++) {
8901                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8902                if (DEBUG_SHOW_INFO) {
8903                    Log.v(TAG, "    IntentFilter:");
8904                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8905                }
8906                removeFilter(intent);
8907            }
8908        }
8909
8910        @Override
8911        protected boolean allowFilterResult(
8912                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8913            ServiceInfo filterSi = filter.service.info;
8914            for (int i=dest.size()-1; i>=0; i--) {
8915                ServiceInfo destAi = dest.get(i).serviceInfo;
8916                if (destAi.name == filterSi.name
8917                        && destAi.packageName == filterSi.packageName) {
8918                    return false;
8919                }
8920            }
8921            return true;
8922        }
8923
8924        @Override
8925        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8926            return new PackageParser.ServiceIntentInfo[size];
8927        }
8928
8929        @Override
8930        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8931            if (!sUserManager.exists(userId)) return true;
8932            PackageParser.Package p = filter.service.owner;
8933            if (p != null) {
8934                PackageSetting ps = (PackageSetting)p.mExtras;
8935                if (ps != null) {
8936                    // System apps are never considered stopped for purposes of
8937                    // filtering, because there may be no way for the user to
8938                    // actually re-launch them.
8939                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8940                            && ps.getStopped(userId);
8941                }
8942            }
8943            return false;
8944        }
8945
8946        @Override
8947        protected boolean isPackageForFilter(String packageName,
8948                PackageParser.ServiceIntentInfo info) {
8949            return packageName.equals(info.service.owner.packageName);
8950        }
8951
8952        @Override
8953        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8954                int match, int userId) {
8955            if (!sUserManager.exists(userId)) return null;
8956            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8957            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8958                return null;
8959            }
8960            final PackageParser.Service service = info.service;
8961            if (mSafeMode && (service.info.applicationInfo.flags
8962                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8963                return null;
8964            }
8965            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8966            if (ps == null) {
8967                return null;
8968            }
8969            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8970                    ps.readUserState(userId), userId);
8971            if (si == null) {
8972                return null;
8973            }
8974            final ResolveInfo res = new ResolveInfo();
8975            res.serviceInfo = si;
8976            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8977                res.filter = filter;
8978            }
8979            res.priority = info.getPriority();
8980            res.preferredOrder = service.owner.mPreferredOrder;
8981            res.match = match;
8982            res.isDefault = info.hasDefault;
8983            res.labelRes = info.labelRes;
8984            res.nonLocalizedLabel = info.nonLocalizedLabel;
8985            res.icon = info.icon;
8986            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8987            return res;
8988        }
8989
8990        @Override
8991        protected void sortResults(List<ResolveInfo> results) {
8992            Collections.sort(results, mResolvePrioritySorter);
8993        }
8994
8995        @Override
8996        protected void dumpFilter(PrintWriter out, String prefix,
8997                PackageParser.ServiceIntentInfo filter) {
8998            out.print(prefix); out.print(
8999                    Integer.toHexString(System.identityHashCode(filter.service)));
9000                    out.print(' ');
9001                    filter.service.printComponentShortName(out);
9002                    out.print(" filter ");
9003                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9004        }
9005
9006        @Override
9007        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9008            return filter.service;
9009        }
9010
9011        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9012            PackageParser.Service service = (PackageParser.Service)label;
9013            out.print(prefix); out.print(
9014                    Integer.toHexString(System.identityHashCode(service)));
9015                    out.print(' ');
9016                    service.printComponentShortName(out);
9017            if (count > 1) {
9018                out.print(" ("); out.print(count); out.print(" filters)");
9019            }
9020            out.println();
9021        }
9022
9023//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9024//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9025//            final List<ResolveInfo> retList = Lists.newArrayList();
9026//            while (i.hasNext()) {
9027//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9028//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9029//                    retList.add(resolveInfo);
9030//                }
9031//            }
9032//            return retList;
9033//        }
9034
9035        // Keys are String (activity class name), values are Activity.
9036        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9037                = new ArrayMap<ComponentName, PackageParser.Service>();
9038        private int mFlags;
9039    };
9040
9041    private final class ProviderIntentResolver
9042            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9043        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9044                boolean defaultOnly, int userId) {
9045            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9046            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9047        }
9048
9049        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9050                int userId) {
9051            if (!sUserManager.exists(userId))
9052                return null;
9053            mFlags = flags;
9054            return super.queryIntent(intent, resolvedType,
9055                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9056        }
9057
9058        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9059                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9060            if (!sUserManager.exists(userId))
9061                return null;
9062            if (packageProviders == null) {
9063                return null;
9064            }
9065            mFlags = flags;
9066            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9067            final int N = packageProviders.size();
9068            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9069                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9070
9071            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9072            for (int i = 0; i < N; ++i) {
9073                intentFilters = packageProviders.get(i).intents;
9074                if (intentFilters != null && intentFilters.size() > 0) {
9075                    PackageParser.ProviderIntentInfo[] array =
9076                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9077                    intentFilters.toArray(array);
9078                    listCut.add(array);
9079                }
9080            }
9081            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9082        }
9083
9084        public final void addProvider(PackageParser.Provider p) {
9085            if (mProviders.containsKey(p.getComponentName())) {
9086                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9087                return;
9088            }
9089
9090            mProviders.put(p.getComponentName(), p);
9091            if (DEBUG_SHOW_INFO) {
9092                Log.v(TAG, "  "
9093                        + (p.info.nonLocalizedLabel != null
9094                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9095                Log.v(TAG, "    Class=" + p.info.name);
9096            }
9097            final int NI = p.intents.size();
9098            int j;
9099            for (j = 0; j < NI; j++) {
9100                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9101                if (DEBUG_SHOW_INFO) {
9102                    Log.v(TAG, "    IntentFilter:");
9103                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9104                }
9105                if (!intent.debugCheck()) {
9106                    Log.w(TAG, "==> For Provider " + p.info.name);
9107                }
9108                addFilter(intent);
9109            }
9110        }
9111
9112        public final void removeProvider(PackageParser.Provider p) {
9113            mProviders.remove(p.getComponentName());
9114            if (DEBUG_SHOW_INFO) {
9115                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9116                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9117                Log.v(TAG, "    Class=" + p.info.name);
9118            }
9119            final int NI = p.intents.size();
9120            int j;
9121            for (j = 0; j < NI; j++) {
9122                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9123                if (DEBUG_SHOW_INFO) {
9124                    Log.v(TAG, "    IntentFilter:");
9125                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9126                }
9127                removeFilter(intent);
9128            }
9129        }
9130
9131        @Override
9132        protected boolean allowFilterResult(
9133                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9134            ProviderInfo filterPi = filter.provider.info;
9135            for (int i = dest.size() - 1; i >= 0; i--) {
9136                ProviderInfo destPi = dest.get(i).providerInfo;
9137                if (destPi.name == filterPi.name
9138                        && destPi.packageName == filterPi.packageName) {
9139                    return false;
9140                }
9141            }
9142            return true;
9143        }
9144
9145        @Override
9146        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9147            return new PackageParser.ProviderIntentInfo[size];
9148        }
9149
9150        @Override
9151        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9152            if (!sUserManager.exists(userId))
9153                return true;
9154            PackageParser.Package p = filter.provider.owner;
9155            if (p != null) {
9156                PackageSetting ps = (PackageSetting) p.mExtras;
9157                if (ps != null) {
9158                    // System apps are never considered stopped for purposes of
9159                    // filtering, because there may be no way for the user to
9160                    // actually re-launch them.
9161                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9162                            && ps.getStopped(userId);
9163                }
9164            }
9165            return false;
9166        }
9167
9168        @Override
9169        protected boolean isPackageForFilter(String packageName,
9170                PackageParser.ProviderIntentInfo info) {
9171            return packageName.equals(info.provider.owner.packageName);
9172        }
9173
9174        @Override
9175        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9176                int match, int userId) {
9177            if (!sUserManager.exists(userId))
9178                return null;
9179            final PackageParser.ProviderIntentInfo info = filter;
9180            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9181                return null;
9182            }
9183            final PackageParser.Provider provider = info.provider;
9184            if (mSafeMode && (provider.info.applicationInfo.flags
9185                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9186                return null;
9187            }
9188            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9189            if (ps == null) {
9190                return null;
9191            }
9192            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9193                    ps.readUserState(userId), userId);
9194            if (pi == null) {
9195                return null;
9196            }
9197            final ResolveInfo res = new ResolveInfo();
9198            res.providerInfo = pi;
9199            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9200                res.filter = filter;
9201            }
9202            res.priority = info.getPriority();
9203            res.preferredOrder = provider.owner.mPreferredOrder;
9204            res.match = match;
9205            res.isDefault = info.hasDefault;
9206            res.labelRes = info.labelRes;
9207            res.nonLocalizedLabel = info.nonLocalizedLabel;
9208            res.icon = info.icon;
9209            res.system = res.providerInfo.applicationInfo.isSystemApp();
9210            return res;
9211        }
9212
9213        @Override
9214        protected void sortResults(List<ResolveInfo> results) {
9215            Collections.sort(results, mResolvePrioritySorter);
9216        }
9217
9218        @Override
9219        protected void dumpFilter(PrintWriter out, String prefix,
9220                PackageParser.ProviderIntentInfo filter) {
9221            out.print(prefix);
9222            out.print(
9223                    Integer.toHexString(System.identityHashCode(filter.provider)));
9224            out.print(' ');
9225            filter.provider.printComponentShortName(out);
9226            out.print(" filter ");
9227            out.println(Integer.toHexString(System.identityHashCode(filter)));
9228        }
9229
9230        @Override
9231        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9232            return filter.provider;
9233        }
9234
9235        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9236            PackageParser.Provider provider = (PackageParser.Provider)label;
9237            out.print(prefix); out.print(
9238                    Integer.toHexString(System.identityHashCode(provider)));
9239                    out.print(' ');
9240                    provider.printComponentShortName(out);
9241            if (count > 1) {
9242                out.print(" ("); out.print(count); out.print(" filters)");
9243            }
9244            out.println();
9245        }
9246
9247        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9248                = new ArrayMap<ComponentName, PackageParser.Provider>();
9249        private int mFlags;
9250    };
9251
9252    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9253            new Comparator<ResolveInfo>() {
9254        public int compare(ResolveInfo r1, ResolveInfo r2) {
9255            int v1 = r1.priority;
9256            int v2 = r2.priority;
9257            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9258            if (v1 != v2) {
9259                return (v1 > v2) ? -1 : 1;
9260            }
9261            v1 = r1.preferredOrder;
9262            v2 = r2.preferredOrder;
9263            if (v1 != v2) {
9264                return (v1 > v2) ? -1 : 1;
9265            }
9266            if (r1.isDefault != r2.isDefault) {
9267                return r1.isDefault ? -1 : 1;
9268            }
9269            v1 = r1.match;
9270            v2 = r2.match;
9271            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9272            if (v1 != v2) {
9273                return (v1 > v2) ? -1 : 1;
9274            }
9275            if (r1.system != r2.system) {
9276                return r1.system ? -1 : 1;
9277            }
9278            return 0;
9279        }
9280    };
9281
9282    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9283            new Comparator<ProviderInfo>() {
9284        public int compare(ProviderInfo p1, ProviderInfo p2) {
9285            final int v1 = p1.initOrder;
9286            final int v2 = p2.initOrder;
9287            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9288        }
9289    };
9290
9291    final void sendPackageBroadcast(final String action, final String pkg,
9292            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9293            final int[] userIds) {
9294        mHandler.post(new Runnable() {
9295            @Override
9296            public void run() {
9297                try {
9298                    final IActivityManager am = ActivityManagerNative.getDefault();
9299                    if (am == null) return;
9300                    final int[] resolvedUserIds;
9301                    if (userIds == null) {
9302                        resolvedUserIds = am.getRunningUserIds();
9303                    } else {
9304                        resolvedUserIds = userIds;
9305                    }
9306                    for (int id : resolvedUserIds) {
9307                        final Intent intent = new Intent(action,
9308                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9309                        if (extras != null) {
9310                            intent.putExtras(extras);
9311                        }
9312                        if (targetPkg != null) {
9313                            intent.setPackage(targetPkg);
9314                        }
9315                        // Modify the UID when posting to other users
9316                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9317                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9318                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9319                            intent.putExtra(Intent.EXTRA_UID, uid);
9320                        }
9321                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9322                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9323                        if (DEBUG_BROADCASTS) {
9324                            RuntimeException here = new RuntimeException("here");
9325                            here.fillInStackTrace();
9326                            Slog.d(TAG, "Sending to user " + id + ": "
9327                                    + intent.toShortString(false, true, false, false)
9328                                    + " " + intent.getExtras(), here);
9329                        }
9330                        am.broadcastIntent(null, intent, null, finishedReceiver,
9331                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9332                                null, finishedReceiver != null, false, id);
9333                    }
9334                } catch (RemoteException ex) {
9335                }
9336            }
9337        });
9338    }
9339
9340    /**
9341     * Check if the external storage media is available. This is true if there
9342     * is a mounted external storage medium or if the external storage is
9343     * emulated.
9344     */
9345    private boolean isExternalMediaAvailable() {
9346        return mMediaMounted || Environment.isExternalStorageEmulated();
9347    }
9348
9349    @Override
9350    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9351        // writer
9352        synchronized (mPackages) {
9353            if (!isExternalMediaAvailable()) {
9354                // If the external storage is no longer mounted at this point,
9355                // the caller may not have been able to delete all of this
9356                // packages files and can not delete any more.  Bail.
9357                return null;
9358            }
9359            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9360            if (lastPackage != null) {
9361                pkgs.remove(lastPackage);
9362            }
9363            if (pkgs.size() > 0) {
9364                return pkgs.get(0);
9365            }
9366        }
9367        return null;
9368    }
9369
9370    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9371        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9372                userId, andCode ? 1 : 0, packageName);
9373        if (mSystemReady) {
9374            msg.sendToTarget();
9375        } else {
9376            if (mPostSystemReadyMessages == null) {
9377                mPostSystemReadyMessages = new ArrayList<>();
9378            }
9379            mPostSystemReadyMessages.add(msg);
9380        }
9381    }
9382
9383    void startCleaningPackages() {
9384        // reader
9385        synchronized (mPackages) {
9386            if (!isExternalMediaAvailable()) {
9387                return;
9388            }
9389            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9390                return;
9391            }
9392        }
9393        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9394        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9395        IActivityManager am = ActivityManagerNative.getDefault();
9396        if (am != null) {
9397            try {
9398                am.startService(null, intent, null, mContext.getOpPackageName(),
9399                        UserHandle.USER_OWNER);
9400            } catch (RemoteException e) {
9401            }
9402        }
9403    }
9404
9405    @Override
9406    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9407            int installFlags, String installerPackageName, VerificationParams verificationParams,
9408            String packageAbiOverride) {
9409        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9410                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9411    }
9412
9413    @Override
9414    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9415            int installFlags, String installerPackageName, VerificationParams verificationParams,
9416            String packageAbiOverride, int userId) {
9417        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9418
9419        final int callingUid = Binder.getCallingUid();
9420        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9421
9422        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9423            try {
9424                if (observer != null) {
9425                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9426                }
9427            } catch (RemoteException re) {
9428            }
9429            return;
9430        }
9431
9432        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9433            installFlags |= PackageManager.INSTALL_FROM_ADB;
9434
9435        } else {
9436            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9437            // about installerPackageName.
9438
9439            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9440            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9441        }
9442
9443        UserHandle user;
9444        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9445            user = UserHandle.ALL;
9446        } else {
9447            user = new UserHandle(userId);
9448        }
9449
9450        // Only system components can circumvent runtime permissions when installing.
9451        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9452                && mContext.checkCallingOrSelfPermission(Manifest.permission
9453                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9454            throw new SecurityException("You need the "
9455                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9456                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9457        }
9458
9459        verificationParams.setInstallerUid(callingUid);
9460
9461        final File originFile = new File(originPath);
9462        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9463
9464        final Message msg = mHandler.obtainMessage(INIT_COPY);
9465        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9466                null, verificationParams, user, packageAbiOverride, null);
9467        mHandler.sendMessage(msg);
9468    }
9469
9470    void installStage(String packageName, File stagedDir, String stagedCid,
9471            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9472            String installerPackageName, int installerUid, UserHandle user) {
9473        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9474                params.referrerUri, installerUid, null);
9475        verifParams.setInstallerUid(installerUid);
9476
9477        final OriginInfo origin;
9478        if (stagedDir != null) {
9479            origin = OriginInfo.fromStagedFile(stagedDir);
9480        } else {
9481            origin = OriginInfo.fromStagedContainer(stagedCid);
9482        }
9483
9484        final Message msg = mHandler.obtainMessage(INIT_COPY);
9485        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9486                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9487                params.grantedRuntimePermissions);
9488        mHandler.sendMessage(msg);
9489    }
9490
9491    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9492        Bundle extras = new Bundle(1);
9493        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9494
9495        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9496                packageName, extras, null, null, new int[] {userId});
9497        try {
9498            IActivityManager am = ActivityManagerNative.getDefault();
9499            final boolean isSystem =
9500                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9501            if (isSystem && am.isUserRunning(userId, false)) {
9502                // The just-installed/enabled app is bundled on the system, so presumed
9503                // to be able to run automatically without needing an explicit launch.
9504                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9505                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9506                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9507                        .setPackage(packageName);
9508                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9509                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9510            }
9511        } catch (RemoteException e) {
9512            // shouldn't happen
9513            Slog.w(TAG, "Unable to bootstrap installed package", e);
9514        }
9515    }
9516
9517    @Override
9518    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9519            int userId) {
9520        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9521        PackageSetting pkgSetting;
9522        final int uid = Binder.getCallingUid();
9523        enforceCrossUserPermission(uid, userId, true, true,
9524                "setApplicationHiddenSetting for user " + userId);
9525
9526        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9527            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9528            return false;
9529        }
9530
9531        long callingId = Binder.clearCallingIdentity();
9532        try {
9533            boolean sendAdded = false;
9534            boolean sendRemoved = false;
9535            // writer
9536            synchronized (mPackages) {
9537                pkgSetting = mSettings.mPackages.get(packageName);
9538                if (pkgSetting == null) {
9539                    return false;
9540                }
9541                if (pkgSetting.getHidden(userId) != hidden) {
9542                    pkgSetting.setHidden(hidden, userId);
9543                    mSettings.writePackageRestrictionsLPr(userId);
9544                    if (hidden) {
9545                        sendRemoved = true;
9546                    } else {
9547                        sendAdded = true;
9548                    }
9549                }
9550            }
9551            if (sendAdded) {
9552                sendPackageAddedForUser(packageName, pkgSetting, userId);
9553                return true;
9554            }
9555            if (sendRemoved) {
9556                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9557                        "hiding pkg");
9558                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9559            }
9560        } finally {
9561            Binder.restoreCallingIdentity(callingId);
9562        }
9563        return false;
9564    }
9565
9566    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9567            int userId) {
9568        final PackageRemovedInfo info = new PackageRemovedInfo();
9569        info.removedPackage = packageName;
9570        info.removedUsers = new int[] {userId};
9571        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9572        info.sendBroadcast(false, false, false);
9573    }
9574
9575    /**
9576     * Returns true if application is not found or there was an error. Otherwise it returns
9577     * the hidden state of the package for the given user.
9578     */
9579    @Override
9580    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9581        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9582        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9583                false, "getApplicationHidden for user " + userId);
9584        PackageSetting pkgSetting;
9585        long callingId = Binder.clearCallingIdentity();
9586        try {
9587            // writer
9588            synchronized (mPackages) {
9589                pkgSetting = mSettings.mPackages.get(packageName);
9590                if (pkgSetting == null) {
9591                    return true;
9592                }
9593                return pkgSetting.getHidden(userId);
9594            }
9595        } finally {
9596            Binder.restoreCallingIdentity(callingId);
9597        }
9598    }
9599
9600    /**
9601     * @hide
9602     */
9603    @Override
9604    public int installExistingPackageAsUser(String packageName, int userId) {
9605        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9606                null);
9607        PackageSetting pkgSetting;
9608        final int uid = Binder.getCallingUid();
9609        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9610                + userId);
9611        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9612            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9613        }
9614
9615        long callingId = Binder.clearCallingIdentity();
9616        try {
9617            boolean sendAdded = false;
9618
9619            // writer
9620            synchronized (mPackages) {
9621                pkgSetting = mSettings.mPackages.get(packageName);
9622                if (pkgSetting == null) {
9623                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9624                }
9625                if (!pkgSetting.getInstalled(userId)) {
9626                    pkgSetting.setInstalled(true, userId);
9627                    pkgSetting.setHidden(false, userId);
9628                    mSettings.writePackageRestrictionsLPr(userId);
9629                    sendAdded = true;
9630                }
9631            }
9632
9633            if (sendAdded) {
9634                sendPackageAddedForUser(packageName, pkgSetting, userId);
9635            }
9636        } finally {
9637            Binder.restoreCallingIdentity(callingId);
9638        }
9639
9640        return PackageManager.INSTALL_SUCCEEDED;
9641    }
9642
9643    boolean isUserRestricted(int userId, String restrictionKey) {
9644        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9645        if (restrictions.getBoolean(restrictionKey, false)) {
9646            Log.w(TAG, "User is restricted: " + restrictionKey);
9647            return true;
9648        }
9649        return false;
9650    }
9651
9652    @Override
9653    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9654        mContext.enforceCallingOrSelfPermission(
9655                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9656                "Only package verification agents can verify applications");
9657
9658        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9659        final PackageVerificationResponse response = new PackageVerificationResponse(
9660                verificationCode, Binder.getCallingUid());
9661        msg.arg1 = id;
9662        msg.obj = response;
9663        mHandler.sendMessage(msg);
9664    }
9665
9666    @Override
9667    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9668            long millisecondsToDelay) {
9669        mContext.enforceCallingOrSelfPermission(
9670                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9671                "Only package verification agents can extend verification timeouts");
9672
9673        final PackageVerificationState state = mPendingVerification.get(id);
9674        final PackageVerificationResponse response = new PackageVerificationResponse(
9675                verificationCodeAtTimeout, Binder.getCallingUid());
9676
9677        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9678            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9679        }
9680        if (millisecondsToDelay < 0) {
9681            millisecondsToDelay = 0;
9682        }
9683        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9684                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9685            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9686        }
9687
9688        if ((state != null) && !state.timeoutExtended()) {
9689            state.extendTimeout();
9690
9691            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9692            msg.arg1 = id;
9693            msg.obj = response;
9694            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9695        }
9696    }
9697
9698    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9699            int verificationCode, UserHandle user) {
9700        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9701        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9702        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9703        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9704        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9705
9706        mContext.sendBroadcastAsUser(intent, user,
9707                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9708    }
9709
9710    private ComponentName matchComponentForVerifier(String packageName,
9711            List<ResolveInfo> receivers) {
9712        ActivityInfo targetReceiver = null;
9713
9714        final int NR = receivers.size();
9715        for (int i = 0; i < NR; i++) {
9716            final ResolveInfo info = receivers.get(i);
9717            if (info.activityInfo == null) {
9718                continue;
9719            }
9720
9721            if (packageName.equals(info.activityInfo.packageName)) {
9722                targetReceiver = info.activityInfo;
9723                break;
9724            }
9725        }
9726
9727        if (targetReceiver == null) {
9728            return null;
9729        }
9730
9731        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9732    }
9733
9734    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9735            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9736        if (pkgInfo.verifiers.length == 0) {
9737            return null;
9738        }
9739
9740        final int N = pkgInfo.verifiers.length;
9741        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9742        for (int i = 0; i < N; i++) {
9743            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9744
9745            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9746                    receivers);
9747            if (comp == null) {
9748                continue;
9749            }
9750
9751            final int verifierUid = getUidForVerifier(verifierInfo);
9752            if (verifierUid == -1) {
9753                continue;
9754            }
9755
9756            if (DEBUG_VERIFY) {
9757                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9758                        + " with the correct signature");
9759            }
9760            sufficientVerifiers.add(comp);
9761            verificationState.addSufficientVerifier(verifierUid);
9762        }
9763
9764        return sufficientVerifiers;
9765    }
9766
9767    private int getUidForVerifier(VerifierInfo verifierInfo) {
9768        synchronized (mPackages) {
9769            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9770            if (pkg == null) {
9771                return -1;
9772            } else if (pkg.mSignatures.length != 1) {
9773                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9774                        + " has more than one signature; ignoring");
9775                return -1;
9776            }
9777
9778            /*
9779             * If the public key of the package's signature does not match
9780             * our expected public key, then this is a different package and
9781             * we should skip.
9782             */
9783
9784            final byte[] expectedPublicKey;
9785            try {
9786                final Signature verifierSig = pkg.mSignatures[0];
9787                final PublicKey publicKey = verifierSig.getPublicKey();
9788                expectedPublicKey = publicKey.getEncoded();
9789            } catch (CertificateException e) {
9790                return -1;
9791            }
9792
9793            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9794
9795            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9796                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9797                        + " does not have the expected public key; ignoring");
9798                return -1;
9799            }
9800
9801            return pkg.applicationInfo.uid;
9802        }
9803    }
9804
9805    @Override
9806    public void finishPackageInstall(int token) {
9807        enforceSystemOrRoot("Only the system is allowed to finish installs");
9808
9809        if (DEBUG_INSTALL) {
9810            Slog.v(TAG, "BM finishing package install for " + token);
9811        }
9812
9813        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9814        mHandler.sendMessage(msg);
9815    }
9816
9817    /**
9818     * Get the verification agent timeout.
9819     *
9820     * @return verification timeout in milliseconds
9821     */
9822    private long getVerificationTimeout() {
9823        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9824                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9825                DEFAULT_VERIFICATION_TIMEOUT);
9826    }
9827
9828    /**
9829     * Get the default verification agent response code.
9830     *
9831     * @return default verification response code
9832     */
9833    private int getDefaultVerificationResponse() {
9834        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9835                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9836                DEFAULT_VERIFICATION_RESPONSE);
9837    }
9838
9839    /**
9840     * Check whether or not package verification has been enabled.
9841     *
9842     * @return true if verification should be performed
9843     */
9844    private boolean isVerificationEnabled(int userId, int installFlags) {
9845        if (!DEFAULT_VERIFY_ENABLE) {
9846            return false;
9847        }
9848
9849        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9850
9851        // Check if installing from ADB
9852        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9853            // Do not run verification in a test harness environment
9854            if (ActivityManager.isRunningInTestHarness()) {
9855                return false;
9856            }
9857            if (ensureVerifyAppsEnabled) {
9858                return true;
9859            }
9860            // Check if the developer does not want package verification for ADB installs
9861            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9862                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9863                return false;
9864            }
9865        }
9866
9867        if (ensureVerifyAppsEnabled) {
9868            return true;
9869        }
9870
9871        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9872                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9873    }
9874
9875    @Override
9876    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9877            throws RemoteException {
9878        mContext.enforceCallingOrSelfPermission(
9879                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9880                "Only intentfilter verification agents can verify applications");
9881
9882        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9883        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9884                Binder.getCallingUid(), verificationCode, failedDomains);
9885        msg.arg1 = id;
9886        msg.obj = response;
9887        mHandler.sendMessage(msg);
9888    }
9889
9890    @Override
9891    public int getIntentVerificationStatus(String packageName, int userId) {
9892        synchronized (mPackages) {
9893            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9894        }
9895    }
9896
9897    @Override
9898    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9899        mContext.enforceCallingOrSelfPermission(
9900                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9901
9902        boolean result = false;
9903        synchronized (mPackages) {
9904            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9905        }
9906        if (result) {
9907            scheduleWritePackageRestrictionsLocked(userId);
9908        }
9909        return result;
9910    }
9911
9912    @Override
9913    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9914        synchronized (mPackages) {
9915            return mSettings.getIntentFilterVerificationsLPr(packageName);
9916        }
9917    }
9918
9919    @Override
9920    public List<IntentFilter> getAllIntentFilters(String packageName) {
9921        if (TextUtils.isEmpty(packageName)) {
9922            return Collections.<IntentFilter>emptyList();
9923        }
9924        synchronized (mPackages) {
9925            PackageParser.Package pkg = mPackages.get(packageName);
9926            if (pkg == null || pkg.activities == null) {
9927                return Collections.<IntentFilter>emptyList();
9928            }
9929            final int count = pkg.activities.size();
9930            ArrayList<IntentFilter> result = new ArrayList<>();
9931            for (int n=0; n<count; n++) {
9932                PackageParser.Activity activity = pkg.activities.get(n);
9933                if (activity.intents != null || activity.intents.size() > 0) {
9934                    result.addAll(activity.intents);
9935                }
9936            }
9937            return result;
9938        }
9939    }
9940
9941    @Override
9942    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9943        mContext.enforceCallingOrSelfPermission(
9944                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9945
9946        synchronized (mPackages) {
9947            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9948            if (packageName != null) {
9949                result |= updateIntentVerificationStatus(packageName,
9950                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9951                        userId);
9952                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9953                        packageName, userId);
9954            }
9955            return result;
9956        }
9957    }
9958
9959    @Override
9960    public String getDefaultBrowserPackageName(int userId) {
9961        synchronized (mPackages) {
9962            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9963        }
9964    }
9965
9966    /**
9967     * Get the "allow unknown sources" setting.
9968     *
9969     * @return the current "allow unknown sources" setting
9970     */
9971    private int getUnknownSourcesSettings() {
9972        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9973                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9974                -1);
9975    }
9976
9977    @Override
9978    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9979        final int uid = Binder.getCallingUid();
9980        // writer
9981        synchronized (mPackages) {
9982            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9983            if (targetPackageSetting == null) {
9984                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9985            }
9986
9987            PackageSetting installerPackageSetting;
9988            if (installerPackageName != null) {
9989                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9990                if (installerPackageSetting == null) {
9991                    throw new IllegalArgumentException("Unknown installer package: "
9992                            + installerPackageName);
9993                }
9994            } else {
9995                installerPackageSetting = null;
9996            }
9997
9998            Signature[] callerSignature;
9999            Object obj = mSettings.getUserIdLPr(uid);
10000            if (obj != null) {
10001                if (obj instanceof SharedUserSetting) {
10002                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10003                } else if (obj instanceof PackageSetting) {
10004                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10005                } else {
10006                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10007                }
10008            } else {
10009                throw new SecurityException("Unknown calling uid " + uid);
10010            }
10011
10012            // Verify: can't set installerPackageName to a package that is
10013            // not signed with the same cert as the caller.
10014            if (installerPackageSetting != null) {
10015                if (compareSignatures(callerSignature,
10016                        installerPackageSetting.signatures.mSignatures)
10017                        != PackageManager.SIGNATURE_MATCH) {
10018                    throw new SecurityException(
10019                            "Caller does not have same cert as new installer package "
10020                            + installerPackageName);
10021                }
10022            }
10023
10024            // Verify: if target already has an installer package, it must
10025            // be signed with the same cert as the caller.
10026            if (targetPackageSetting.installerPackageName != null) {
10027                PackageSetting setting = mSettings.mPackages.get(
10028                        targetPackageSetting.installerPackageName);
10029                // If the currently set package isn't valid, then it's always
10030                // okay to change it.
10031                if (setting != null) {
10032                    if (compareSignatures(callerSignature,
10033                            setting.signatures.mSignatures)
10034                            != PackageManager.SIGNATURE_MATCH) {
10035                        throw new SecurityException(
10036                                "Caller does not have same cert as old installer package "
10037                                + targetPackageSetting.installerPackageName);
10038                    }
10039                }
10040            }
10041
10042            // Okay!
10043            targetPackageSetting.installerPackageName = installerPackageName;
10044            scheduleWriteSettingsLocked();
10045        }
10046    }
10047
10048    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10049        // Queue up an async operation since the package installation may take a little while.
10050        mHandler.post(new Runnable() {
10051            public void run() {
10052                mHandler.removeCallbacks(this);
10053                 // Result object to be returned
10054                PackageInstalledInfo res = new PackageInstalledInfo();
10055                res.returnCode = currentStatus;
10056                res.uid = -1;
10057                res.pkg = null;
10058                res.removedInfo = new PackageRemovedInfo();
10059                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10060                    args.doPreInstall(res.returnCode);
10061                    synchronized (mInstallLock) {
10062                        installPackageLI(args, res);
10063                    }
10064                    args.doPostInstall(res.returnCode, res.uid);
10065                }
10066
10067                // A restore should be performed at this point if (a) the install
10068                // succeeded, (b) the operation is not an update, and (c) the new
10069                // package has not opted out of backup participation.
10070                final boolean update = res.removedInfo.removedPackage != null;
10071                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10072                boolean doRestore = !update
10073                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10074
10075                // Set up the post-install work request bookkeeping.  This will be used
10076                // and cleaned up by the post-install event handling regardless of whether
10077                // there's a restore pass performed.  Token values are >= 1.
10078                int token;
10079                if (mNextInstallToken < 0) mNextInstallToken = 1;
10080                token = mNextInstallToken++;
10081
10082                PostInstallData data = new PostInstallData(args, res);
10083                mRunningInstalls.put(token, data);
10084                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10085
10086                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10087                    // Pass responsibility to the Backup Manager.  It will perform a
10088                    // restore if appropriate, then pass responsibility back to the
10089                    // Package Manager to run the post-install observer callbacks
10090                    // and broadcasts.
10091                    IBackupManager bm = IBackupManager.Stub.asInterface(
10092                            ServiceManager.getService(Context.BACKUP_SERVICE));
10093                    if (bm != null) {
10094                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10095                                + " to BM for possible restore");
10096                        try {
10097                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10098                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10099                            } else {
10100                                doRestore = false;
10101                            }
10102                        } catch (RemoteException e) {
10103                            // can't happen; the backup manager is local
10104                        } catch (Exception e) {
10105                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10106                            doRestore = false;
10107                        }
10108                    } else {
10109                        Slog.e(TAG, "Backup Manager not found!");
10110                        doRestore = false;
10111                    }
10112                }
10113
10114                if (!doRestore) {
10115                    // No restore possible, or the Backup Manager was mysteriously not
10116                    // available -- just fire the post-install work request directly.
10117                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10118                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10119                    mHandler.sendMessage(msg);
10120                }
10121            }
10122        });
10123    }
10124
10125    private abstract class HandlerParams {
10126        private static final int MAX_RETRIES = 4;
10127
10128        /**
10129         * Number of times startCopy() has been attempted and had a non-fatal
10130         * error.
10131         */
10132        private int mRetries = 0;
10133
10134        /** User handle for the user requesting the information or installation. */
10135        private final UserHandle mUser;
10136
10137        HandlerParams(UserHandle user) {
10138            mUser = user;
10139        }
10140
10141        UserHandle getUser() {
10142            return mUser;
10143        }
10144
10145        final boolean startCopy() {
10146            boolean res;
10147            try {
10148                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10149
10150                if (++mRetries > MAX_RETRIES) {
10151                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10152                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10153                    handleServiceError();
10154                    return false;
10155                } else {
10156                    handleStartCopy();
10157                    res = true;
10158                }
10159            } catch (RemoteException e) {
10160                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10161                mHandler.sendEmptyMessage(MCS_RECONNECT);
10162                res = false;
10163            }
10164            handleReturnCode();
10165            return res;
10166        }
10167
10168        final void serviceError() {
10169            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10170            handleServiceError();
10171            handleReturnCode();
10172        }
10173
10174        abstract void handleStartCopy() throws RemoteException;
10175        abstract void handleServiceError();
10176        abstract void handleReturnCode();
10177    }
10178
10179    class MeasureParams extends HandlerParams {
10180        private final PackageStats mStats;
10181        private boolean mSuccess;
10182
10183        private final IPackageStatsObserver mObserver;
10184
10185        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10186            super(new UserHandle(stats.userHandle));
10187            mObserver = observer;
10188            mStats = stats;
10189        }
10190
10191        @Override
10192        public String toString() {
10193            return "MeasureParams{"
10194                + Integer.toHexString(System.identityHashCode(this))
10195                + " " + mStats.packageName + "}";
10196        }
10197
10198        @Override
10199        void handleStartCopy() throws RemoteException {
10200            synchronized (mInstallLock) {
10201                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10202            }
10203
10204            if (mSuccess) {
10205                final boolean mounted;
10206                if (Environment.isExternalStorageEmulated()) {
10207                    mounted = true;
10208                } else {
10209                    final String status = Environment.getExternalStorageState();
10210                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10211                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10212                }
10213
10214                if (mounted) {
10215                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10216
10217                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10218                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10219
10220                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10221                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10222
10223                    // Always subtract cache size, since it's a subdirectory
10224                    mStats.externalDataSize -= mStats.externalCacheSize;
10225
10226                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10227                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10228
10229                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10230                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10231                }
10232            }
10233        }
10234
10235        @Override
10236        void handleReturnCode() {
10237            if (mObserver != null) {
10238                try {
10239                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10240                } catch (RemoteException e) {
10241                    Slog.i(TAG, "Observer no longer exists.");
10242                }
10243            }
10244        }
10245
10246        @Override
10247        void handleServiceError() {
10248            Slog.e(TAG, "Could not measure application " + mStats.packageName
10249                            + " external storage");
10250        }
10251    }
10252
10253    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10254            throws RemoteException {
10255        long result = 0;
10256        for (File path : paths) {
10257            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10258        }
10259        return result;
10260    }
10261
10262    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10263        for (File path : paths) {
10264            try {
10265                mcs.clearDirectory(path.getAbsolutePath());
10266            } catch (RemoteException e) {
10267            }
10268        }
10269    }
10270
10271    static class OriginInfo {
10272        /**
10273         * Location where install is coming from, before it has been
10274         * copied/renamed into place. This could be a single monolithic APK
10275         * file, or a cluster directory. This location may be untrusted.
10276         */
10277        final File file;
10278        final String cid;
10279
10280        /**
10281         * Flag indicating that {@link #file} or {@link #cid} has already been
10282         * staged, meaning downstream users don't need to defensively copy the
10283         * contents.
10284         */
10285        final boolean staged;
10286
10287        /**
10288         * Flag indicating that {@link #file} or {@link #cid} is an already
10289         * installed app that is being moved.
10290         */
10291        final boolean existing;
10292
10293        final String resolvedPath;
10294        final File resolvedFile;
10295
10296        static OriginInfo fromNothing() {
10297            return new OriginInfo(null, null, false, false);
10298        }
10299
10300        static OriginInfo fromUntrustedFile(File file) {
10301            return new OriginInfo(file, null, false, false);
10302        }
10303
10304        static OriginInfo fromExistingFile(File file) {
10305            return new OriginInfo(file, null, false, true);
10306        }
10307
10308        static OriginInfo fromStagedFile(File file) {
10309            return new OriginInfo(file, null, true, false);
10310        }
10311
10312        static OriginInfo fromStagedContainer(String cid) {
10313            return new OriginInfo(null, cid, true, false);
10314        }
10315
10316        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10317            this.file = file;
10318            this.cid = cid;
10319            this.staged = staged;
10320            this.existing = existing;
10321
10322            if (cid != null) {
10323                resolvedPath = PackageHelper.getSdDir(cid);
10324                resolvedFile = new File(resolvedPath);
10325            } else if (file != null) {
10326                resolvedPath = file.getAbsolutePath();
10327                resolvedFile = file;
10328            } else {
10329                resolvedPath = null;
10330                resolvedFile = null;
10331            }
10332        }
10333    }
10334
10335    class MoveInfo {
10336        final int moveId;
10337        final String fromUuid;
10338        final String toUuid;
10339        final String packageName;
10340        final String dataAppName;
10341        final int appId;
10342        final String seinfo;
10343
10344        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10345                String dataAppName, int appId, String seinfo) {
10346            this.moveId = moveId;
10347            this.fromUuid = fromUuid;
10348            this.toUuid = toUuid;
10349            this.packageName = packageName;
10350            this.dataAppName = dataAppName;
10351            this.appId = appId;
10352            this.seinfo = seinfo;
10353        }
10354    }
10355
10356    class InstallParams extends HandlerParams {
10357        final OriginInfo origin;
10358        final MoveInfo move;
10359        final IPackageInstallObserver2 observer;
10360        int installFlags;
10361        final String installerPackageName;
10362        final String volumeUuid;
10363        final VerificationParams verificationParams;
10364        private InstallArgs mArgs;
10365        private int mRet;
10366        final String packageAbiOverride;
10367        final String[] grantedRuntimePermissions;
10368
10369
10370        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10371                int installFlags, String installerPackageName, String volumeUuid,
10372                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10373                String[] grantedPermissions) {
10374            super(user);
10375            this.origin = origin;
10376            this.move = move;
10377            this.observer = observer;
10378            this.installFlags = installFlags;
10379            this.installerPackageName = installerPackageName;
10380            this.volumeUuid = volumeUuid;
10381            this.verificationParams = verificationParams;
10382            this.packageAbiOverride = packageAbiOverride;
10383            this.grantedRuntimePermissions = grantedPermissions;
10384        }
10385
10386        @Override
10387        public String toString() {
10388            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10389                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10390        }
10391
10392        public ManifestDigest getManifestDigest() {
10393            if (verificationParams == null) {
10394                return null;
10395            }
10396            return verificationParams.getManifestDigest();
10397        }
10398
10399        private int installLocationPolicy(PackageInfoLite pkgLite) {
10400            String packageName = pkgLite.packageName;
10401            int installLocation = pkgLite.installLocation;
10402            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10403            // reader
10404            synchronized (mPackages) {
10405                PackageParser.Package pkg = mPackages.get(packageName);
10406                if (pkg != null) {
10407                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10408                        // Check for downgrading.
10409                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10410                            try {
10411                                checkDowngrade(pkg, pkgLite);
10412                            } catch (PackageManagerException e) {
10413                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10414                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10415                            }
10416                        }
10417                        // Check for updated system application.
10418                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10419                            if (onSd) {
10420                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10421                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10422                            }
10423                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10424                        } else {
10425                            if (onSd) {
10426                                // Install flag overrides everything.
10427                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10428                            }
10429                            // If current upgrade specifies particular preference
10430                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10431                                // Application explicitly specified internal.
10432                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10433                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10434                                // App explictly prefers external. Let policy decide
10435                            } else {
10436                                // Prefer previous location
10437                                if (isExternal(pkg)) {
10438                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10439                                }
10440                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10441                            }
10442                        }
10443                    } else {
10444                        // Invalid install. Return error code
10445                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10446                    }
10447                }
10448            }
10449            // All the special cases have been taken care of.
10450            // Return result based on recommended install location.
10451            if (onSd) {
10452                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10453            }
10454            return pkgLite.recommendedInstallLocation;
10455        }
10456
10457        /*
10458         * Invoke remote method to get package information and install
10459         * location values. Override install location based on default
10460         * policy if needed and then create install arguments based
10461         * on the install location.
10462         */
10463        public void handleStartCopy() throws RemoteException {
10464            int ret = PackageManager.INSTALL_SUCCEEDED;
10465
10466            // If we're already staged, we've firmly committed to an install location
10467            if (origin.staged) {
10468                if (origin.file != null) {
10469                    installFlags |= PackageManager.INSTALL_INTERNAL;
10470                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10471                } else if (origin.cid != null) {
10472                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10473                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10474                } else {
10475                    throw new IllegalStateException("Invalid stage location");
10476                }
10477            }
10478
10479            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10480            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10481
10482            PackageInfoLite pkgLite = null;
10483
10484            if (onInt && onSd) {
10485                // Check if both bits are set.
10486                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10487                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10488            } else {
10489                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10490                        packageAbiOverride);
10491
10492                /*
10493                 * If we have too little free space, try to free cache
10494                 * before giving up.
10495                 */
10496                if (!origin.staged && pkgLite.recommendedInstallLocation
10497                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10498                    // TODO: focus freeing disk space on the target device
10499                    final StorageManager storage = StorageManager.from(mContext);
10500                    final long lowThreshold = storage.getStorageLowBytes(
10501                            Environment.getDataDirectory());
10502
10503                    final long sizeBytes = mContainerService.calculateInstalledSize(
10504                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10505
10506                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10507                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10508                                installFlags, packageAbiOverride);
10509                    }
10510
10511                    /*
10512                     * The cache free must have deleted the file we
10513                     * downloaded to install.
10514                     *
10515                     * TODO: fix the "freeCache" call to not delete
10516                     *       the file we care about.
10517                     */
10518                    if (pkgLite.recommendedInstallLocation
10519                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10520                        pkgLite.recommendedInstallLocation
10521                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10522                    }
10523                }
10524            }
10525
10526            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10527                int loc = pkgLite.recommendedInstallLocation;
10528                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10529                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10530                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10531                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10532                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10533                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10534                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10535                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10536                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10537                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10538                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10539                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10540                } else {
10541                    // Override with defaults if needed.
10542                    loc = installLocationPolicy(pkgLite);
10543                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10544                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10545                    } else if (!onSd && !onInt) {
10546                        // Override install location with flags
10547                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10548                            // Set the flag to install on external media.
10549                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10550                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10551                        } else {
10552                            // Make sure the flag for installing on external
10553                            // media is unset
10554                            installFlags |= PackageManager.INSTALL_INTERNAL;
10555                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10556                        }
10557                    }
10558                }
10559            }
10560
10561            final InstallArgs args = createInstallArgs(this);
10562            mArgs = args;
10563
10564            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10565                 /*
10566                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10567                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10568                 */
10569                int userIdentifier = getUser().getIdentifier();
10570                if (userIdentifier == UserHandle.USER_ALL
10571                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10572                    userIdentifier = UserHandle.USER_OWNER;
10573                }
10574
10575                /*
10576                 * Determine if we have any installed package verifiers. If we
10577                 * do, then we'll defer to them to verify the packages.
10578                 */
10579                final int requiredUid = mRequiredVerifierPackage == null ? -1
10580                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10581                if (!origin.existing && requiredUid != -1
10582                        && isVerificationEnabled(userIdentifier, installFlags)) {
10583                    final Intent verification = new Intent(
10584                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10585                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10586                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10587                            PACKAGE_MIME_TYPE);
10588                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10589
10590                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10591                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10592                            0 /* TODO: Which userId? */);
10593
10594                    if (DEBUG_VERIFY) {
10595                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10596                                + verification.toString() + " with " + pkgLite.verifiers.length
10597                                + " optional verifiers");
10598                    }
10599
10600                    final int verificationId = mPendingVerificationToken++;
10601
10602                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10603
10604                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10605                            installerPackageName);
10606
10607                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10608                            installFlags);
10609
10610                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10611                            pkgLite.packageName);
10612
10613                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10614                            pkgLite.versionCode);
10615
10616                    if (verificationParams != null) {
10617                        if (verificationParams.getVerificationURI() != null) {
10618                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10619                                 verificationParams.getVerificationURI());
10620                        }
10621                        if (verificationParams.getOriginatingURI() != null) {
10622                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10623                                  verificationParams.getOriginatingURI());
10624                        }
10625                        if (verificationParams.getReferrer() != null) {
10626                            verification.putExtra(Intent.EXTRA_REFERRER,
10627                                  verificationParams.getReferrer());
10628                        }
10629                        if (verificationParams.getOriginatingUid() >= 0) {
10630                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10631                                  verificationParams.getOriginatingUid());
10632                        }
10633                        if (verificationParams.getInstallerUid() >= 0) {
10634                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10635                                  verificationParams.getInstallerUid());
10636                        }
10637                    }
10638
10639                    final PackageVerificationState verificationState = new PackageVerificationState(
10640                            requiredUid, args);
10641
10642                    mPendingVerification.append(verificationId, verificationState);
10643
10644                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10645                            receivers, verificationState);
10646
10647                    // Apps installed for "all" users use the device owner to verify the app
10648                    UserHandle verifierUser = getUser();
10649                    if (verifierUser == UserHandle.ALL) {
10650                        verifierUser = UserHandle.OWNER;
10651                    }
10652
10653                    /*
10654                     * If any sufficient verifiers were listed in the package
10655                     * manifest, attempt to ask them.
10656                     */
10657                    if (sufficientVerifiers != null) {
10658                        final int N = sufficientVerifiers.size();
10659                        if (N == 0) {
10660                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10661                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10662                        } else {
10663                            for (int i = 0; i < N; i++) {
10664                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10665
10666                                final Intent sufficientIntent = new Intent(verification);
10667                                sufficientIntent.setComponent(verifierComponent);
10668                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10669                            }
10670                        }
10671                    }
10672
10673                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10674                            mRequiredVerifierPackage, receivers);
10675                    if (ret == PackageManager.INSTALL_SUCCEEDED
10676                            && mRequiredVerifierPackage != null) {
10677                        /*
10678                         * Send the intent to the required verification agent,
10679                         * but only start the verification timeout after the
10680                         * target BroadcastReceivers have run.
10681                         */
10682                        verification.setComponent(requiredVerifierComponent);
10683                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10684                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10685                                new BroadcastReceiver() {
10686                                    @Override
10687                                    public void onReceive(Context context, Intent intent) {
10688                                        final Message msg = mHandler
10689                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10690                                        msg.arg1 = verificationId;
10691                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10692                                    }
10693                                }, null, 0, null, null);
10694
10695                        /*
10696                         * We don't want the copy to proceed until verification
10697                         * succeeds, so null out this field.
10698                         */
10699                        mArgs = null;
10700                    }
10701                } else {
10702                    /*
10703                     * No package verification is enabled, so immediately start
10704                     * the remote call to initiate copy using temporary file.
10705                     */
10706                    ret = args.copyApk(mContainerService, true);
10707                }
10708            }
10709
10710            mRet = ret;
10711        }
10712
10713        @Override
10714        void handleReturnCode() {
10715            // If mArgs is null, then MCS couldn't be reached. When it
10716            // reconnects, it will try again to install. At that point, this
10717            // will succeed.
10718            if (mArgs != null) {
10719                processPendingInstall(mArgs, mRet);
10720            }
10721        }
10722
10723        @Override
10724        void handleServiceError() {
10725            mArgs = createInstallArgs(this);
10726            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10727        }
10728
10729        public boolean isForwardLocked() {
10730            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10731        }
10732    }
10733
10734    /**
10735     * Used during creation of InstallArgs
10736     *
10737     * @param installFlags package installation flags
10738     * @return true if should be installed on external storage
10739     */
10740    private static boolean installOnExternalAsec(int installFlags) {
10741        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10742            return false;
10743        }
10744        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10745            return true;
10746        }
10747        return false;
10748    }
10749
10750    /**
10751     * Used during creation of InstallArgs
10752     *
10753     * @param installFlags package installation flags
10754     * @return true if should be installed as forward locked
10755     */
10756    private static boolean installForwardLocked(int installFlags) {
10757        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10758    }
10759
10760    private InstallArgs createInstallArgs(InstallParams params) {
10761        if (params.move != null) {
10762            return new MoveInstallArgs(params);
10763        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10764            return new AsecInstallArgs(params);
10765        } else {
10766            return new FileInstallArgs(params);
10767        }
10768    }
10769
10770    /**
10771     * Create args that describe an existing installed package. Typically used
10772     * when cleaning up old installs, or used as a move source.
10773     */
10774    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10775            String resourcePath, String[] instructionSets) {
10776        final boolean isInAsec;
10777        if (installOnExternalAsec(installFlags)) {
10778            /* Apps on SD card are always in ASEC containers. */
10779            isInAsec = true;
10780        } else if (installForwardLocked(installFlags)
10781                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10782            /*
10783             * Forward-locked apps are only in ASEC containers if they're the
10784             * new style
10785             */
10786            isInAsec = true;
10787        } else {
10788            isInAsec = false;
10789        }
10790
10791        if (isInAsec) {
10792            return new AsecInstallArgs(codePath, instructionSets,
10793                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10794        } else {
10795            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10796        }
10797    }
10798
10799    static abstract class InstallArgs {
10800        /** @see InstallParams#origin */
10801        final OriginInfo origin;
10802        /** @see InstallParams#move */
10803        final MoveInfo move;
10804
10805        final IPackageInstallObserver2 observer;
10806        // Always refers to PackageManager flags only
10807        final int installFlags;
10808        final String installerPackageName;
10809        final String volumeUuid;
10810        final ManifestDigest manifestDigest;
10811        final UserHandle user;
10812        final String abiOverride;
10813        final String[] installGrantPermissions;
10814
10815        // The list of instruction sets supported by this app. This is currently
10816        // only used during the rmdex() phase to clean up resources. We can get rid of this
10817        // if we move dex files under the common app path.
10818        /* nullable */ String[] instructionSets;
10819
10820        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10821                int installFlags, String installerPackageName, String volumeUuid,
10822                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10823                String abiOverride, String[] installGrantPermissions) {
10824            this.origin = origin;
10825            this.move = move;
10826            this.installFlags = installFlags;
10827            this.observer = observer;
10828            this.installerPackageName = installerPackageName;
10829            this.volumeUuid = volumeUuid;
10830            this.manifestDigest = manifestDigest;
10831            this.user = user;
10832            this.instructionSets = instructionSets;
10833            this.abiOverride = abiOverride;
10834            this.installGrantPermissions = installGrantPermissions;
10835        }
10836
10837        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10838        abstract int doPreInstall(int status);
10839
10840        /**
10841         * Rename package into final resting place. All paths on the given
10842         * scanned package should be updated to reflect the rename.
10843         */
10844        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10845        abstract int doPostInstall(int status, int uid);
10846
10847        /** @see PackageSettingBase#codePathString */
10848        abstract String getCodePath();
10849        /** @see PackageSettingBase#resourcePathString */
10850        abstract String getResourcePath();
10851
10852        // Need installer lock especially for dex file removal.
10853        abstract void cleanUpResourcesLI();
10854        abstract boolean doPostDeleteLI(boolean delete);
10855
10856        /**
10857         * Called before the source arguments are copied. This is used mostly
10858         * for MoveParams when it needs to read the source file to put it in the
10859         * destination.
10860         */
10861        int doPreCopy() {
10862            return PackageManager.INSTALL_SUCCEEDED;
10863        }
10864
10865        /**
10866         * Called after the source arguments are copied. This is used mostly for
10867         * MoveParams when it needs to read the source file to put it in the
10868         * destination.
10869         *
10870         * @return
10871         */
10872        int doPostCopy(int uid) {
10873            return PackageManager.INSTALL_SUCCEEDED;
10874        }
10875
10876        protected boolean isFwdLocked() {
10877            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10878        }
10879
10880        protected boolean isExternalAsec() {
10881            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10882        }
10883
10884        UserHandle getUser() {
10885            return user;
10886        }
10887    }
10888
10889    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10890        if (!allCodePaths.isEmpty()) {
10891            if (instructionSets == null) {
10892                throw new IllegalStateException("instructionSet == null");
10893            }
10894            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10895            for (String codePath : allCodePaths) {
10896                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10897                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10898                    if (retCode < 0) {
10899                        Slog.w(TAG, "Couldn't remove dex file for package: "
10900                                + " at location " + codePath + ", retcode=" + retCode);
10901                        // we don't consider this to be a failure of the core package deletion
10902                    }
10903                }
10904            }
10905        }
10906    }
10907
10908    /**
10909     * Logic to handle installation of non-ASEC applications, including copying
10910     * and renaming logic.
10911     */
10912    class FileInstallArgs extends InstallArgs {
10913        private File codeFile;
10914        private File resourceFile;
10915
10916        // Example topology:
10917        // /data/app/com.example/base.apk
10918        // /data/app/com.example/split_foo.apk
10919        // /data/app/com.example/lib/arm/libfoo.so
10920        // /data/app/com.example/lib/arm64/libfoo.so
10921        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10922
10923        /** New install */
10924        FileInstallArgs(InstallParams params) {
10925            super(params.origin, params.move, params.observer, params.installFlags,
10926                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10927                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10928                    params.grantedRuntimePermissions);
10929            if (isFwdLocked()) {
10930                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10931            }
10932        }
10933
10934        /** Existing install */
10935        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10936            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10937                    null, null);
10938            this.codeFile = (codePath != null) ? new File(codePath) : null;
10939            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10940        }
10941
10942        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10943            if (origin.staged) {
10944                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10945                codeFile = origin.file;
10946                resourceFile = origin.file;
10947                return PackageManager.INSTALL_SUCCEEDED;
10948            }
10949
10950            try {
10951                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10952                codeFile = tempDir;
10953                resourceFile = tempDir;
10954            } catch (IOException e) {
10955                Slog.w(TAG, "Failed to create copy file: " + e);
10956                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10957            }
10958
10959            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10960                @Override
10961                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10962                    if (!FileUtils.isValidExtFilename(name)) {
10963                        throw new IllegalArgumentException("Invalid filename: " + name);
10964                    }
10965                    try {
10966                        final File file = new File(codeFile, name);
10967                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10968                                O_RDWR | O_CREAT, 0644);
10969                        Os.chmod(file.getAbsolutePath(), 0644);
10970                        return new ParcelFileDescriptor(fd);
10971                    } catch (ErrnoException e) {
10972                        throw new RemoteException("Failed to open: " + e.getMessage());
10973                    }
10974                }
10975            };
10976
10977            int ret = PackageManager.INSTALL_SUCCEEDED;
10978            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10979            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10980                Slog.e(TAG, "Failed to copy package");
10981                return ret;
10982            }
10983
10984            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10985            NativeLibraryHelper.Handle handle = null;
10986            try {
10987                handle = NativeLibraryHelper.Handle.create(codeFile);
10988                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10989                        abiOverride);
10990            } catch (IOException e) {
10991                Slog.e(TAG, "Copying native libraries failed", e);
10992                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10993            } finally {
10994                IoUtils.closeQuietly(handle);
10995            }
10996
10997            return ret;
10998        }
10999
11000        int doPreInstall(int status) {
11001            if (status != PackageManager.INSTALL_SUCCEEDED) {
11002                cleanUp();
11003            }
11004            return status;
11005        }
11006
11007        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11008            if (status != PackageManager.INSTALL_SUCCEEDED) {
11009                cleanUp();
11010                return false;
11011            }
11012
11013            final File targetDir = codeFile.getParentFile();
11014            final File beforeCodeFile = codeFile;
11015            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11016
11017            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11018            try {
11019                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11020            } catch (ErrnoException e) {
11021                Slog.w(TAG, "Failed to rename", e);
11022                return false;
11023            }
11024
11025            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11026                Slog.w(TAG, "Failed to restorecon");
11027                return false;
11028            }
11029
11030            // Reflect the rename internally
11031            codeFile = afterCodeFile;
11032            resourceFile = afterCodeFile;
11033
11034            // Reflect the rename in scanned details
11035            pkg.codePath = afterCodeFile.getAbsolutePath();
11036            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11037                    pkg.baseCodePath);
11038            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11039                    pkg.splitCodePaths);
11040
11041            // Reflect the rename in app info
11042            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11043            pkg.applicationInfo.setCodePath(pkg.codePath);
11044            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11045            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11046            pkg.applicationInfo.setResourcePath(pkg.codePath);
11047            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11048            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11049
11050            return true;
11051        }
11052
11053        int doPostInstall(int status, int uid) {
11054            if (status != PackageManager.INSTALL_SUCCEEDED) {
11055                cleanUp();
11056            }
11057            return status;
11058        }
11059
11060        @Override
11061        String getCodePath() {
11062            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11063        }
11064
11065        @Override
11066        String getResourcePath() {
11067            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11068        }
11069
11070        private boolean cleanUp() {
11071            if (codeFile == null || !codeFile.exists()) {
11072                return false;
11073            }
11074
11075            if (codeFile.isDirectory()) {
11076                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11077            } else {
11078                codeFile.delete();
11079            }
11080
11081            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11082                resourceFile.delete();
11083            }
11084
11085            return true;
11086        }
11087
11088        void cleanUpResourcesLI() {
11089            // Try enumerating all code paths before deleting
11090            List<String> allCodePaths = Collections.EMPTY_LIST;
11091            if (codeFile != null && codeFile.exists()) {
11092                try {
11093                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11094                    allCodePaths = pkg.getAllCodePaths();
11095                } catch (PackageParserException e) {
11096                    // Ignored; we tried our best
11097                }
11098            }
11099
11100            cleanUp();
11101            removeDexFiles(allCodePaths, instructionSets);
11102        }
11103
11104        boolean doPostDeleteLI(boolean delete) {
11105            // XXX err, shouldn't we respect the delete flag?
11106            cleanUpResourcesLI();
11107            return true;
11108        }
11109    }
11110
11111    private boolean isAsecExternal(String cid) {
11112        final String asecPath = PackageHelper.getSdFilesystem(cid);
11113        return !asecPath.startsWith(mAsecInternalPath);
11114    }
11115
11116    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11117            PackageManagerException {
11118        if (copyRet < 0) {
11119            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11120                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11121                throw new PackageManagerException(copyRet, message);
11122            }
11123        }
11124    }
11125
11126    /**
11127     * Extract the MountService "container ID" from the full code path of an
11128     * .apk.
11129     */
11130    static String cidFromCodePath(String fullCodePath) {
11131        int eidx = fullCodePath.lastIndexOf("/");
11132        String subStr1 = fullCodePath.substring(0, eidx);
11133        int sidx = subStr1.lastIndexOf("/");
11134        return subStr1.substring(sidx+1, eidx);
11135    }
11136
11137    /**
11138     * Logic to handle installation of ASEC applications, including copying and
11139     * renaming logic.
11140     */
11141    class AsecInstallArgs extends InstallArgs {
11142        static final String RES_FILE_NAME = "pkg.apk";
11143        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11144
11145        String cid;
11146        String packagePath;
11147        String resourcePath;
11148
11149        /** New install */
11150        AsecInstallArgs(InstallParams params) {
11151            super(params.origin, params.move, params.observer, params.installFlags,
11152                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11153                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11154                    params.grantedRuntimePermissions);
11155        }
11156
11157        /** Existing install */
11158        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11159                        boolean isExternal, boolean isForwardLocked) {
11160            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11161                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11162                    instructionSets, null, null);
11163            // Hackily pretend we're still looking at a full code path
11164            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11165                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11166            }
11167
11168            // Extract cid from fullCodePath
11169            int eidx = fullCodePath.lastIndexOf("/");
11170            String subStr1 = fullCodePath.substring(0, eidx);
11171            int sidx = subStr1.lastIndexOf("/");
11172            cid = subStr1.substring(sidx+1, eidx);
11173            setMountPath(subStr1);
11174        }
11175
11176        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11177            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11178                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11179                    instructionSets, null, null);
11180            this.cid = cid;
11181            setMountPath(PackageHelper.getSdDir(cid));
11182        }
11183
11184        void createCopyFile() {
11185            cid = mInstallerService.allocateExternalStageCidLegacy();
11186        }
11187
11188        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11189            if (origin.staged) {
11190                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11191                cid = origin.cid;
11192                setMountPath(PackageHelper.getSdDir(cid));
11193                return PackageManager.INSTALL_SUCCEEDED;
11194            }
11195
11196            if (temp) {
11197                createCopyFile();
11198            } else {
11199                /*
11200                 * Pre-emptively destroy the container since it's destroyed if
11201                 * copying fails due to it existing anyway.
11202                 */
11203                PackageHelper.destroySdDir(cid);
11204            }
11205
11206            final String newMountPath = imcs.copyPackageToContainer(
11207                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11208                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11209
11210            if (newMountPath != null) {
11211                setMountPath(newMountPath);
11212                return PackageManager.INSTALL_SUCCEEDED;
11213            } else {
11214                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11215            }
11216        }
11217
11218        @Override
11219        String getCodePath() {
11220            return packagePath;
11221        }
11222
11223        @Override
11224        String getResourcePath() {
11225            return resourcePath;
11226        }
11227
11228        int doPreInstall(int status) {
11229            if (status != PackageManager.INSTALL_SUCCEEDED) {
11230                // Destroy container
11231                PackageHelper.destroySdDir(cid);
11232            } else {
11233                boolean mounted = PackageHelper.isContainerMounted(cid);
11234                if (!mounted) {
11235                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11236                            Process.SYSTEM_UID);
11237                    if (newMountPath != null) {
11238                        setMountPath(newMountPath);
11239                    } else {
11240                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11241                    }
11242                }
11243            }
11244            return status;
11245        }
11246
11247        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11248            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11249            String newMountPath = null;
11250            if (PackageHelper.isContainerMounted(cid)) {
11251                // Unmount the container
11252                if (!PackageHelper.unMountSdDir(cid)) {
11253                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11254                    return false;
11255                }
11256            }
11257            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11258                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11259                        " which might be stale. Will try to clean up.");
11260                // Clean up the stale container and proceed to recreate.
11261                if (!PackageHelper.destroySdDir(newCacheId)) {
11262                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11263                    return false;
11264                }
11265                // Successfully cleaned up stale container. Try to rename again.
11266                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11267                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11268                            + " inspite of cleaning it up.");
11269                    return false;
11270                }
11271            }
11272            if (!PackageHelper.isContainerMounted(newCacheId)) {
11273                Slog.w(TAG, "Mounting container " + newCacheId);
11274                newMountPath = PackageHelper.mountSdDir(newCacheId,
11275                        getEncryptKey(), Process.SYSTEM_UID);
11276            } else {
11277                newMountPath = PackageHelper.getSdDir(newCacheId);
11278            }
11279            if (newMountPath == null) {
11280                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11281                return false;
11282            }
11283            Log.i(TAG, "Succesfully renamed " + cid +
11284                    " to " + newCacheId +
11285                    " at new path: " + newMountPath);
11286            cid = newCacheId;
11287
11288            final File beforeCodeFile = new File(packagePath);
11289            setMountPath(newMountPath);
11290            final File afterCodeFile = new File(packagePath);
11291
11292            // Reflect the rename in scanned details
11293            pkg.codePath = afterCodeFile.getAbsolutePath();
11294            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11295                    pkg.baseCodePath);
11296            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11297                    pkg.splitCodePaths);
11298
11299            // Reflect the rename in app info
11300            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11301            pkg.applicationInfo.setCodePath(pkg.codePath);
11302            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11303            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11304            pkg.applicationInfo.setResourcePath(pkg.codePath);
11305            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11306            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11307
11308            return true;
11309        }
11310
11311        private void setMountPath(String mountPath) {
11312            final File mountFile = new File(mountPath);
11313
11314            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11315            if (monolithicFile.exists()) {
11316                packagePath = monolithicFile.getAbsolutePath();
11317                if (isFwdLocked()) {
11318                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11319                } else {
11320                    resourcePath = packagePath;
11321                }
11322            } else {
11323                packagePath = mountFile.getAbsolutePath();
11324                resourcePath = packagePath;
11325            }
11326        }
11327
11328        int doPostInstall(int status, int uid) {
11329            if (status != PackageManager.INSTALL_SUCCEEDED) {
11330                cleanUp();
11331            } else {
11332                final int groupOwner;
11333                final String protectedFile;
11334                if (isFwdLocked()) {
11335                    groupOwner = UserHandle.getSharedAppGid(uid);
11336                    protectedFile = RES_FILE_NAME;
11337                } else {
11338                    groupOwner = -1;
11339                    protectedFile = null;
11340                }
11341
11342                if (uid < Process.FIRST_APPLICATION_UID
11343                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11344                    Slog.e(TAG, "Failed to finalize " + cid);
11345                    PackageHelper.destroySdDir(cid);
11346                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11347                }
11348
11349                boolean mounted = PackageHelper.isContainerMounted(cid);
11350                if (!mounted) {
11351                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11352                }
11353            }
11354            return status;
11355        }
11356
11357        private void cleanUp() {
11358            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11359
11360            // Destroy secure container
11361            PackageHelper.destroySdDir(cid);
11362        }
11363
11364        private List<String> getAllCodePaths() {
11365            final File codeFile = new File(getCodePath());
11366            if (codeFile != null && codeFile.exists()) {
11367                try {
11368                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11369                    return pkg.getAllCodePaths();
11370                } catch (PackageParserException e) {
11371                    // Ignored; we tried our best
11372                }
11373            }
11374            return Collections.EMPTY_LIST;
11375        }
11376
11377        void cleanUpResourcesLI() {
11378            // Enumerate all code paths before deleting
11379            cleanUpResourcesLI(getAllCodePaths());
11380        }
11381
11382        private void cleanUpResourcesLI(List<String> allCodePaths) {
11383            cleanUp();
11384            removeDexFiles(allCodePaths, instructionSets);
11385        }
11386
11387        String getPackageName() {
11388            return getAsecPackageName(cid);
11389        }
11390
11391        boolean doPostDeleteLI(boolean delete) {
11392            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11393            final List<String> allCodePaths = getAllCodePaths();
11394            boolean mounted = PackageHelper.isContainerMounted(cid);
11395            if (mounted) {
11396                // Unmount first
11397                if (PackageHelper.unMountSdDir(cid)) {
11398                    mounted = false;
11399                }
11400            }
11401            if (!mounted && delete) {
11402                cleanUpResourcesLI(allCodePaths);
11403            }
11404            return !mounted;
11405        }
11406
11407        @Override
11408        int doPreCopy() {
11409            if (isFwdLocked()) {
11410                if (!PackageHelper.fixSdPermissions(cid,
11411                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11412                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11413                }
11414            }
11415
11416            return PackageManager.INSTALL_SUCCEEDED;
11417        }
11418
11419        @Override
11420        int doPostCopy(int uid) {
11421            if (isFwdLocked()) {
11422                if (uid < Process.FIRST_APPLICATION_UID
11423                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11424                                RES_FILE_NAME)) {
11425                    Slog.e(TAG, "Failed to finalize " + cid);
11426                    PackageHelper.destroySdDir(cid);
11427                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11428                }
11429            }
11430
11431            return PackageManager.INSTALL_SUCCEEDED;
11432        }
11433    }
11434
11435    /**
11436     * Logic to handle movement of existing installed applications.
11437     */
11438    class MoveInstallArgs extends InstallArgs {
11439        private File codeFile;
11440        private File resourceFile;
11441
11442        /** New install */
11443        MoveInstallArgs(InstallParams params) {
11444            super(params.origin, params.move, params.observer, params.installFlags,
11445                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11446                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11447                    params.grantedRuntimePermissions);
11448        }
11449
11450        int copyApk(IMediaContainerService imcs, boolean temp) {
11451            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11452                    + move.fromUuid + " to " + move.toUuid);
11453            synchronized (mInstaller) {
11454                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11455                        move.dataAppName, move.appId, move.seinfo) != 0) {
11456                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11457                }
11458            }
11459
11460            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11461            resourceFile = codeFile;
11462            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11463
11464            return PackageManager.INSTALL_SUCCEEDED;
11465        }
11466
11467        int doPreInstall(int status) {
11468            if (status != PackageManager.INSTALL_SUCCEEDED) {
11469                cleanUp(move.toUuid);
11470            }
11471            return status;
11472        }
11473
11474        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11475            if (status != PackageManager.INSTALL_SUCCEEDED) {
11476                cleanUp(move.toUuid);
11477                return false;
11478            }
11479
11480            // Reflect the move in app info
11481            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11482            pkg.applicationInfo.setCodePath(pkg.codePath);
11483            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11484            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11485            pkg.applicationInfo.setResourcePath(pkg.codePath);
11486            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11487            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11488
11489            return true;
11490        }
11491
11492        int doPostInstall(int status, int uid) {
11493            if (status == PackageManager.INSTALL_SUCCEEDED) {
11494                cleanUp(move.fromUuid);
11495            } else {
11496                cleanUp(move.toUuid);
11497            }
11498            return status;
11499        }
11500
11501        @Override
11502        String getCodePath() {
11503            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11504        }
11505
11506        @Override
11507        String getResourcePath() {
11508            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11509        }
11510
11511        private boolean cleanUp(String volumeUuid) {
11512            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11513                    move.dataAppName);
11514            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11515            synchronized (mInstallLock) {
11516                // Clean up both app data and code
11517                removeDataDirsLI(volumeUuid, move.packageName);
11518                if (codeFile.isDirectory()) {
11519                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11520                } else {
11521                    codeFile.delete();
11522                }
11523            }
11524            return true;
11525        }
11526
11527        void cleanUpResourcesLI() {
11528            throw new UnsupportedOperationException();
11529        }
11530
11531        boolean doPostDeleteLI(boolean delete) {
11532            throw new UnsupportedOperationException();
11533        }
11534    }
11535
11536    static String getAsecPackageName(String packageCid) {
11537        int idx = packageCid.lastIndexOf("-");
11538        if (idx == -1) {
11539            return packageCid;
11540        }
11541        return packageCid.substring(0, idx);
11542    }
11543
11544    // Utility method used to create code paths based on package name and available index.
11545    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11546        String idxStr = "";
11547        int idx = 1;
11548        // Fall back to default value of idx=1 if prefix is not
11549        // part of oldCodePath
11550        if (oldCodePath != null) {
11551            String subStr = oldCodePath;
11552            // Drop the suffix right away
11553            if (suffix != null && subStr.endsWith(suffix)) {
11554                subStr = subStr.substring(0, subStr.length() - suffix.length());
11555            }
11556            // If oldCodePath already contains prefix find out the
11557            // ending index to either increment or decrement.
11558            int sidx = subStr.lastIndexOf(prefix);
11559            if (sidx != -1) {
11560                subStr = subStr.substring(sidx + prefix.length());
11561                if (subStr != null) {
11562                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11563                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11564                    }
11565                    try {
11566                        idx = Integer.parseInt(subStr);
11567                        if (idx <= 1) {
11568                            idx++;
11569                        } else {
11570                            idx--;
11571                        }
11572                    } catch(NumberFormatException e) {
11573                    }
11574                }
11575            }
11576        }
11577        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11578        return prefix + idxStr;
11579    }
11580
11581    private File getNextCodePath(File targetDir, String packageName) {
11582        int suffix = 1;
11583        File result;
11584        do {
11585            result = new File(targetDir, packageName + "-" + suffix);
11586            suffix++;
11587        } while (result.exists());
11588        return result;
11589    }
11590
11591    // Utility method that returns the relative package path with respect
11592    // to the installation directory. Like say for /data/data/com.test-1.apk
11593    // string com.test-1 is returned.
11594    static String deriveCodePathName(String codePath) {
11595        if (codePath == null) {
11596            return null;
11597        }
11598        final File codeFile = new File(codePath);
11599        final String name = codeFile.getName();
11600        if (codeFile.isDirectory()) {
11601            return name;
11602        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11603            final int lastDot = name.lastIndexOf('.');
11604            return name.substring(0, lastDot);
11605        } else {
11606            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11607            return null;
11608        }
11609    }
11610
11611    class PackageInstalledInfo {
11612        String name;
11613        int uid;
11614        // The set of users that originally had this package installed.
11615        int[] origUsers;
11616        // The set of users that now have this package installed.
11617        int[] newUsers;
11618        PackageParser.Package pkg;
11619        int returnCode;
11620        String returnMsg;
11621        PackageRemovedInfo removedInfo;
11622
11623        public void setError(int code, String msg) {
11624            returnCode = code;
11625            returnMsg = msg;
11626            Slog.w(TAG, msg);
11627        }
11628
11629        public void setError(String msg, PackageParserException e) {
11630            returnCode = e.error;
11631            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11632            Slog.w(TAG, msg, e);
11633        }
11634
11635        public void setError(String msg, PackageManagerException e) {
11636            returnCode = e.error;
11637            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11638            Slog.w(TAG, msg, e);
11639        }
11640
11641        // In some error cases we want to convey more info back to the observer
11642        String origPackage;
11643        String origPermission;
11644    }
11645
11646    /*
11647     * Install a non-existing package.
11648     */
11649    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11650            UserHandle user, String installerPackageName, String volumeUuid,
11651            PackageInstalledInfo res) {
11652        // Remember this for later, in case we need to rollback this install
11653        String pkgName = pkg.packageName;
11654
11655        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11656        final boolean dataDirExists = Environment
11657                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11658        synchronized(mPackages) {
11659            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11660                // A package with the same name is already installed, though
11661                // it has been renamed to an older name.  The package we
11662                // are trying to install should be installed as an update to
11663                // the existing one, but that has not been requested, so bail.
11664                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11665                        + " without first uninstalling package running as "
11666                        + mSettings.mRenamedPackages.get(pkgName));
11667                return;
11668            }
11669            if (mPackages.containsKey(pkgName)) {
11670                // Don't allow installation over an existing package with the same name.
11671                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11672                        + " without first uninstalling.");
11673                return;
11674            }
11675        }
11676
11677        try {
11678            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11679                    System.currentTimeMillis(), user);
11680
11681            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11682            // delete the partially installed application. the data directory will have to be
11683            // restored if it was already existing
11684            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11685                // remove package from internal structures.  Note that we want deletePackageX to
11686                // delete the package data and cache directories that it created in
11687                // scanPackageLocked, unless those directories existed before we even tried to
11688                // install.
11689                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11690                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11691                                res.removedInfo, true);
11692            }
11693
11694        } catch (PackageManagerException e) {
11695            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11696        }
11697    }
11698
11699    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11700        // Can't rotate keys during boot or if sharedUser.
11701        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11702                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11703            return false;
11704        }
11705        // app is using upgradeKeySets; make sure all are valid
11706        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11707        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11708        for (int i = 0; i < upgradeKeySets.length; i++) {
11709            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11710                Slog.wtf(TAG, "Package "
11711                         + (oldPs.name != null ? oldPs.name : "<null>")
11712                         + " contains upgrade-key-set reference to unknown key-set: "
11713                         + upgradeKeySets[i]
11714                         + " reverting to signatures check.");
11715                return false;
11716            }
11717        }
11718        return true;
11719    }
11720
11721    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11722        // Upgrade keysets are being used.  Determine if new package has a superset of the
11723        // required keys.
11724        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11725        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11726        for (int i = 0; i < upgradeKeySets.length; i++) {
11727            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11728            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11729                return true;
11730            }
11731        }
11732        return false;
11733    }
11734
11735    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11736            UserHandle user, String installerPackageName, String volumeUuid,
11737            PackageInstalledInfo res) {
11738        final PackageParser.Package oldPackage;
11739        final String pkgName = pkg.packageName;
11740        final int[] allUsers;
11741        final boolean[] perUserInstalled;
11742        final boolean weFroze;
11743
11744        // First find the old package info and check signatures
11745        synchronized(mPackages) {
11746            oldPackage = mPackages.get(pkgName);
11747            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11748            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11749            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11750                if(!checkUpgradeKeySetLP(ps, pkg)) {
11751                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11752                            "New package not signed by keys specified by upgrade-keysets: "
11753                            + pkgName);
11754                    return;
11755                }
11756            } else {
11757                // default to original signature matching
11758                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11759                    != PackageManager.SIGNATURE_MATCH) {
11760                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11761                            "New package has a different signature: " + pkgName);
11762                    return;
11763                }
11764            }
11765
11766            // In case of rollback, remember per-user/profile install state
11767            allUsers = sUserManager.getUserIds();
11768            perUserInstalled = new boolean[allUsers.length];
11769            for (int i = 0; i < allUsers.length; i++) {
11770                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11771            }
11772
11773            // Mark the app as frozen to prevent launching during the upgrade
11774            // process, and then kill all running instances
11775            if (!ps.frozen) {
11776                ps.frozen = true;
11777                weFroze = true;
11778            } else {
11779                weFroze = false;
11780            }
11781        }
11782
11783        // Now that we're guarded by frozen state, kill app during upgrade
11784        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11785
11786        try {
11787            boolean sysPkg = (isSystemApp(oldPackage));
11788            if (sysPkg) {
11789                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11790                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11791            } else {
11792                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11793                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11794            }
11795        } finally {
11796            // Regardless of success or failure of upgrade steps above, always
11797            // unfreeze the package if we froze it
11798            if (weFroze) {
11799                unfreezePackage(pkgName);
11800            }
11801        }
11802    }
11803
11804    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11805            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11806            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11807            String volumeUuid, PackageInstalledInfo res) {
11808        String pkgName = deletedPackage.packageName;
11809        boolean deletedPkg = true;
11810        boolean updatedSettings = false;
11811
11812        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11813                + deletedPackage);
11814        long origUpdateTime;
11815        if (pkg.mExtras != null) {
11816            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11817        } else {
11818            origUpdateTime = 0;
11819        }
11820
11821        // First delete the existing package while retaining the data directory
11822        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11823                res.removedInfo, true)) {
11824            // If the existing package wasn't successfully deleted
11825            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11826            deletedPkg = false;
11827        } else {
11828            // Successfully deleted the old package; proceed with replace.
11829
11830            // If deleted package lived in a container, give users a chance to
11831            // relinquish resources before killing.
11832            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11833                if (DEBUG_INSTALL) {
11834                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11835                }
11836                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11837                final ArrayList<String> pkgList = new ArrayList<String>(1);
11838                pkgList.add(deletedPackage.applicationInfo.packageName);
11839                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11840            }
11841
11842            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11843            try {
11844                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11845                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11846                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11847                        perUserInstalled, res, user);
11848                updatedSettings = true;
11849            } catch (PackageManagerException e) {
11850                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11851            }
11852        }
11853
11854        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11855            // remove package from internal structures.  Note that we want deletePackageX to
11856            // delete the package data and cache directories that it created in
11857            // scanPackageLocked, unless those directories existed before we even tried to
11858            // install.
11859            if(updatedSettings) {
11860                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11861                deletePackageLI(
11862                        pkgName, null, true, allUsers, perUserInstalled,
11863                        PackageManager.DELETE_KEEP_DATA,
11864                                res.removedInfo, true);
11865            }
11866            // Since we failed to install the new package we need to restore the old
11867            // package that we deleted.
11868            if (deletedPkg) {
11869                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11870                File restoreFile = new File(deletedPackage.codePath);
11871                // Parse old package
11872                boolean oldExternal = isExternal(deletedPackage);
11873                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11874                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11875                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11876                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11877                try {
11878                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11879                } catch (PackageManagerException e) {
11880                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11881                            + e.getMessage());
11882                    return;
11883                }
11884                // Restore of old package succeeded. Update permissions.
11885                // writer
11886                synchronized (mPackages) {
11887                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11888                            UPDATE_PERMISSIONS_ALL);
11889                    // can downgrade to reader
11890                    mSettings.writeLPr();
11891                }
11892                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11893            }
11894        }
11895    }
11896
11897    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11898            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11899            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11900            String volumeUuid, PackageInstalledInfo res) {
11901        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11902                + ", old=" + deletedPackage);
11903        boolean disabledSystem = false;
11904        boolean updatedSettings = false;
11905        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11906        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11907                != 0) {
11908            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11909        }
11910        String packageName = deletedPackage.packageName;
11911        if (packageName == null) {
11912            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11913                    "Attempt to delete null packageName.");
11914            return;
11915        }
11916        PackageParser.Package oldPkg;
11917        PackageSetting oldPkgSetting;
11918        // reader
11919        synchronized (mPackages) {
11920            oldPkg = mPackages.get(packageName);
11921            oldPkgSetting = mSettings.mPackages.get(packageName);
11922            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11923                    (oldPkgSetting == null)) {
11924                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11925                        "Couldn't find package:" + packageName + " information");
11926                return;
11927            }
11928        }
11929
11930        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11931        res.removedInfo.removedPackage = packageName;
11932        // Remove existing system package
11933        removePackageLI(oldPkgSetting, true);
11934        // writer
11935        synchronized (mPackages) {
11936            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11937            if (!disabledSystem && deletedPackage != null) {
11938                // We didn't need to disable the .apk as a current system package,
11939                // which means we are replacing another update that is already
11940                // installed.  We need to make sure to delete the older one's .apk.
11941                res.removedInfo.args = createInstallArgsForExisting(0,
11942                        deletedPackage.applicationInfo.getCodePath(),
11943                        deletedPackage.applicationInfo.getResourcePath(),
11944                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11945            } else {
11946                res.removedInfo.args = null;
11947            }
11948        }
11949
11950        // Successfully disabled the old package. Now proceed with re-installation
11951        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11952
11953        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11954        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11955
11956        PackageParser.Package newPackage = null;
11957        try {
11958            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11959            if (newPackage.mExtras != null) {
11960                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11961                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11962                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11963
11964                // is the update attempting to change shared user? that isn't going to work...
11965                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11966                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11967                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11968                            + " to " + newPkgSetting.sharedUser);
11969                    updatedSettings = true;
11970                }
11971            }
11972
11973            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11974                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11975                        perUserInstalled, res, user);
11976                updatedSettings = true;
11977            }
11978
11979        } catch (PackageManagerException e) {
11980            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11981        }
11982
11983        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11984            // Re installation failed. Restore old information
11985            // Remove new pkg information
11986            if (newPackage != null) {
11987                removeInstalledPackageLI(newPackage, true);
11988            }
11989            // Add back the old system package
11990            try {
11991                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11992            } catch (PackageManagerException e) {
11993                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11994            }
11995            // Restore the old system information in Settings
11996            synchronized (mPackages) {
11997                if (disabledSystem) {
11998                    mSettings.enableSystemPackageLPw(packageName);
11999                }
12000                if (updatedSettings) {
12001                    mSettings.setInstallerPackageName(packageName,
12002                            oldPkgSetting.installerPackageName);
12003                }
12004                mSettings.writeLPr();
12005            }
12006        }
12007    }
12008
12009    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12010            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12011            UserHandle user) {
12012        String pkgName = newPackage.packageName;
12013        synchronized (mPackages) {
12014            //write settings. the installStatus will be incomplete at this stage.
12015            //note that the new package setting would have already been
12016            //added to mPackages. It hasn't been persisted yet.
12017            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12018            mSettings.writeLPr();
12019        }
12020
12021        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12022
12023        synchronized (mPackages) {
12024            updatePermissionsLPw(newPackage.packageName, newPackage,
12025                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12026                            ? UPDATE_PERMISSIONS_ALL : 0));
12027            // For system-bundled packages, we assume that installing an upgraded version
12028            // of the package implies that the user actually wants to run that new code,
12029            // so we enable the package.
12030            PackageSetting ps = mSettings.mPackages.get(pkgName);
12031            if (ps != null) {
12032                if (isSystemApp(newPackage)) {
12033                    // NB: implicit assumption that system package upgrades apply to all users
12034                    if (DEBUG_INSTALL) {
12035                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12036                    }
12037                    if (res.origUsers != null) {
12038                        for (int userHandle : res.origUsers) {
12039                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12040                                    userHandle, installerPackageName);
12041                        }
12042                    }
12043                    // Also convey the prior install/uninstall state
12044                    if (allUsers != null && perUserInstalled != null) {
12045                        for (int i = 0; i < allUsers.length; i++) {
12046                            if (DEBUG_INSTALL) {
12047                                Slog.d(TAG, "    user " + allUsers[i]
12048                                        + " => " + perUserInstalled[i]);
12049                            }
12050                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12051                        }
12052                        // these install state changes will be persisted in the
12053                        // upcoming call to mSettings.writeLPr().
12054                    }
12055                }
12056                // It's implied that when a user requests installation, they want the app to be
12057                // installed and enabled.
12058                int userId = user.getIdentifier();
12059                if (userId != UserHandle.USER_ALL) {
12060                    ps.setInstalled(true, userId);
12061                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12062                }
12063            }
12064            res.name = pkgName;
12065            res.uid = newPackage.applicationInfo.uid;
12066            res.pkg = newPackage;
12067            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12068            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12069            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12070            //to update install status
12071            mSettings.writeLPr();
12072        }
12073    }
12074
12075    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12076        final int installFlags = args.installFlags;
12077        final String installerPackageName = args.installerPackageName;
12078        final String volumeUuid = args.volumeUuid;
12079        final File tmpPackageFile = new File(args.getCodePath());
12080        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12081        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12082                || (args.volumeUuid != null));
12083        boolean replace = false;
12084        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12085        if (args.move != null) {
12086            // moving a complete application; perfom an initial scan on the new install location
12087            scanFlags |= SCAN_INITIAL;
12088        }
12089        // Result object to be returned
12090        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12091
12092        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12093        // Retrieve PackageSettings and parse package
12094        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12095                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12096                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12097        PackageParser pp = new PackageParser();
12098        pp.setSeparateProcesses(mSeparateProcesses);
12099        pp.setDisplayMetrics(mMetrics);
12100
12101        final PackageParser.Package pkg;
12102        try {
12103            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12104        } catch (PackageParserException e) {
12105            res.setError("Failed parse during installPackageLI", e);
12106            return;
12107        }
12108
12109        // Mark that we have an install time CPU ABI override.
12110        pkg.cpuAbiOverride = args.abiOverride;
12111
12112        String pkgName = res.name = pkg.packageName;
12113        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12114            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12115                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12116                return;
12117            }
12118        }
12119
12120        try {
12121            pp.collectCertificates(pkg, parseFlags);
12122            pp.collectManifestDigest(pkg);
12123        } catch (PackageParserException e) {
12124            res.setError("Failed collect during installPackageLI", e);
12125            return;
12126        }
12127
12128        /* If the installer passed in a manifest digest, compare it now. */
12129        if (args.manifestDigest != null) {
12130            if (DEBUG_INSTALL) {
12131                final String parsedManifest = pkg.manifestDigest == null ? "null"
12132                        : pkg.manifestDigest.toString();
12133                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12134                        + parsedManifest);
12135            }
12136
12137            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12138                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12139                return;
12140            }
12141        } else if (DEBUG_INSTALL) {
12142            final String parsedManifest = pkg.manifestDigest == null
12143                    ? "null" : pkg.manifestDigest.toString();
12144            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12145        }
12146
12147        // Get rid of all references to package scan path via parser.
12148        pp = null;
12149        String oldCodePath = null;
12150        boolean systemApp = false;
12151        synchronized (mPackages) {
12152            // Check if installing already existing package
12153            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12154                String oldName = mSettings.mRenamedPackages.get(pkgName);
12155                if (pkg.mOriginalPackages != null
12156                        && pkg.mOriginalPackages.contains(oldName)
12157                        && mPackages.containsKey(oldName)) {
12158                    // This package is derived from an original package,
12159                    // and this device has been updating from that original
12160                    // name.  We must continue using the original name, so
12161                    // rename the new package here.
12162                    pkg.setPackageName(oldName);
12163                    pkgName = pkg.packageName;
12164                    replace = true;
12165                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12166                            + oldName + " pkgName=" + pkgName);
12167                } else if (mPackages.containsKey(pkgName)) {
12168                    // This package, under its official name, already exists
12169                    // on the device; we should replace it.
12170                    replace = true;
12171                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12172                }
12173
12174                // Prevent apps opting out from runtime permissions
12175                if (replace) {
12176                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12177                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12178                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12179                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12180                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12181                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12182                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12183                                        + " doesn't support runtime permissions but the old"
12184                                        + " target SDK " + oldTargetSdk + " does.");
12185                        return;
12186                    }
12187                }
12188            }
12189
12190            PackageSetting ps = mSettings.mPackages.get(pkgName);
12191            if (ps != null) {
12192                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12193
12194                // Quick sanity check that we're signed correctly if updating;
12195                // we'll check this again later when scanning, but we want to
12196                // bail early here before tripping over redefined permissions.
12197                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12198                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12199                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12200                                + pkg.packageName + " upgrade keys do not match the "
12201                                + "previously installed version");
12202                        return;
12203                    }
12204                } else {
12205                    try {
12206                        verifySignaturesLP(ps, pkg);
12207                    } catch (PackageManagerException e) {
12208                        res.setError(e.error, e.getMessage());
12209                        return;
12210                    }
12211                }
12212
12213                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12214                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12215                    systemApp = (ps.pkg.applicationInfo.flags &
12216                            ApplicationInfo.FLAG_SYSTEM) != 0;
12217                }
12218                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12219            }
12220
12221            // Check whether the newly-scanned package wants to define an already-defined perm
12222            int N = pkg.permissions.size();
12223            for (int i = N-1; i >= 0; i--) {
12224                PackageParser.Permission perm = pkg.permissions.get(i);
12225                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12226                if (bp != null) {
12227                    // If the defining package is signed with our cert, it's okay.  This
12228                    // also includes the "updating the same package" case, of course.
12229                    // "updating same package" could also involve key-rotation.
12230                    final boolean sigsOk;
12231                    if (bp.sourcePackage.equals(pkg.packageName)
12232                            && (bp.packageSetting instanceof PackageSetting)
12233                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12234                                    scanFlags))) {
12235                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12236                    } else {
12237                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12238                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12239                    }
12240                    if (!sigsOk) {
12241                        // If the owning package is the system itself, we log but allow
12242                        // install to proceed; we fail the install on all other permission
12243                        // redefinitions.
12244                        if (!bp.sourcePackage.equals("android")) {
12245                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12246                                    + pkg.packageName + " attempting to redeclare permission "
12247                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12248                            res.origPermission = perm.info.name;
12249                            res.origPackage = bp.sourcePackage;
12250                            return;
12251                        } else {
12252                            Slog.w(TAG, "Package " + pkg.packageName
12253                                    + " attempting to redeclare system permission "
12254                                    + perm.info.name + "; ignoring new declaration");
12255                            pkg.permissions.remove(i);
12256                        }
12257                    }
12258                }
12259            }
12260
12261        }
12262
12263        if (systemApp && onExternal) {
12264            // Disable updates to system apps on sdcard
12265            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12266                    "Cannot install updates to system apps on sdcard");
12267            return;
12268        }
12269
12270        if (args.move != null) {
12271            // We did an in-place move, so dex is ready to roll
12272            scanFlags |= SCAN_NO_DEX;
12273            scanFlags |= SCAN_MOVE;
12274
12275            synchronized (mPackages) {
12276                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12277                if (ps == null) {
12278                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12279                            "Missing settings for moved package " + pkgName);
12280                }
12281
12282                // We moved the entire application as-is, so bring over the
12283                // previously derived ABI information.
12284                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12285                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12286            }
12287
12288        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12289            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12290            scanFlags |= SCAN_NO_DEX;
12291
12292            try {
12293                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12294                        true /* extract libs */);
12295            } catch (PackageManagerException pme) {
12296                Slog.e(TAG, "Error deriving application ABI", pme);
12297                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12298                return;
12299            }
12300
12301            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12302            int result = mPackageDexOptimizer
12303                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12304                            false /* defer */, false /* inclDependencies */);
12305            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12306                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12307                return;
12308            }
12309        }
12310
12311        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12312            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12313            return;
12314        }
12315
12316        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12317
12318        if (replace) {
12319            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12320                    installerPackageName, volumeUuid, res);
12321        } else {
12322            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12323                    args.user, installerPackageName, volumeUuid, res);
12324        }
12325        synchronized (mPackages) {
12326            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12327            if (ps != null) {
12328                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12329            }
12330        }
12331    }
12332
12333    private void startIntentFilterVerifications(int userId, boolean replacing,
12334            PackageParser.Package pkg) {
12335        if (mIntentFilterVerifierComponent == null) {
12336            Slog.w(TAG, "No IntentFilter verification will not be done as "
12337                    + "there is no IntentFilterVerifier available!");
12338            return;
12339        }
12340
12341        final int verifierUid = getPackageUid(
12342                mIntentFilterVerifierComponent.getPackageName(),
12343                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12344
12345        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12346        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12347        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12348        mHandler.sendMessage(msg);
12349    }
12350
12351    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12352            PackageParser.Package pkg) {
12353        int size = pkg.activities.size();
12354        if (size == 0) {
12355            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12356                    "No activity, so no need to verify any IntentFilter!");
12357            return;
12358        }
12359
12360        final boolean hasDomainURLs = hasDomainURLs(pkg);
12361        if (!hasDomainURLs) {
12362            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12363                    "No domain URLs, so no need to verify any IntentFilter!");
12364            return;
12365        }
12366
12367        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12368                + " if any IntentFilter from the " + size
12369                + " Activities needs verification ...");
12370
12371        int count = 0;
12372        final String packageName = pkg.packageName;
12373
12374        synchronized (mPackages) {
12375            // If this is a new install and we see that we've already run verification for this
12376            // package, we have nothing to do: it means the state was restored from backup.
12377            if (!replacing) {
12378                IntentFilterVerificationInfo ivi =
12379                        mSettings.getIntentFilterVerificationLPr(packageName);
12380                if (ivi != null) {
12381                    if (DEBUG_DOMAIN_VERIFICATION) {
12382                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12383                                + ivi.getStatusString());
12384                    }
12385                    return;
12386                }
12387            }
12388
12389            // If any filters need to be verified, then all need to be.
12390            boolean needToVerify = false;
12391            for (PackageParser.Activity a : pkg.activities) {
12392                for (ActivityIntentInfo filter : a.intents) {
12393                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12394                        if (DEBUG_DOMAIN_VERIFICATION) {
12395                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12396                        }
12397                        needToVerify = true;
12398                        break;
12399                    }
12400                }
12401            }
12402
12403            if (needToVerify) {
12404                final int verificationId = mIntentFilterVerificationToken++;
12405                for (PackageParser.Activity a : pkg.activities) {
12406                    for (ActivityIntentInfo filter : a.intents) {
12407                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12408                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12409                                    "Verification needed for IntentFilter:" + filter.toString());
12410                            mIntentFilterVerifier.addOneIntentFilterVerification(
12411                                    verifierUid, userId, verificationId, filter, packageName);
12412                            count++;
12413                        }
12414                    }
12415                }
12416            }
12417        }
12418
12419        if (count > 0) {
12420            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12421                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12422                    +  " for userId:" + userId);
12423            mIntentFilterVerifier.startVerifications(userId);
12424        } else {
12425            if (DEBUG_DOMAIN_VERIFICATION) {
12426                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12427            }
12428        }
12429    }
12430
12431    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12432        final ComponentName cn  = filter.activity.getComponentName();
12433        final String packageName = cn.getPackageName();
12434
12435        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12436                packageName);
12437        if (ivi == null) {
12438            return true;
12439        }
12440        int status = ivi.getStatus();
12441        switch (status) {
12442            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12443            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12444                return true;
12445
12446            default:
12447                // Nothing to do
12448                return false;
12449        }
12450    }
12451
12452    private static boolean isMultiArch(PackageSetting ps) {
12453        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12454    }
12455
12456    private static boolean isMultiArch(ApplicationInfo info) {
12457        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12458    }
12459
12460    private static boolean isExternal(PackageParser.Package pkg) {
12461        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12462    }
12463
12464    private static boolean isExternal(PackageSetting ps) {
12465        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12466    }
12467
12468    private static boolean isExternal(ApplicationInfo info) {
12469        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12470    }
12471
12472    private static boolean isSystemApp(PackageParser.Package pkg) {
12473        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12474    }
12475
12476    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12477        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12478    }
12479
12480    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12481        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12482    }
12483
12484    private static boolean isSystemApp(PackageSetting ps) {
12485        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12486    }
12487
12488    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12489        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12490    }
12491
12492    private int packageFlagsToInstallFlags(PackageSetting ps) {
12493        int installFlags = 0;
12494        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12495            // This existing package was an external ASEC install when we have
12496            // the external flag without a UUID
12497            installFlags |= PackageManager.INSTALL_EXTERNAL;
12498        }
12499        if (ps.isForwardLocked()) {
12500            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12501        }
12502        return installFlags;
12503    }
12504
12505    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12506        if (isExternal(pkg)) {
12507            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12508                return mSettings.getExternalVersion();
12509            } else {
12510                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12511            }
12512        } else {
12513            return mSettings.getInternalVersion();
12514        }
12515    }
12516
12517    private void deleteTempPackageFiles() {
12518        final FilenameFilter filter = new FilenameFilter() {
12519            public boolean accept(File dir, String name) {
12520                return name.startsWith("vmdl") && name.endsWith(".tmp");
12521            }
12522        };
12523        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12524            file.delete();
12525        }
12526    }
12527
12528    @Override
12529    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12530            int flags) {
12531        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12532                flags);
12533    }
12534
12535    @Override
12536    public void deletePackage(final String packageName,
12537            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12538        mContext.enforceCallingOrSelfPermission(
12539                android.Manifest.permission.DELETE_PACKAGES, null);
12540        Preconditions.checkNotNull(packageName);
12541        Preconditions.checkNotNull(observer);
12542        final int uid = Binder.getCallingUid();
12543        if (UserHandle.getUserId(uid) != userId) {
12544            mContext.enforceCallingPermission(
12545                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12546                    "deletePackage for user " + userId);
12547        }
12548        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12549            try {
12550                observer.onPackageDeleted(packageName,
12551                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12552            } catch (RemoteException re) {
12553            }
12554            return;
12555        }
12556
12557        boolean uninstallBlocked = false;
12558        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12559            int[] users = sUserManager.getUserIds();
12560            for (int i = 0; i < users.length; ++i) {
12561                if (getBlockUninstallForUser(packageName, users[i])) {
12562                    uninstallBlocked = true;
12563                    break;
12564                }
12565            }
12566        } else {
12567            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12568        }
12569        if (uninstallBlocked) {
12570            try {
12571                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12572                        null);
12573            } catch (RemoteException re) {
12574            }
12575            return;
12576        }
12577
12578        if (DEBUG_REMOVE) {
12579            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12580        }
12581        // Queue up an async operation since the package deletion may take a little while.
12582        mHandler.post(new Runnable() {
12583            public void run() {
12584                mHandler.removeCallbacks(this);
12585                final int returnCode = deletePackageX(packageName, userId, flags);
12586                if (observer != null) {
12587                    try {
12588                        observer.onPackageDeleted(packageName, returnCode, null);
12589                    } catch (RemoteException e) {
12590                        Log.i(TAG, "Observer no longer exists.");
12591                    } //end catch
12592                } //end if
12593            } //end run
12594        });
12595    }
12596
12597    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12598        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12599                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12600        try {
12601            if (dpm != null) {
12602                if (dpm.isDeviceOwner(packageName)) {
12603                    return true;
12604                }
12605                int[] users;
12606                if (userId == UserHandle.USER_ALL) {
12607                    users = sUserManager.getUserIds();
12608                } else {
12609                    users = new int[]{userId};
12610                }
12611                for (int i = 0; i < users.length; ++i) {
12612                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12613                        return true;
12614                    }
12615                }
12616            }
12617        } catch (RemoteException e) {
12618        }
12619        return false;
12620    }
12621
12622    /**
12623     *  This method is an internal method that could be get invoked either
12624     *  to delete an installed package or to clean up a failed installation.
12625     *  After deleting an installed package, a broadcast is sent to notify any
12626     *  listeners that the package has been installed. For cleaning up a failed
12627     *  installation, the broadcast is not necessary since the package's
12628     *  installation wouldn't have sent the initial broadcast either
12629     *  The key steps in deleting a package are
12630     *  deleting the package information in internal structures like mPackages,
12631     *  deleting the packages base directories through installd
12632     *  updating mSettings to reflect current status
12633     *  persisting settings for later use
12634     *  sending a broadcast if necessary
12635     */
12636    private int deletePackageX(String packageName, int userId, int flags) {
12637        final PackageRemovedInfo info = new PackageRemovedInfo();
12638        final boolean res;
12639
12640        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12641                ? UserHandle.ALL : new UserHandle(userId);
12642
12643        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12644            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12645            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12646        }
12647
12648        boolean removedForAllUsers = false;
12649        boolean systemUpdate = false;
12650
12651        // for the uninstall-updates case and restricted profiles, remember the per-
12652        // userhandle installed state
12653        int[] allUsers;
12654        boolean[] perUserInstalled;
12655        synchronized (mPackages) {
12656            PackageSetting ps = mSettings.mPackages.get(packageName);
12657            allUsers = sUserManager.getUserIds();
12658            perUserInstalled = new boolean[allUsers.length];
12659            for (int i = 0; i < allUsers.length; i++) {
12660                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12661            }
12662        }
12663
12664        synchronized (mInstallLock) {
12665            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12666            res = deletePackageLI(packageName, removeForUser,
12667                    true, allUsers, perUserInstalled,
12668                    flags | REMOVE_CHATTY, info, true);
12669            systemUpdate = info.isRemovedPackageSystemUpdate;
12670            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12671                removedForAllUsers = true;
12672            }
12673            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12674                    + " removedForAllUsers=" + removedForAllUsers);
12675        }
12676
12677        if (res) {
12678            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12679
12680            // If the removed package was a system update, the old system package
12681            // was re-enabled; we need to broadcast this information
12682            if (systemUpdate) {
12683                Bundle extras = new Bundle(1);
12684                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12685                        ? info.removedAppId : info.uid);
12686                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12687
12688                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12689                        extras, null, null, null);
12690                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12691                        extras, null, null, null);
12692                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12693                        null, packageName, null, null);
12694            }
12695        }
12696        // Force a gc here.
12697        Runtime.getRuntime().gc();
12698        // Delete the resources here after sending the broadcast to let
12699        // other processes clean up before deleting resources.
12700        if (info.args != null) {
12701            synchronized (mInstallLock) {
12702                info.args.doPostDeleteLI(true);
12703            }
12704        }
12705
12706        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12707    }
12708
12709    class PackageRemovedInfo {
12710        String removedPackage;
12711        int uid = -1;
12712        int removedAppId = -1;
12713        int[] removedUsers = null;
12714        boolean isRemovedPackageSystemUpdate = false;
12715        // Clean up resources deleted packages.
12716        InstallArgs args = null;
12717
12718        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12719            Bundle extras = new Bundle(1);
12720            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12721            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12722            if (replacing) {
12723                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12724            }
12725            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12726            if (removedPackage != null) {
12727                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12728                        extras, null, null, removedUsers);
12729                if (fullRemove && !replacing) {
12730                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12731                            extras, null, null, removedUsers);
12732                }
12733            }
12734            if (removedAppId >= 0) {
12735                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12736                        removedUsers);
12737            }
12738        }
12739    }
12740
12741    /*
12742     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12743     * flag is not set, the data directory is removed as well.
12744     * make sure this flag is set for partially installed apps. If not its meaningless to
12745     * delete a partially installed application.
12746     */
12747    private void removePackageDataLI(PackageSetting ps,
12748            int[] allUserHandles, boolean[] perUserInstalled,
12749            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12750        String packageName = ps.name;
12751        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12752        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12753        // Retrieve object to delete permissions for shared user later on
12754        final PackageSetting deletedPs;
12755        // reader
12756        synchronized (mPackages) {
12757            deletedPs = mSettings.mPackages.get(packageName);
12758            if (outInfo != null) {
12759                outInfo.removedPackage = packageName;
12760                outInfo.removedUsers = deletedPs != null
12761                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12762                        : null;
12763            }
12764        }
12765        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12766            removeDataDirsLI(ps.volumeUuid, packageName);
12767            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12768        }
12769        // writer
12770        synchronized (mPackages) {
12771            if (deletedPs != null) {
12772                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12773                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12774                    clearDefaultBrowserIfNeeded(packageName);
12775                    if (outInfo != null) {
12776                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12777                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12778                    }
12779                    updatePermissionsLPw(deletedPs.name, null, 0);
12780                    if (deletedPs.sharedUser != null) {
12781                        // Remove permissions associated with package. Since runtime
12782                        // permissions are per user we have to kill the removed package
12783                        // or packages running under the shared user of the removed
12784                        // package if revoking the permissions requested only by the removed
12785                        // package is successful and this causes a change in gids.
12786                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12787                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12788                                    userId);
12789                            if (userIdToKill == UserHandle.USER_ALL
12790                                    || userIdToKill >= UserHandle.USER_OWNER) {
12791                                // If gids changed for this user, kill all affected packages.
12792                                mHandler.post(new Runnable() {
12793                                    @Override
12794                                    public void run() {
12795                                        // This has to happen with no lock held.
12796                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12797                                                KILL_APP_REASON_GIDS_CHANGED);
12798                                    }
12799                                });
12800                                break;
12801                            }
12802                        }
12803                    }
12804                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12805                }
12806                // make sure to preserve per-user disabled state if this removal was just
12807                // a downgrade of a system app to the factory package
12808                if (allUserHandles != null && perUserInstalled != null) {
12809                    if (DEBUG_REMOVE) {
12810                        Slog.d(TAG, "Propagating install state across downgrade");
12811                    }
12812                    for (int i = 0; i < allUserHandles.length; i++) {
12813                        if (DEBUG_REMOVE) {
12814                            Slog.d(TAG, "    user " + allUserHandles[i]
12815                                    + " => " + perUserInstalled[i]);
12816                        }
12817                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12818                    }
12819                }
12820            }
12821            // can downgrade to reader
12822            if (writeSettings) {
12823                // Save settings now
12824                mSettings.writeLPr();
12825            }
12826        }
12827        if (outInfo != null) {
12828            // A user ID was deleted here. Go through all users and remove it
12829            // from KeyStore.
12830            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12831        }
12832    }
12833
12834    static boolean locationIsPrivileged(File path) {
12835        try {
12836            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12837                    .getCanonicalPath();
12838            return path.getCanonicalPath().startsWith(privilegedAppDir);
12839        } catch (IOException e) {
12840            Slog.e(TAG, "Unable to access code path " + path);
12841        }
12842        return false;
12843    }
12844
12845    /*
12846     * Tries to delete system package.
12847     */
12848    private boolean deleteSystemPackageLI(PackageSetting newPs,
12849            int[] allUserHandles, boolean[] perUserInstalled,
12850            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12851        final boolean applyUserRestrictions
12852                = (allUserHandles != null) && (perUserInstalled != null);
12853        PackageSetting disabledPs = null;
12854        // Confirm if the system package has been updated
12855        // An updated system app can be deleted. This will also have to restore
12856        // the system pkg from system partition
12857        // reader
12858        synchronized (mPackages) {
12859            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12860        }
12861        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12862                + " disabledPs=" + disabledPs);
12863        if (disabledPs == null) {
12864            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12865            return false;
12866        } else if (DEBUG_REMOVE) {
12867            Slog.d(TAG, "Deleting system pkg from data partition");
12868        }
12869        if (DEBUG_REMOVE) {
12870            if (applyUserRestrictions) {
12871                Slog.d(TAG, "Remembering install states:");
12872                for (int i = 0; i < allUserHandles.length; i++) {
12873                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12874                }
12875            }
12876        }
12877        // Delete the updated package
12878        outInfo.isRemovedPackageSystemUpdate = true;
12879        if (disabledPs.versionCode < newPs.versionCode) {
12880            // Delete data for downgrades
12881            flags &= ~PackageManager.DELETE_KEEP_DATA;
12882        } else {
12883            // Preserve data by setting flag
12884            flags |= PackageManager.DELETE_KEEP_DATA;
12885        }
12886        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12887                allUserHandles, perUserInstalled, outInfo, writeSettings);
12888        if (!ret) {
12889            return false;
12890        }
12891        // writer
12892        synchronized (mPackages) {
12893            // Reinstate the old system package
12894            mSettings.enableSystemPackageLPw(newPs.name);
12895            // Remove any native libraries from the upgraded package.
12896            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12897        }
12898        // Install the system package
12899        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12900        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12901        if (locationIsPrivileged(disabledPs.codePath)) {
12902            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12903        }
12904
12905        final PackageParser.Package newPkg;
12906        try {
12907            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12908        } catch (PackageManagerException e) {
12909            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12910            return false;
12911        }
12912
12913        // writer
12914        synchronized (mPackages) {
12915            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12916
12917            // Propagate the permissions state as we do want to drop on the floor
12918            // runtime permissions. The update permissions method below will take
12919            // care of removing obsolete permissions and grant install permissions.
12920            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12921            updatePermissionsLPw(newPkg.packageName, newPkg,
12922                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12923
12924            if (applyUserRestrictions) {
12925                if (DEBUG_REMOVE) {
12926                    Slog.d(TAG, "Propagating install state across reinstall");
12927                }
12928                for (int i = 0; i < allUserHandles.length; i++) {
12929                    if (DEBUG_REMOVE) {
12930                        Slog.d(TAG, "    user " + allUserHandles[i]
12931                                + " => " + perUserInstalled[i]);
12932                    }
12933                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12934                }
12935                // Regardless of writeSettings we need to ensure that this restriction
12936                // state propagation is persisted
12937                mSettings.writeAllUsersPackageRestrictionsLPr();
12938            }
12939            // can downgrade to reader here
12940            if (writeSettings) {
12941                mSettings.writeLPr();
12942            }
12943        }
12944        return true;
12945    }
12946
12947    private boolean deleteInstalledPackageLI(PackageSetting ps,
12948            boolean deleteCodeAndResources, int flags,
12949            int[] allUserHandles, boolean[] perUserInstalled,
12950            PackageRemovedInfo outInfo, boolean writeSettings) {
12951        if (outInfo != null) {
12952            outInfo.uid = ps.appId;
12953        }
12954
12955        // Delete package data from internal structures and also remove data if flag is set
12956        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12957
12958        // Delete application code and resources
12959        if (deleteCodeAndResources && (outInfo != null)) {
12960            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12961                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12962            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12963        }
12964        return true;
12965    }
12966
12967    @Override
12968    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12969            int userId) {
12970        mContext.enforceCallingOrSelfPermission(
12971                android.Manifest.permission.DELETE_PACKAGES, null);
12972        synchronized (mPackages) {
12973            PackageSetting ps = mSettings.mPackages.get(packageName);
12974            if (ps == null) {
12975                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12976                return false;
12977            }
12978            if (!ps.getInstalled(userId)) {
12979                // Can't block uninstall for an app that is not installed or enabled.
12980                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12981                return false;
12982            }
12983            ps.setBlockUninstall(blockUninstall, userId);
12984            mSettings.writePackageRestrictionsLPr(userId);
12985        }
12986        return true;
12987    }
12988
12989    @Override
12990    public boolean getBlockUninstallForUser(String packageName, int userId) {
12991        synchronized (mPackages) {
12992            PackageSetting ps = mSettings.mPackages.get(packageName);
12993            if (ps == null) {
12994                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12995                return false;
12996            }
12997            return ps.getBlockUninstall(userId);
12998        }
12999    }
13000
13001    /*
13002     * This method handles package deletion in general
13003     */
13004    private boolean deletePackageLI(String packageName, UserHandle user,
13005            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13006            int flags, PackageRemovedInfo outInfo,
13007            boolean writeSettings) {
13008        if (packageName == null) {
13009            Slog.w(TAG, "Attempt to delete null packageName.");
13010            return false;
13011        }
13012        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13013        PackageSetting ps;
13014        boolean dataOnly = false;
13015        int removeUser = -1;
13016        int appId = -1;
13017        synchronized (mPackages) {
13018            ps = mSettings.mPackages.get(packageName);
13019            if (ps == null) {
13020                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13021                return false;
13022            }
13023            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13024                    && user.getIdentifier() != UserHandle.USER_ALL) {
13025                // The caller is asking that the package only be deleted for a single
13026                // user.  To do this, we just mark its uninstalled state and delete
13027                // its data.  If this is a system app, we only allow this to happen if
13028                // they have set the special DELETE_SYSTEM_APP which requests different
13029                // semantics than normal for uninstalling system apps.
13030                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13031                ps.setUserState(user.getIdentifier(),
13032                        COMPONENT_ENABLED_STATE_DEFAULT,
13033                        false, //installed
13034                        true,  //stopped
13035                        true,  //notLaunched
13036                        false, //hidden
13037                        null, null, null,
13038                        false, // blockUninstall
13039                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0);
13040                if (!isSystemApp(ps)) {
13041                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13042                        // Other user still have this package installed, so all
13043                        // we need to do is clear this user's data and save that
13044                        // it is uninstalled.
13045                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13046                        removeUser = user.getIdentifier();
13047                        appId = ps.appId;
13048                        scheduleWritePackageRestrictionsLocked(removeUser);
13049                    } else {
13050                        // We need to set it back to 'installed' so the uninstall
13051                        // broadcasts will be sent correctly.
13052                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13053                        ps.setInstalled(true, user.getIdentifier());
13054                    }
13055                } else {
13056                    // This is a system app, so we assume that the
13057                    // other users still have this package installed, so all
13058                    // we need to do is clear this user's data and save that
13059                    // it is uninstalled.
13060                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13061                    removeUser = user.getIdentifier();
13062                    appId = ps.appId;
13063                    scheduleWritePackageRestrictionsLocked(removeUser);
13064                }
13065            }
13066        }
13067
13068        if (removeUser >= 0) {
13069            // From above, we determined that we are deleting this only
13070            // for a single user.  Continue the work here.
13071            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13072            if (outInfo != null) {
13073                outInfo.removedPackage = packageName;
13074                outInfo.removedAppId = appId;
13075                outInfo.removedUsers = new int[] {removeUser};
13076            }
13077            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13078            removeKeystoreDataIfNeeded(removeUser, appId);
13079            schedulePackageCleaning(packageName, removeUser, false);
13080            synchronized (mPackages) {
13081                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13082                    scheduleWritePackageRestrictionsLocked(removeUser);
13083                }
13084                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13085            }
13086            return true;
13087        }
13088
13089        if (dataOnly) {
13090            // Delete application data first
13091            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13092            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13093            return true;
13094        }
13095
13096        boolean ret = false;
13097        if (isSystemApp(ps)) {
13098            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13099            // When an updated system application is deleted we delete the existing resources as well and
13100            // fall back to existing code in system partition
13101            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13102                    flags, outInfo, writeSettings);
13103        } else {
13104            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13105            // Kill application pre-emptively especially for apps on sd.
13106            killApplication(packageName, ps.appId, "uninstall pkg");
13107            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13108                    allUserHandles, perUserInstalled,
13109                    outInfo, writeSettings);
13110        }
13111
13112        return ret;
13113    }
13114
13115    private final class ClearStorageConnection implements ServiceConnection {
13116        IMediaContainerService mContainerService;
13117
13118        @Override
13119        public void onServiceConnected(ComponentName name, IBinder service) {
13120            synchronized (this) {
13121                mContainerService = IMediaContainerService.Stub.asInterface(service);
13122                notifyAll();
13123            }
13124        }
13125
13126        @Override
13127        public void onServiceDisconnected(ComponentName name) {
13128        }
13129    }
13130
13131    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13132        final boolean mounted;
13133        if (Environment.isExternalStorageEmulated()) {
13134            mounted = true;
13135        } else {
13136            final String status = Environment.getExternalStorageState();
13137
13138            mounted = status.equals(Environment.MEDIA_MOUNTED)
13139                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13140        }
13141
13142        if (!mounted) {
13143            return;
13144        }
13145
13146        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13147        int[] users;
13148        if (userId == UserHandle.USER_ALL) {
13149            users = sUserManager.getUserIds();
13150        } else {
13151            users = new int[] { userId };
13152        }
13153        final ClearStorageConnection conn = new ClearStorageConnection();
13154        if (mContext.bindServiceAsUser(
13155                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13156            try {
13157                for (int curUser : users) {
13158                    long timeout = SystemClock.uptimeMillis() + 5000;
13159                    synchronized (conn) {
13160                        long now = SystemClock.uptimeMillis();
13161                        while (conn.mContainerService == null && now < timeout) {
13162                            try {
13163                                conn.wait(timeout - now);
13164                            } catch (InterruptedException e) {
13165                            }
13166                        }
13167                    }
13168                    if (conn.mContainerService == null) {
13169                        return;
13170                    }
13171
13172                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13173                    clearDirectory(conn.mContainerService,
13174                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13175                    if (allData) {
13176                        clearDirectory(conn.mContainerService,
13177                                userEnv.buildExternalStorageAppDataDirs(packageName));
13178                        clearDirectory(conn.mContainerService,
13179                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13180                    }
13181                }
13182            } finally {
13183                mContext.unbindService(conn);
13184            }
13185        }
13186    }
13187
13188    @Override
13189    public void clearApplicationUserData(final String packageName,
13190            final IPackageDataObserver observer, final int userId) {
13191        mContext.enforceCallingOrSelfPermission(
13192                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13193        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13194        // Queue up an async operation since the package deletion may take a little while.
13195        mHandler.post(new Runnable() {
13196            public void run() {
13197                mHandler.removeCallbacks(this);
13198                final boolean succeeded;
13199                synchronized (mInstallLock) {
13200                    succeeded = clearApplicationUserDataLI(packageName, userId);
13201                }
13202                clearExternalStorageDataSync(packageName, userId, true);
13203                if (succeeded) {
13204                    // invoke DeviceStorageMonitor's update method to clear any notifications
13205                    DeviceStorageMonitorInternal
13206                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13207                    if (dsm != null) {
13208                        dsm.checkMemory();
13209                    }
13210                }
13211                if(observer != null) {
13212                    try {
13213                        observer.onRemoveCompleted(packageName, succeeded);
13214                    } catch (RemoteException e) {
13215                        Log.i(TAG, "Observer no longer exists.");
13216                    }
13217                } //end if observer
13218            } //end run
13219        });
13220    }
13221
13222    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13223        if (packageName == null) {
13224            Slog.w(TAG, "Attempt to delete null packageName.");
13225            return false;
13226        }
13227
13228        // Try finding details about the requested package
13229        PackageParser.Package pkg;
13230        synchronized (mPackages) {
13231            pkg = mPackages.get(packageName);
13232            if (pkg == null) {
13233                final PackageSetting ps = mSettings.mPackages.get(packageName);
13234                if (ps != null) {
13235                    pkg = ps.pkg;
13236                }
13237            }
13238
13239            if (pkg == null) {
13240                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13241                return false;
13242            }
13243
13244            PackageSetting ps = (PackageSetting) pkg.mExtras;
13245            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13246        }
13247
13248        // Always delete data directories for package, even if we found no other
13249        // record of app. This helps users recover from UID mismatches without
13250        // resorting to a full data wipe.
13251        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13252        if (retCode < 0) {
13253            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13254            return false;
13255        }
13256
13257        final int appId = pkg.applicationInfo.uid;
13258        removeKeystoreDataIfNeeded(userId, appId);
13259
13260        // Create a native library symlink only if we have native libraries
13261        // and if the native libraries are 32 bit libraries. We do not provide
13262        // this symlink for 64 bit libraries.
13263        if (pkg.applicationInfo.primaryCpuAbi != null &&
13264                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13265            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13266            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13267                    nativeLibPath, userId) < 0) {
13268                Slog.w(TAG, "Failed linking native library dir");
13269                return false;
13270            }
13271        }
13272
13273        return true;
13274    }
13275
13276    /**
13277     * Reverts user permission state changes (permissions and flags).
13278     *
13279     * @param ps The package for which to reset.
13280     * @param userId The device user for which to do a reset.
13281     */
13282    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13283            final PackageSetting ps, final int userId) {
13284        if (ps.pkg == null) {
13285            return;
13286        }
13287
13288        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13289                | FLAG_PERMISSION_USER_FIXED
13290                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13291
13292        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13293                | FLAG_PERMISSION_POLICY_FIXED;
13294
13295        boolean writeInstallPermissions = false;
13296        boolean writeRuntimePermissions = false;
13297
13298        final int permissionCount = ps.pkg.requestedPermissions.size();
13299        for (int i = 0; i < permissionCount; i++) {
13300            String permission = ps.pkg.requestedPermissions.get(i);
13301
13302            BasePermission bp = mSettings.mPermissions.get(permission);
13303            if (bp == null) {
13304                continue;
13305            }
13306
13307            // If shared user we just reset the state to which only this app contributed.
13308            if (ps.sharedUser != null) {
13309                boolean used = false;
13310                final int packageCount = ps.sharedUser.packages.size();
13311                for (int j = 0; j < packageCount; j++) {
13312                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13313                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13314                            && pkg.pkg.requestedPermissions.contains(permission)) {
13315                        used = true;
13316                        break;
13317                    }
13318                }
13319                if (used) {
13320                    continue;
13321                }
13322            }
13323
13324            PermissionsState permissionsState = ps.getPermissionsState();
13325
13326            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13327
13328            // Always clear the user settable flags.
13329            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13330                    bp.name) != null;
13331            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13332                if (hasInstallState) {
13333                    writeInstallPermissions = true;
13334                } else {
13335                    writeRuntimePermissions = true;
13336                }
13337            }
13338
13339            // Below is only runtime permission handling.
13340            if (!bp.isRuntime()) {
13341                continue;
13342            }
13343
13344            // Never clobber system or policy.
13345            if ((oldFlags & policyOrSystemFlags) != 0) {
13346                continue;
13347            }
13348
13349            // If this permission was granted by default, make sure it is.
13350            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13351                if (permissionsState.grantRuntimePermission(bp, userId)
13352                        != PERMISSION_OPERATION_FAILURE) {
13353                    writeRuntimePermissions = true;
13354                }
13355            } else {
13356                // Otherwise, reset the permission.
13357                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13358                switch (revokeResult) {
13359                    case PERMISSION_OPERATION_SUCCESS: {
13360                        writeRuntimePermissions = true;
13361                    } break;
13362
13363                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13364                        writeRuntimePermissions = true;
13365                        // If gids changed for this user, kill all affected packages.
13366                        mHandler.post(new Runnable() {
13367                            @Override
13368                            public void run() {
13369                                // This has to happen with no lock held.
13370                                killSettingPackagesForUser(ps, userId,
13371                                        KILL_APP_REASON_GIDS_CHANGED);
13372                            }
13373                        });
13374                    } break;
13375                }
13376            }
13377        }
13378
13379        // Synchronously write as we are taking permissions away.
13380        if (writeRuntimePermissions) {
13381            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13382        }
13383
13384        // Synchronously write as we are taking permissions away.
13385        if (writeInstallPermissions) {
13386            mSettings.writeLPr();
13387        }
13388    }
13389
13390    /**
13391     * Remove entries from the keystore daemon. Will only remove it if the
13392     * {@code appId} is valid.
13393     */
13394    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13395        if (appId < 0) {
13396            return;
13397        }
13398
13399        final KeyStore keyStore = KeyStore.getInstance();
13400        if (keyStore != null) {
13401            if (userId == UserHandle.USER_ALL) {
13402                for (final int individual : sUserManager.getUserIds()) {
13403                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13404                }
13405            } else {
13406                keyStore.clearUid(UserHandle.getUid(userId, appId));
13407            }
13408        } else {
13409            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13410        }
13411    }
13412
13413    @Override
13414    public void deleteApplicationCacheFiles(final String packageName,
13415            final IPackageDataObserver observer) {
13416        mContext.enforceCallingOrSelfPermission(
13417                android.Manifest.permission.DELETE_CACHE_FILES, null);
13418        // Queue up an async operation since the package deletion may take a little while.
13419        final int userId = UserHandle.getCallingUserId();
13420        mHandler.post(new Runnable() {
13421            public void run() {
13422                mHandler.removeCallbacks(this);
13423                final boolean succeded;
13424                synchronized (mInstallLock) {
13425                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13426                }
13427                clearExternalStorageDataSync(packageName, userId, false);
13428                if (observer != null) {
13429                    try {
13430                        observer.onRemoveCompleted(packageName, succeded);
13431                    } catch (RemoteException e) {
13432                        Log.i(TAG, "Observer no longer exists.");
13433                    }
13434                } //end if observer
13435            } //end run
13436        });
13437    }
13438
13439    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13440        if (packageName == null) {
13441            Slog.w(TAG, "Attempt to delete null packageName.");
13442            return false;
13443        }
13444        PackageParser.Package p;
13445        synchronized (mPackages) {
13446            p = mPackages.get(packageName);
13447        }
13448        if (p == null) {
13449            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13450            return false;
13451        }
13452        final ApplicationInfo applicationInfo = p.applicationInfo;
13453        if (applicationInfo == null) {
13454            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13455            return false;
13456        }
13457        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13458        if (retCode < 0) {
13459            Slog.w(TAG, "Couldn't remove cache files for package: "
13460                       + packageName + " u" + userId);
13461            return false;
13462        }
13463        return true;
13464    }
13465
13466    @Override
13467    public void getPackageSizeInfo(final String packageName, int userHandle,
13468            final IPackageStatsObserver observer) {
13469        mContext.enforceCallingOrSelfPermission(
13470                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13471        if (packageName == null) {
13472            throw new IllegalArgumentException("Attempt to get size of null packageName");
13473        }
13474
13475        PackageStats stats = new PackageStats(packageName, userHandle);
13476
13477        /*
13478         * Queue up an async operation since the package measurement may take a
13479         * little while.
13480         */
13481        Message msg = mHandler.obtainMessage(INIT_COPY);
13482        msg.obj = new MeasureParams(stats, observer);
13483        mHandler.sendMessage(msg);
13484    }
13485
13486    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13487            PackageStats pStats) {
13488        if (packageName == null) {
13489            Slog.w(TAG, "Attempt to get size of null packageName.");
13490            return false;
13491        }
13492        PackageParser.Package p;
13493        boolean dataOnly = false;
13494        String libDirRoot = null;
13495        String asecPath = null;
13496        PackageSetting ps = null;
13497        synchronized (mPackages) {
13498            p = mPackages.get(packageName);
13499            ps = mSettings.mPackages.get(packageName);
13500            if(p == null) {
13501                dataOnly = true;
13502                if((ps == null) || (ps.pkg == null)) {
13503                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13504                    return false;
13505                }
13506                p = ps.pkg;
13507            }
13508            if (ps != null) {
13509                libDirRoot = ps.legacyNativeLibraryPathString;
13510            }
13511            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13512                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13513                if (secureContainerId != null) {
13514                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13515                }
13516            }
13517        }
13518        String publicSrcDir = null;
13519        if(!dataOnly) {
13520            final ApplicationInfo applicationInfo = p.applicationInfo;
13521            if (applicationInfo == null) {
13522                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13523                return false;
13524            }
13525            if (p.isForwardLocked()) {
13526                publicSrcDir = applicationInfo.getBaseResourcePath();
13527            }
13528        }
13529        // TODO: extend to measure size of split APKs
13530        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13531        // not just the first level.
13532        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13533        // just the primary.
13534        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13535        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13536                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13537        if (res < 0) {
13538            return false;
13539        }
13540
13541        // Fix-up for forward-locked applications in ASEC containers.
13542        if (!isExternal(p)) {
13543            pStats.codeSize += pStats.externalCodeSize;
13544            pStats.externalCodeSize = 0L;
13545        }
13546
13547        return true;
13548    }
13549
13550
13551    @Override
13552    public void addPackageToPreferred(String packageName) {
13553        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13554    }
13555
13556    @Override
13557    public void removePackageFromPreferred(String packageName) {
13558        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13559    }
13560
13561    @Override
13562    public List<PackageInfo> getPreferredPackages(int flags) {
13563        return new ArrayList<PackageInfo>();
13564    }
13565
13566    private int getUidTargetSdkVersionLockedLPr(int uid) {
13567        Object obj = mSettings.getUserIdLPr(uid);
13568        if (obj instanceof SharedUserSetting) {
13569            final SharedUserSetting sus = (SharedUserSetting) obj;
13570            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13571            final Iterator<PackageSetting> it = sus.packages.iterator();
13572            while (it.hasNext()) {
13573                final PackageSetting ps = it.next();
13574                if (ps.pkg != null) {
13575                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13576                    if (v < vers) vers = v;
13577                }
13578            }
13579            return vers;
13580        } else if (obj instanceof PackageSetting) {
13581            final PackageSetting ps = (PackageSetting) obj;
13582            if (ps.pkg != null) {
13583                return ps.pkg.applicationInfo.targetSdkVersion;
13584            }
13585        }
13586        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13587    }
13588
13589    @Override
13590    public void addPreferredActivity(IntentFilter filter, int match,
13591            ComponentName[] set, ComponentName activity, int userId) {
13592        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13593                "Adding preferred");
13594    }
13595
13596    private void addPreferredActivityInternal(IntentFilter filter, int match,
13597            ComponentName[] set, ComponentName activity, boolean always, int userId,
13598            String opname) {
13599        // writer
13600        int callingUid = Binder.getCallingUid();
13601        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13602        if (filter.countActions() == 0) {
13603            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13604            return;
13605        }
13606        synchronized (mPackages) {
13607            if (mContext.checkCallingOrSelfPermission(
13608                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13609                    != PackageManager.PERMISSION_GRANTED) {
13610                if (getUidTargetSdkVersionLockedLPr(callingUid)
13611                        < Build.VERSION_CODES.FROYO) {
13612                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13613                            + callingUid);
13614                    return;
13615                }
13616                mContext.enforceCallingOrSelfPermission(
13617                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13618            }
13619
13620            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13621            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13622                    + userId + ":");
13623            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13624            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13625            scheduleWritePackageRestrictionsLocked(userId);
13626        }
13627    }
13628
13629    @Override
13630    public void replacePreferredActivity(IntentFilter filter, int match,
13631            ComponentName[] set, ComponentName activity, int userId) {
13632        if (filter.countActions() != 1) {
13633            throw new IllegalArgumentException(
13634                    "replacePreferredActivity expects filter to have only 1 action.");
13635        }
13636        if (filter.countDataAuthorities() != 0
13637                || filter.countDataPaths() != 0
13638                || filter.countDataSchemes() > 1
13639                || filter.countDataTypes() != 0) {
13640            throw new IllegalArgumentException(
13641                    "replacePreferredActivity expects filter to have no data authorities, " +
13642                    "paths, or types; and at most one scheme.");
13643        }
13644
13645        final int callingUid = Binder.getCallingUid();
13646        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13647        synchronized (mPackages) {
13648            if (mContext.checkCallingOrSelfPermission(
13649                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13650                    != PackageManager.PERMISSION_GRANTED) {
13651                if (getUidTargetSdkVersionLockedLPr(callingUid)
13652                        < Build.VERSION_CODES.FROYO) {
13653                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13654                            + Binder.getCallingUid());
13655                    return;
13656                }
13657                mContext.enforceCallingOrSelfPermission(
13658                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13659            }
13660
13661            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13662            if (pir != null) {
13663                // Get all of the existing entries that exactly match this filter.
13664                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13665                if (existing != null && existing.size() == 1) {
13666                    PreferredActivity cur = existing.get(0);
13667                    if (DEBUG_PREFERRED) {
13668                        Slog.i(TAG, "Checking replace of preferred:");
13669                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13670                        if (!cur.mPref.mAlways) {
13671                            Slog.i(TAG, "  -- CUR; not mAlways!");
13672                        } else {
13673                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13674                            Slog.i(TAG, "  -- CUR: mSet="
13675                                    + Arrays.toString(cur.mPref.mSetComponents));
13676                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13677                            Slog.i(TAG, "  -- NEW: mMatch="
13678                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13679                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13680                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13681                        }
13682                    }
13683                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13684                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13685                            && cur.mPref.sameSet(set)) {
13686                        // Setting the preferred activity to what it happens to be already
13687                        if (DEBUG_PREFERRED) {
13688                            Slog.i(TAG, "Replacing with same preferred activity "
13689                                    + cur.mPref.mShortComponent + " for user "
13690                                    + userId + ":");
13691                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13692                        }
13693                        return;
13694                    }
13695                }
13696
13697                if (existing != null) {
13698                    if (DEBUG_PREFERRED) {
13699                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13700                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13701                    }
13702                    for (int i = 0; i < existing.size(); i++) {
13703                        PreferredActivity pa = existing.get(i);
13704                        if (DEBUG_PREFERRED) {
13705                            Slog.i(TAG, "Removing existing preferred activity "
13706                                    + pa.mPref.mComponent + ":");
13707                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13708                        }
13709                        pir.removeFilter(pa);
13710                    }
13711                }
13712            }
13713            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13714                    "Replacing preferred");
13715        }
13716    }
13717
13718    @Override
13719    public void clearPackagePreferredActivities(String packageName) {
13720        final int uid = Binder.getCallingUid();
13721        // writer
13722        synchronized (mPackages) {
13723            PackageParser.Package pkg = mPackages.get(packageName);
13724            if (pkg == null || pkg.applicationInfo.uid != uid) {
13725                if (mContext.checkCallingOrSelfPermission(
13726                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13727                        != PackageManager.PERMISSION_GRANTED) {
13728                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13729                            < Build.VERSION_CODES.FROYO) {
13730                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13731                                + Binder.getCallingUid());
13732                        return;
13733                    }
13734                    mContext.enforceCallingOrSelfPermission(
13735                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13736                }
13737            }
13738
13739            int user = UserHandle.getCallingUserId();
13740            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13741                scheduleWritePackageRestrictionsLocked(user);
13742            }
13743        }
13744    }
13745
13746    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13747    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13748        ArrayList<PreferredActivity> removed = null;
13749        boolean changed = false;
13750        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13751            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13752            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13753            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13754                continue;
13755            }
13756            Iterator<PreferredActivity> it = pir.filterIterator();
13757            while (it.hasNext()) {
13758                PreferredActivity pa = it.next();
13759                // Mark entry for removal only if it matches the package name
13760                // and the entry is of type "always".
13761                if (packageName == null ||
13762                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13763                                && pa.mPref.mAlways)) {
13764                    if (removed == null) {
13765                        removed = new ArrayList<PreferredActivity>();
13766                    }
13767                    removed.add(pa);
13768                }
13769            }
13770            if (removed != null) {
13771                for (int j=0; j<removed.size(); j++) {
13772                    PreferredActivity pa = removed.get(j);
13773                    pir.removeFilter(pa);
13774                }
13775                changed = true;
13776            }
13777        }
13778        return changed;
13779    }
13780
13781    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13782    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13783        if (userId == UserHandle.USER_ALL) {
13784            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13785                    sUserManager.getUserIds())) {
13786                for (int oneUserId : sUserManager.getUserIds()) {
13787                    scheduleWritePackageRestrictionsLocked(oneUserId);
13788                }
13789            }
13790        } else {
13791            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13792                scheduleWritePackageRestrictionsLocked(userId);
13793            }
13794        }
13795    }
13796
13797
13798    void clearDefaultBrowserIfNeeded(String packageName) {
13799        for (int oneUserId : sUserManager.getUserIds()) {
13800            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13801            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13802            if (packageName.equals(defaultBrowserPackageName)) {
13803                setDefaultBrowserPackageName(null, oneUserId);
13804            }
13805        }
13806    }
13807
13808    @Override
13809    public void resetPreferredActivities(int userId) {
13810        mContext.enforceCallingOrSelfPermission(
13811                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13812        // writer
13813        synchronized (mPackages) {
13814            clearPackagePreferredActivitiesLPw(null, userId);
13815            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13816            applyFactoryDefaultBrowserLPw(userId);
13817            primeDomainVerificationsLPw(userId);
13818
13819            scheduleWritePackageRestrictionsLocked(userId);
13820        }
13821    }
13822
13823    @Override
13824    public int getPreferredActivities(List<IntentFilter> outFilters,
13825            List<ComponentName> outActivities, String packageName) {
13826
13827        int num = 0;
13828        final int userId = UserHandle.getCallingUserId();
13829        // reader
13830        synchronized (mPackages) {
13831            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13832            if (pir != null) {
13833                final Iterator<PreferredActivity> it = pir.filterIterator();
13834                while (it.hasNext()) {
13835                    final PreferredActivity pa = it.next();
13836                    if (packageName == null
13837                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13838                                    && pa.mPref.mAlways)) {
13839                        if (outFilters != null) {
13840                            outFilters.add(new IntentFilter(pa));
13841                        }
13842                        if (outActivities != null) {
13843                            outActivities.add(pa.mPref.mComponent);
13844                        }
13845                    }
13846                }
13847            }
13848        }
13849
13850        return num;
13851    }
13852
13853    @Override
13854    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13855            int userId) {
13856        int callingUid = Binder.getCallingUid();
13857        if (callingUid != Process.SYSTEM_UID) {
13858            throw new SecurityException(
13859                    "addPersistentPreferredActivity can only be run by the system");
13860        }
13861        if (filter.countActions() == 0) {
13862            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13863            return;
13864        }
13865        synchronized (mPackages) {
13866            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13867                    " :");
13868            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13869            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13870                    new PersistentPreferredActivity(filter, activity));
13871            scheduleWritePackageRestrictionsLocked(userId);
13872        }
13873    }
13874
13875    @Override
13876    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13877        int callingUid = Binder.getCallingUid();
13878        if (callingUid != Process.SYSTEM_UID) {
13879            throw new SecurityException(
13880                    "clearPackagePersistentPreferredActivities can only be run by the system");
13881        }
13882        ArrayList<PersistentPreferredActivity> removed = null;
13883        boolean changed = false;
13884        synchronized (mPackages) {
13885            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13886                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13887                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13888                        .valueAt(i);
13889                if (userId != thisUserId) {
13890                    continue;
13891                }
13892                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13893                while (it.hasNext()) {
13894                    PersistentPreferredActivity ppa = it.next();
13895                    // Mark entry for removal only if it matches the package name.
13896                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13897                        if (removed == null) {
13898                            removed = new ArrayList<PersistentPreferredActivity>();
13899                        }
13900                        removed.add(ppa);
13901                    }
13902                }
13903                if (removed != null) {
13904                    for (int j=0; j<removed.size(); j++) {
13905                        PersistentPreferredActivity ppa = removed.get(j);
13906                        ppir.removeFilter(ppa);
13907                    }
13908                    changed = true;
13909                }
13910            }
13911
13912            if (changed) {
13913                scheduleWritePackageRestrictionsLocked(userId);
13914            }
13915        }
13916    }
13917
13918    /**
13919     * Common machinery for picking apart a restored XML blob and passing
13920     * it to a caller-supplied functor to be applied to the running system.
13921     */
13922    private void restoreFromXml(XmlPullParser parser, int userId,
13923            String expectedStartTag, BlobXmlRestorer functor)
13924            throws IOException, XmlPullParserException {
13925        int type;
13926        while ((type = parser.next()) != XmlPullParser.START_TAG
13927                && type != XmlPullParser.END_DOCUMENT) {
13928        }
13929        if (type != XmlPullParser.START_TAG) {
13930            // oops didn't find a start tag?!
13931            if (DEBUG_BACKUP) {
13932                Slog.e(TAG, "Didn't find start tag during restore");
13933            }
13934            return;
13935        }
13936
13937        // this is supposed to be TAG_PREFERRED_BACKUP
13938        if (!expectedStartTag.equals(parser.getName())) {
13939            if (DEBUG_BACKUP) {
13940                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13941            }
13942            return;
13943        }
13944
13945        // skip interfering stuff, then we're aligned with the backing implementation
13946        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13947        functor.apply(parser, userId);
13948    }
13949
13950    private interface BlobXmlRestorer {
13951        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13952    }
13953
13954    /**
13955     * Non-Binder method, support for the backup/restore mechanism: write the
13956     * full set of preferred activities in its canonical XML format.  Returns the
13957     * XML output as a byte array, or null if there is none.
13958     */
13959    @Override
13960    public byte[] getPreferredActivityBackup(int userId) {
13961        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13962            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13963        }
13964
13965        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13966        try {
13967            final XmlSerializer serializer = new FastXmlSerializer();
13968            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13969            serializer.startDocument(null, true);
13970            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13971
13972            synchronized (mPackages) {
13973                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13974            }
13975
13976            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13977            serializer.endDocument();
13978            serializer.flush();
13979        } catch (Exception e) {
13980            if (DEBUG_BACKUP) {
13981                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13982            }
13983            return null;
13984        }
13985
13986        return dataStream.toByteArray();
13987    }
13988
13989    @Override
13990    public void restorePreferredActivities(byte[] backup, int userId) {
13991        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13992            throw new SecurityException("Only the system may call restorePreferredActivities()");
13993        }
13994
13995        try {
13996            final XmlPullParser parser = Xml.newPullParser();
13997            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13998            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13999                    new BlobXmlRestorer() {
14000                        @Override
14001                        public void apply(XmlPullParser parser, int userId)
14002                                throws XmlPullParserException, IOException {
14003                            synchronized (mPackages) {
14004                                mSettings.readPreferredActivitiesLPw(parser, userId);
14005                            }
14006                        }
14007                    } );
14008        } catch (Exception e) {
14009            if (DEBUG_BACKUP) {
14010                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14011            }
14012        }
14013    }
14014
14015    /**
14016     * Non-Binder method, support for the backup/restore mechanism: write the
14017     * default browser (etc) settings in its canonical XML format.  Returns the default
14018     * browser XML representation as a byte array, or null if there is none.
14019     */
14020    @Override
14021    public byte[] getDefaultAppsBackup(int userId) {
14022        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14023            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14024        }
14025
14026        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14027        try {
14028            final XmlSerializer serializer = new FastXmlSerializer();
14029            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14030            serializer.startDocument(null, true);
14031            serializer.startTag(null, TAG_DEFAULT_APPS);
14032
14033            synchronized (mPackages) {
14034                mSettings.writeDefaultAppsLPr(serializer, userId);
14035            }
14036
14037            serializer.endTag(null, TAG_DEFAULT_APPS);
14038            serializer.endDocument();
14039            serializer.flush();
14040        } catch (Exception e) {
14041            if (DEBUG_BACKUP) {
14042                Slog.e(TAG, "Unable to write default apps for backup", e);
14043            }
14044            return null;
14045        }
14046
14047        return dataStream.toByteArray();
14048    }
14049
14050    @Override
14051    public void restoreDefaultApps(byte[] backup, int userId) {
14052        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14053            throw new SecurityException("Only the system may call restoreDefaultApps()");
14054        }
14055
14056        try {
14057            final XmlPullParser parser = Xml.newPullParser();
14058            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14059            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14060                    new BlobXmlRestorer() {
14061                        @Override
14062                        public void apply(XmlPullParser parser, int userId)
14063                                throws XmlPullParserException, IOException {
14064                            synchronized (mPackages) {
14065                                mSettings.readDefaultAppsLPw(parser, userId);
14066                            }
14067                        }
14068                    } );
14069        } catch (Exception e) {
14070            if (DEBUG_BACKUP) {
14071                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14072            }
14073        }
14074    }
14075
14076    @Override
14077    public byte[] getIntentFilterVerificationBackup(int userId) {
14078        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14079            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14080        }
14081
14082        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14083        try {
14084            final XmlSerializer serializer = new FastXmlSerializer();
14085            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14086            serializer.startDocument(null, true);
14087            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14088
14089            synchronized (mPackages) {
14090                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14091            }
14092
14093            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14094            serializer.endDocument();
14095            serializer.flush();
14096        } catch (Exception e) {
14097            if (DEBUG_BACKUP) {
14098                Slog.e(TAG, "Unable to write default apps for backup", e);
14099            }
14100            return null;
14101        }
14102
14103        return dataStream.toByteArray();
14104    }
14105
14106    @Override
14107    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14108        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14109            throw new SecurityException("Only the system may call restorePreferredActivities()");
14110        }
14111
14112        try {
14113            final XmlPullParser parser = Xml.newPullParser();
14114            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14115            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14116                    new BlobXmlRestorer() {
14117                        @Override
14118                        public void apply(XmlPullParser parser, int userId)
14119                                throws XmlPullParserException, IOException {
14120                            synchronized (mPackages) {
14121                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14122                                mSettings.writeLPr();
14123                            }
14124                        }
14125                    } );
14126        } catch (Exception e) {
14127            if (DEBUG_BACKUP) {
14128                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14129            }
14130        }
14131    }
14132
14133    @Override
14134    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14135            int sourceUserId, int targetUserId, int flags) {
14136        mContext.enforceCallingOrSelfPermission(
14137                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14138        int callingUid = Binder.getCallingUid();
14139        enforceOwnerRights(ownerPackage, callingUid);
14140        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14141        if (intentFilter.countActions() == 0) {
14142            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14143            return;
14144        }
14145        synchronized (mPackages) {
14146            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14147                    ownerPackage, targetUserId, flags);
14148            CrossProfileIntentResolver resolver =
14149                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14150            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14151            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14152            if (existing != null) {
14153                int size = existing.size();
14154                for (int i = 0; i < size; i++) {
14155                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14156                        return;
14157                    }
14158                }
14159            }
14160            resolver.addFilter(newFilter);
14161            scheduleWritePackageRestrictionsLocked(sourceUserId);
14162        }
14163    }
14164
14165    @Override
14166    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14167        mContext.enforceCallingOrSelfPermission(
14168                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14169        int callingUid = Binder.getCallingUid();
14170        enforceOwnerRights(ownerPackage, callingUid);
14171        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14172        synchronized (mPackages) {
14173            CrossProfileIntentResolver resolver =
14174                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14175            ArraySet<CrossProfileIntentFilter> set =
14176                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14177            for (CrossProfileIntentFilter filter : set) {
14178                if (filter.getOwnerPackage().equals(ownerPackage)) {
14179                    resolver.removeFilter(filter);
14180                }
14181            }
14182            scheduleWritePackageRestrictionsLocked(sourceUserId);
14183        }
14184    }
14185
14186    // Enforcing that callingUid is owning pkg on userId
14187    private void enforceOwnerRights(String pkg, int callingUid) {
14188        // The system owns everything.
14189        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14190            return;
14191        }
14192        int callingUserId = UserHandle.getUserId(callingUid);
14193        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14194        if (pi == null) {
14195            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14196                    + callingUserId);
14197        }
14198        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14199            throw new SecurityException("Calling uid " + callingUid
14200                    + " does not own package " + pkg);
14201        }
14202    }
14203
14204    @Override
14205    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14206        Intent intent = new Intent(Intent.ACTION_MAIN);
14207        intent.addCategory(Intent.CATEGORY_HOME);
14208
14209        final int callingUserId = UserHandle.getCallingUserId();
14210        List<ResolveInfo> list = queryIntentActivities(intent, null,
14211                PackageManager.GET_META_DATA, callingUserId);
14212        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14213                true, false, false, callingUserId);
14214
14215        allHomeCandidates.clear();
14216        if (list != null) {
14217            for (ResolveInfo ri : list) {
14218                allHomeCandidates.add(ri);
14219            }
14220        }
14221        return (preferred == null || preferred.activityInfo == null)
14222                ? null
14223                : new ComponentName(preferred.activityInfo.packageName,
14224                        preferred.activityInfo.name);
14225    }
14226
14227    @Override
14228    public void setApplicationEnabledSetting(String appPackageName,
14229            int newState, int flags, int userId, String callingPackage) {
14230        if (!sUserManager.exists(userId)) return;
14231        if (callingPackage == null) {
14232            callingPackage = Integer.toString(Binder.getCallingUid());
14233        }
14234        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14235    }
14236
14237    @Override
14238    public void setComponentEnabledSetting(ComponentName componentName,
14239            int newState, int flags, int userId) {
14240        if (!sUserManager.exists(userId)) return;
14241        setEnabledSetting(componentName.getPackageName(),
14242                componentName.getClassName(), newState, flags, userId, null);
14243    }
14244
14245    private void setEnabledSetting(final String packageName, String className, int newState,
14246            final int flags, int userId, String callingPackage) {
14247        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14248              || newState == COMPONENT_ENABLED_STATE_ENABLED
14249              || newState == COMPONENT_ENABLED_STATE_DISABLED
14250              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14251              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14252            throw new IllegalArgumentException("Invalid new component state: "
14253                    + newState);
14254        }
14255        PackageSetting pkgSetting;
14256        final int uid = Binder.getCallingUid();
14257        final int permission = mContext.checkCallingOrSelfPermission(
14258                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14259        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14260        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14261        boolean sendNow = false;
14262        boolean isApp = (className == null);
14263        String componentName = isApp ? packageName : className;
14264        int packageUid = -1;
14265        ArrayList<String> components;
14266
14267        // writer
14268        synchronized (mPackages) {
14269            pkgSetting = mSettings.mPackages.get(packageName);
14270            if (pkgSetting == null) {
14271                if (className == null) {
14272                    throw new IllegalArgumentException(
14273                            "Unknown package: " + packageName);
14274                }
14275                throw new IllegalArgumentException(
14276                        "Unknown component: " + packageName
14277                        + "/" + className);
14278            }
14279            // Allow root and verify that userId is not being specified by a different user
14280            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14281                throw new SecurityException(
14282                        "Permission Denial: attempt to change component state from pid="
14283                        + Binder.getCallingPid()
14284                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14285            }
14286            if (className == null) {
14287                // We're dealing with an application/package level state change
14288                if (pkgSetting.getEnabled(userId) == newState) {
14289                    // Nothing to do
14290                    return;
14291                }
14292                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14293                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14294                    // Don't care about who enables an app.
14295                    callingPackage = null;
14296                }
14297                pkgSetting.setEnabled(newState, userId, callingPackage);
14298                // pkgSetting.pkg.mSetEnabled = newState;
14299            } else {
14300                // We're dealing with a component level state change
14301                // First, verify that this is a valid class name.
14302                PackageParser.Package pkg = pkgSetting.pkg;
14303                if (pkg == null || !pkg.hasComponentClassName(className)) {
14304                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14305                        throw new IllegalArgumentException("Component class " + className
14306                                + " does not exist in " + packageName);
14307                    } else {
14308                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14309                                + className + " does not exist in " + packageName);
14310                    }
14311                }
14312                switch (newState) {
14313                case COMPONENT_ENABLED_STATE_ENABLED:
14314                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14315                        return;
14316                    }
14317                    break;
14318                case COMPONENT_ENABLED_STATE_DISABLED:
14319                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14320                        return;
14321                    }
14322                    break;
14323                case COMPONENT_ENABLED_STATE_DEFAULT:
14324                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14325                        return;
14326                    }
14327                    break;
14328                default:
14329                    Slog.e(TAG, "Invalid new component state: " + newState);
14330                    return;
14331                }
14332            }
14333            scheduleWritePackageRestrictionsLocked(userId);
14334            components = mPendingBroadcasts.get(userId, packageName);
14335            final boolean newPackage = components == null;
14336            if (newPackage) {
14337                components = new ArrayList<String>();
14338            }
14339            if (!components.contains(componentName)) {
14340                components.add(componentName);
14341            }
14342            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14343                sendNow = true;
14344                // Purge entry from pending broadcast list if another one exists already
14345                // since we are sending one right away.
14346                mPendingBroadcasts.remove(userId, packageName);
14347            } else {
14348                if (newPackage) {
14349                    mPendingBroadcasts.put(userId, packageName, components);
14350                }
14351                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14352                    // Schedule a message
14353                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14354                }
14355            }
14356        }
14357
14358        long callingId = Binder.clearCallingIdentity();
14359        try {
14360            if (sendNow) {
14361                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14362                sendPackageChangedBroadcast(packageName,
14363                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14364            }
14365        } finally {
14366            Binder.restoreCallingIdentity(callingId);
14367        }
14368    }
14369
14370    private void sendPackageChangedBroadcast(String packageName,
14371            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14372        if (DEBUG_INSTALL)
14373            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14374                    + componentNames);
14375        Bundle extras = new Bundle(4);
14376        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14377        String nameList[] = new String[componentNames.size()];
14378        componentNames.toArray(nameList);
14379        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14380        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14381        extras.putInt(Intent.EXTRA_UID, packageUid);
14382        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14383                new int[] {UserHandle.getUserId(packageUid)});
14384    }
14385
14386    @Override
14387    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14388        if (!sUserManager.exists(userId)) return;
14389        final int uid = Binder.getCallingUid();
14390        final int permission = mContext.checkCallingOrSelfPermission(
14391                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14392        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14393        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14394        // writer
14395        synchronized (mPackages) {
14396            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14397                    allowedByPermission, uid, userId)) {
14398                scheduleWritePackageRestrictionsLocked(userId);
14399            }
14400        }
14401    }
14402
14403    @Override
14404    public String getInstallerPackageName(String packageName) {
14405        // reader
14406        synchronized (mPackages) {
14407            return mSettings.getInstallerPackageNameLPr(packageName);
14408        }
14409    }
14410
14411    @Override
14412    public int getApplicationEnabledSetting(String packageName, int userId) {
14413        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14414        int uid = Binder.getCallingUid();
14415        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14416        // reader
14417        synchronized (mPackages) {
14418            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14419        }
14420    }
14421
14422    @Override
14423    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14424        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14425        int uid = Binder.getCallingUid();
14426        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14427        // reader
14428        synchronized (mPackages) {
14429            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14430        }
14431    }
14432
14433    @Override
14434    public void enterSafeMode() {
14435        enforceSystemOrRoot("Only the system can request entering safe mode");
14436
14437        if (!mSystemReady) {
14438            mSafeMode = true;
14439        }
14440    }
14441
14442    @Override
14443    public void systemReady() {
14444        mSystemReady = true;
14445
14446        // Read the compatibilty setting when the system is ready.
14447        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14448                mContext.getContentResolver(),
14449                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14450        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14451        if (DEBUG_SETTINGS) {
14452            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14453        }
14454
14455        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14456
14457        synchronized (mPackages) {
14458            // Verify that all of the preferred activity components actually
14459            // exist.  It is possible for applications to be updated and at
14460            // that point remove a previously declared activity component that
14461            // had been set as a preferred activity.  We try to clean this up
14462            // the next time we encounter that preferred activity, but it is
14463            // possible for the user flow to never be able to return to that
14464            // situation so here we do a sanity check to make sure we haven't
14465            // left any junk around.
14466            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14467            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14468                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14469                removed.clear();
14470                for (PreferredActivity pa : pir.filterSet()) {
14471                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14472                        removed.add(pa);
14473                    }
14474                }
14475                if (removed.size() > 0) {
14476                    for (int r=0; r<removed.size(); r++) {
14477                        PreferredActivity pa = removed.get(r);
14478                        Slog.w(TAG, "Removing dangling preferred activity: "
14479                                + pa.mPref.mComponent);
14480                        pir.removeFilter(pa);
14481                    }
14482                    mSettings.writePackageRestrictionsLPr(
14483                            mSettings.mPreferredActivities.keyAt(i));
14484                }
14485            }
14486
14487            for (int userId : UserManagerService.getInstance().getUserIds()) {
14488                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14489                    grantPermissionsUserIds = ArrayUtils.appendInt(
14490                            grantPermissionsUserIds, userId);
14491                }
14492            }
14493        }
14494        sUserManager.systemReady();
14495
14496        // If we upgraded grant all default permissions before kicking off.
14497        for (int userId : grantPermissionsUserIds) {
14498            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14499        }
14500
14501        // Kick off any messages waiting for system ready
14502        if (mPostSystemReadyMessages != null) {
14503            for (Message msg : mPostSystemReadyMessages) {
14504                msg.sendToTarget();
14505            }
14506            mPostSystemReadyMessages = null;
14507        }
14508
14509        // Watch for external volumes that come and go over time
14510        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14511        storage.registerListener(mStorageListener);
14512
14513        mInstallerService.systemReady();
14514        mPackageDexOptimizer.systemReady();
14515
14516        MountServiceInternal mountServiceInternal = LocalServices.getService(
14517                MountServiceInternal.class);
14518        mountServiceInternal.addExternalStoragePolicy(
14519                new MountServiceInternal.ExternalStorageMountPolicy() {
14520            @Override
14521            public int getMountMode(int uid, String packageName) {
14522                if (Process.isIsolated(uid)) {
14523                    return Zygote.MOUNT_EXTERNAL_NONE;
14524                }
14525                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14526                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14527                }
14528                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14529                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14530                }
14531                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14532                    return Zygote.MOUNT_EXTERNAL_READ;
14533                }
14534                return Zygote.MOUNT_EXTERNAL_WRITE;
14535            }
14536
14537            @Override
14538            public boolean hasExternalStorage(int uid, String packageName) {
14539                return true;
14540            }
14541        });
14542    }
14543
14544    @Override
14545    public boolean isSafeMode() {
14546        return mSafeMode;
14547    }
14548
14549    @Override
14550    public boolean hasSystemUidErrors() {
14551        return mHasSystemUidErrors;
14552    }
14553
14554    static String arrayToString(int[] array) {
14555        StringBuffer buf = new StringBuffer(128);
14556        buf.append('[');
14557        if (array != null) {
14558            for (int i=0; i<array.length; i++) {
14559                if (i > 0) buf.append(", ");
14560                buf.append(array[i]);
14561            }
14562        }
14563        buf.append(']');
14564        return buf.toString();
14565    }
14566
14567    static class DumpState {
14568        public static final int DUMP_LIBS = 1 << 0;
14569        public static final int DUMP_FEATURES = 1 << 1;
14570        public static final int DUMP_RESOLVERS = 1 << 2;
14571        public static final int DUMP_PERMISSIONS = 1 << 3;
14572        public static final int DUMP_PACKAGES = 1 << 4;
14573        public static final int DUMP_SHARED_USERS = 1 << 5;
14574        public static final int DUMP_MESSAGES = 1 << 6;
14575        public static final int DUMP_PROVIDERS = 1 << 7;
14576        public static final int DUMP_VERIFIERS = 1 << 8;
14577        public static final int DUMP_PREFERRED = 1 << 9;
14578        public static final int DUMP_PREFERRED_XML = 1 << 10;
14579        public static final int DUMP_KEYSETS = 1 << 11;
14580        public static final int DUMP_VERSION = 1 << 12;
14581        public static final int DUMP_INSTALLS = 1 << 13;
14582        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14583        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14584
14585        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14586
14587        private int mTypes;
14588
14589        private int mOptions;
14590
14591        private boolean mTitlePrinted;
14592
14593        private SharedUserSetting mSharedUser;
14594
14595        public boolean isDumping(int type) {
14596            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14597                return true;
14598            }
14599
14600            return (mTypes & type) != 0;
14601        }
14602
14603        public void setDump(int type) {
14604            mTypes |= type;
14605        }
14606
14607        public boolean isOptionEnabled(int option) {
14608            return (mOptions & option) != 0;
14609        }
14610
14611        public void setOptionEnabled(int option) {
14612            mOptions |= option;
14613        }
14614
14615        public boolean onTitlePrinted() {
14616            final boolean printed = mTitlePrinted;
14617            mTitlePrinted = true;
14618            return printed;
14619        }
14620
14621        public boolean getTitlePrinted() {
14622            return mTitlePrinted;
14623        }
14624
14625        public void setTitlePrinted(boolean enabled) {
14626            mTitlePrinted = enabled;
14627        }
14628
14629        public SharedUserSetting getSharedUser() {
14630            return mSharedUser;
14631        }
14632
14633        public void setSharedUser(SharedUserSetting user) {
14634            mSharedUser = user;
14635        }
14636    }
14637
14638    @Override
14639    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14640        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14641                != PackageManager.PERMISSION_GRANTED) {
14642            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14643                    + Binder.getCallingPid()
14644                    + ", uid=" + Binder.getCallingUid()
14645                    + " without permission "
14646                    + android.Manifest.permission.DUMP);
14647            return;
14648        }
14649
14650        DumpState dumpState = new DumpState();
14651        boolean fullPreferred = false;
14652        boolean checkin = false;
14653
14654        String packageName = null;
14655        ArraySet<String> permissionNames = null;
14656
14657        int opti = 0;
14658        while (opti < args.length) {
14659            String opt = args[opti];
14660            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14661                break;
14662            }
14663            opti++;
14664
14665            if ("-a".equals(opt)) {
14666                // Right now we only know how to print all.
14667            } else if ("-h".equals(opt)) {
14668                pw.println("Package manager dump options:");
14669                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14670                pw.println("    --checkin: dump for a checkin");
14671                pw.println("    -f: print details of intent filters");
14672                pw.println("    -h: print this help");
14673                pw.println("  cmd may be one of:");
14674                pw.println("    l[ibraries]: list known shared libraries");
14675                pw.println("    f[ibraries]: list device features");
14676                pw.println("    k[eysets]: print known keysets");
14677                pw.println("    r[esolvers]: dump intent resolvers");
14678                pw.println("    perm[issions]: dump permissions");
14679                pw.println("    permission [name ...]: dump declaration and use of given permission");
14680                pw.println("    pref[erred]: print preferred package settings");
14681                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14682                pw.println("    prov[iders]: dump content providers");
14683                pw.println("    p[ackages]: dump installed packages");
14684                pw.println("    s[hared-users]: dump shared user IDs");
14685                pw.println("    m[essages]: print collected runtime messages");
14686                pw.println("    v[erifiers]: print package verifier info");
14687                pw.println("    version: print database version info");
14688                pw.println("    write: write current settings now");
14689                pw.println("    <package.name>: info about given package");
14690                pw.println("    installs: details about install sessions");
14691                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14692                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14693                return;
14694            } else if ("--checkin".equals(opt)) {
14695                checkin = true;
14696            } else if ("-f".equals(opt)) {
14697                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14698            } else {
14699                pw.println("Unknown argument: " + opt + "; use -h for help");
14700            }
14701        }
14702
14703        // Is the caller requesting to dump a particular piece of data?
14704        if (opti < args.length) {
14705            String cmd = args[opti];
14706            opti++;
14707            // Is this a package name?
14708            if ("android".equals(cmd) || cmd.contains(".")) {
14709                packageName = cmd;
14710                // When dumping a single package, we always dump all of its
14711                // filter information since the amount of data will be reasonable.
14712                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14713            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14714                dumpState.setDump(DumpState.DUMP_LIBS);
14715            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14716                dumpState.setDump(DumpState.DUMP_FEATURES);
14717            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14718                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14719            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14720                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14721            } else if ("permission".equals(cmd)) {
14722                if (opti >= args.length) {
14723                    pw.println("Error: permission requires permission name");
14724                    return;
14725                }
14726                permissionNames = new ArraySet<>();
14727                while (opti < args.length) {
14728                    permissionNames.add(args[opti]);
14729                    opti++;
14730                }
14731                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14732                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14733            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14734                dumpState.setDump(DumpState.DUMP_PREFERRED);
14735            } else if ("preferred-xml".equals(cmd)) {
14736                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14737                if (opti < args.length && "--full".equals(args[opti])) {
14738                    fullPreferred = true;
14739                    opti++;
14740                }
14741            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14742                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14743            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14744                dumpState.setDump(DumpState.DUMP_PACKAGES);
14745            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14746                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14747            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14748                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14749            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14750                dumpState.setDump(DumpState.DUMP_MESSAGES);
14751            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14752                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14753            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14754                    || "intent-filter-verifiers".equals(cmd)) {
14755                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14756            } else if ("version".equals(cmd)) {
14757                dumpState.setDump(DumpState.DUMP_VERSION);
14758            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14759                dumpState.setDump(DumpState.DUMP_KEYSETS);
14760            } else if ("installs".equals(cmd)) {
14761                dumpState.setDump(DumpState.DUMP_INSTALLS);
14762            } else if ("write".equals(cmd)) {
14763                synchronized (mPackages) {
14764                    mSettings.writeLPr();
14765                    pw.println("Settings written.");
14766                    return;
14767                }
14768            }
14769        }
14770
14771        if (checkin) {
14772            pw.println("vers,1");
14773        }
14774
14775        // reader
14776        synchronized (mPackages) {
14777            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14778                if (!checkin) {
14779                    if (dumpState.onTitlePrinted())
14780                        pw.println();
14781                    pw.println("Database versions:");
14782                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14783                }
14784            }
14785
14786            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14787                if (!checkin) {
14788                    if (dumpState.onTitlePrinted())
14789                        pw.println();
14790                    pw.println("Verifiers:");
14791                    pw.print("  Required: ");
14792                    pw.print(mRequiredVerifierPackage);
14793                    pw.print(" (uid=");
14794                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14795                    pw.println(")");
14796                } else if (mRequiredVerifierPackage != null) {
14797                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14798                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14799                }
14800            }
14801
14802            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14803                    packageName == null) {
14804                if (mIntentFilterVerifierComponent != null) {
14805                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14806                    if (!checkin) {
14807                        if (dumpState.onTitlePrinted())
14808                            pw.println();
14809                        pw.println("Intent Filter Verifier:");
14810                        pw.print("  Using: ");
14811                        pw.print(verifierPackageName);
14812                        pw.print(" (uid=");
14813                        pw.print(getPackageUid(verifierPackageName, 0));
14814                        pw.println(")");
14815                    } else if (verifierPackageName != null) {
14816                        pw.print("ifv,"); pw.print(verifierPackageName);
14817                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14818                    }
14819                } else {
14820                    pw.println();
14821                    pw.println("No Intent Filter Verifier available!");
14822                }
14823            }
14824
14825            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14826                boolean printedHeader = false;
14827                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14828                while (it.hasNext()) {
14829                    String name = it.next();
14830                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14831                    if (!checkin) {
14832                        if (!printedHeader) {
14833                            if (dumpState.onTitlePrinted())
14834                                pw.println();
14835                            pw.println("Libraries:");
14836                            printedHeader = true;
14837                        }
14838                        pw.print("  ");
14839                    } else {
14840                        pw.print("lib,");
14841                    }
14842                    pw.print(name);
14843                    if (!checkin) {
14844                        pw.print(" -> ");
14845                    }
14846                    if (ent.path != null) {
14847                        if (!checkin) {
14848                            pw.print("(jar) ");
14849                            pw.print(ent.path);
14850                        } else {
14851                            pw.print(",jar,");
14852                            pw.print(ent.path);
14853                        }
14854                    } else {
14855                        if (!checkin) {
14856                            pw.print("(apk) ");
14857                            pw.print(ent.apk);
14858                        } else {
14859                            pw.print(",apk,");
14860                            pw.print(ent.apk);
14861                        }
14862                    }
14863                    pw.println();
14864                }
14865            }
14866
14867            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14868                if (dumpState.onTitlePrinted())
14869                    pw.println();
14870                if (!checkin) {
14871                    pw.println("Features:");
14872                }
14873                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14874                while (it.hasNext()) {
14875                    String name = it.next();
14876                    if (!checkin) {
14877                        pw.print("  ");
14878                    } else {
14879                        pw.print("feat,");
14880                    }
14881                    pw.println(name);
14882                }
14883            }
14884
14885            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14886                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14887                        : "Activity Resolver Table:", "  ", packageName,
14888                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14889                    dumpState.setTitlePrinted(true);
14890                }
14891                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14892                        : "Receiver Resolver Table:", "  ", packageName,
14893                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14894                    dumpState.setTitlePrinted(true);
14895                }
14896                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14897                        : "Service Resolver Table:", "  ", packageName,
14898                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14899                    dumpState.setTitlePrinted(true);
14900                }
14901                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14902                        : "Provider Resolver Table:", "  ", packageName,
14903                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14904                    dumpState.setTitlePrinted(true);
14905                }
14906            }
14907
14908            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14909                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14910                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14911                    int user = mSettings.mPreferredActivities.keyAt(i);
14912                    if (pir.dump(pw,
14913                            dumpState.getTitlePrinted()
14914                                ? "\nPreferred Activities User " + user + ":"
14915                                : "Preferred Activities User " + user + ":", "  ",
14916                            packageName, true, false)) {
14917                        dumpState.setTitlePrinted(true);
14918                    }
14919                }
14920            }
14921
14922            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14923                pw.flush();
14924                FileOutputStream fout = new FileOutputStream(fd);
14925                BufferedOutputStream str = new BufferedOutputStream(fout);
14926                XmlSerializer serializer = new FastXmlSerializer();
14927                try {
14928                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14929                    serializer.startDocument(null, true);
14930                    serializer.setFeature(
14931                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14932                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14933                    serializer.endDocument();
14934                    serializer.flush();
14935                } catch (IllegalArgumentException e) {
14936                    pw.println("Failed writing: " + e);
14937                } catch (IllegalStateException e) {
14938                    pw.println("Failed writing: " + e);
14939                } catch (IOException e) {
14940                    pw.println("Failed writing: " + e);
14941                }
14942            }
14943
14944            if (!checkin
14945                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14946                    && packageName == null) {
14947                pw.println();
14948                int count = mSettings.mPackages.size();
14949                if (count == 0) {
14950                    pw.println("No applications!");
14951                    pw.println();
14952                } else {
14953                    final String prefix = "  ";
14954                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14955                    if (allPackageSettings.size() == 0) {
14956                        pw.println("No domain preferred apps!");
14957                        pw.println();
14958                    } else {
14959                        pw.println("App verification status:");
14960                        pw.println();
14961                        count = 0;
14962                        for (PackageSetting ps : allPackageSettings) {
14963                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14964                            if (ivi == null || ivi.getPackageName() == null) continue;
14965                            pw.println(prefix + "Package: " + ivi.getPackageName());
14966                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14967                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14968                            pw.println();
14969                            count++;
14970                        }
14971                        if (count == 0) {
14972                            pw.println(prefix + "No app verification established.");
14973                            pw.println();
14974                        }
14975                        for (int userId : sUserManager.getUserIds()) {
14976                            pw.println("App linkages for user " + userId + ":");
14977                            pw.println();
14978                            count = 0;
14979                            for (PackageSetting ps : allPackageSettings) {
14980                                final long status = ps.getDomainVerificationStatusForUser(userId);
14981                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14982                                    continue;
14983                                }
14984                                pw.println(prefix + "Package: " + ps.name);
14985                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14986                                String statusStr = IntentFilterVerificationInfo.
14987                                        getStatusStringFromValue(status);
14988                                pw.println(prefix + "Status:  " + statusStr);
14989                                pw.println();
14990                                count++;
14991                            }
14992                            if (count == 0) {
14993                                pw.println(prefix + "No configured app linkages.");
14994                                pw.println();
14995                            }
14996                        }
14997                    }
14998                }
14999            }
15000
15001            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15002                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15003                if (packageName == null && permissionNames == null) {
15004                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15005                        if (iperm == 0) {
15006                            if (dumpState.onTitlePrinted())
15007                                pw.println();
15008                            pw.println("AppOp Permissions:");
15009                        }
15010                        pw.print("  AppOp Permission ");
15011                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15012                        pw.println(":");
15013                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15014                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15015                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15016                        }
15017                    }
15018                }
15019            }
15020
15021            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15022                boolean printedSomething = false;
15023                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15024                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15025                        continue;
15026                    }
15027                    if (!printedSomething) {
15028                        if (dumpState.onTitlePrinted())
15029                            pw.println();
15030                        pw.println("Registered ContentProviders:");
15031                        printedSomething = true;
15032                    }
15033                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15034                    pw.print("    "); pw.println(p.toString());
15035                }
15036                printedSomething = false;
15037                for (Map.Entry<String, PackageParser.Provider> entry :
15038                        mProvidersByAuthority.entrySet()) {
15039                    PackageParser.Provider p = entry.getValue();
15040                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15041                        continue;
15042                    }
15043                    if (!printedSomething) {
15044                        if (dumpState.onTitlePrinted())
15045                            pw.println();
15046                        pw.println("ContentProvider Authorities:");
15047                        printedSomething = true;
15048                    }
15049                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15050                    pw.print("    "); pw.println(p.toString());
15051                    if (p.info != null && p.info.applicationInfo != null) {
15052                        final String appInfo = p.info.applicationInfo.toString();
15053                        pw.print("      applicationInfo="); pw.println(appInfo);
15054                    }
15055                }
15056            }
15057
15058            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15059                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15060            }
15061
15062            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15063                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15064            }
15065
15066            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15067                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15068            }
15069
15070            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15071                // XXX should handle packageName != null by dumping only install data that
15072                // the given package is involved with.
15073                if (dumpState.onTitlePrinted()) pw.println();
15074                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15075            }
15076
15077            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15078                if (dumpState.onTitlePrinted()) pw.println();
15079                mSettings.dumpReadMessagesLPr(pw, dumpState);
15080
15081                pw.println();
15082                pw.println("Package warning messages:");
15083                BufferedReader in = null;
15084                String line = null;
15085                try {
15086                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15087                    while ((line = in.readLine()) != null) {
15088                        if (line.contains("ignored: updated version")) continue;
15089                        pw.println(line);
15090                    }
15091                } catch (IOException ignored) {
15092                } finally {
15093                    IoUtils.closeQuietly(in);
15094                }
15095            }
15096
15097            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15098                BufferedReader in = null;
15099                String line = null;
15100                try {
15101                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15102                    while ((line = in.readLine()) != null) {
15103                        if (line.contains("ignored: updated version")) continue;
15104                        pw.print("msg,");
15105                        pw.println(line);
15106                    }
15107                } catch (IOException ignored) {
15108                } finally {
15109                    IoUtils.closeQuietly(in);
15110                }
15111            }
15112        }
15113    }
15114
15115    private String dumpDomainString(String packageName) {
15116        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15117        List<IntentFilter> filters = getAllIntentFilters(packageName);
15118
15119        ArraySet<String> result = new ArraySet<>();
15120        if (iviList.size() > 0) {
15121            for (IntentFilterVerificationInfo ivi : iviList) {
15122                for (String host : ivi.getDomains()) {
15123                    result.add(host);
15124                }
15125            }
15126        }
15127        if (filters != null && filters.size() > 0) {
15128            for (IntentFilter filter : filters) {
15129                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15130                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15131                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15132                    result.addAll(filter.getHostsList());
15133                }
15134            }
15135        }
15136
15137        StringBuilder sb = new StringBuilder(result.size() * 16);
15138        for (String domain : result) {
15139            if (sb.length() > 0) sb.append(" ");
15140            sb.append(domain);
15141        }
15142        return sb.toString();
15143    }
15144
15145    // ------- apps on sdcard specific code -------
15146    static final boolean DEBUG_SD_INSTALL = false;
15147
15148    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15149
15150    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15151
15152    private boolean mMediaMounted = false;
15153
15154    static String getEncryptKey() {
15155        try {
15156            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15157                    SD_ENCRYPTION_KEYSTORE_NAME);
15158            if (sdEncKey == null) {
15159                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15160                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15161                if (sdEncKey == null) {
15162                    Slog.e(TAG, "Failed to create encryption keys");
15163                    return null;
15164                }
15165            }
15166            return sdEncKey;
15167        } catch (NoSuchAlgorithmException nsae) {
15168            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15169            return null;
15170        } catch (IOException ioe) {
15171            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15172            return null;
15173        }
15174    }
15175
15176    /*
15177     * Update media status on PackageManager.
15178     */
15179    @Override
15180    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15181        int callingUid = Binder.getCallingUid();
15182        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15183            throw new SecurityException("Media status can only be updated by the system");
15184        }
15185        // reader; this apparently protects mMediaMounted, but should probably
15186        // be a different lock in that case.
15187        synchronized (mPackages) {
15188            Log.i(TAG, "Updating external media status from "
15189                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15190                    + (mediaStatus ? "mounted" : "unmounted"));
15191            if (DEBUG_SD_INSTALL)
15192                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15193                        + ", mMediaMounted=" + mMediaMounted);
15194            if (mediaStatus == mMediaMounted) {
15195                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15196                        : 0, -1);
15197                mHandler.sendMessage(msg);
15198                return;
15199            }
15200            mMediaMounted = mediaStatus;
15201        }
15202        // Queue up an async operation since the package installation may take a
15203        // little while.
15204        mHandler.post(new Runnable() {
15205            public void run() {
15206                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15207            }
15208        });
15209    }
15210
15211    /**
15212     * Called by MountService when the initial ASECs to scan are available.
15213     * Should block until all the ASEC containers are finished being scanned.
15214     */
15215    public void scanAvailableAsecs() {
15216        updateExternalMediaStatusInner(true, false, false);
15217        if (mShouldRestoreconData) {
15218            SELinuxMMAC.setRestoreconDone();
15219            mShouldRestoreconData = false;
15220        }
15221    }
15222
15223    /*
15224     * Collect information of applications on external media, map them against
15225     * existing containers and update information based on current mount status.
15226     * Please note that we always have to report status if reportStatus has been
15227     * set to true especially when unloading packages.
15228     */
15229    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15230            boolean externalStorage) {
15231        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15232        int[] uidArr = EmptyArray.INT;
15233
15234        final String[] list = PackageHelper.getSecureContainerList();
15235        if (ArrayUtils.isEmpty(list)) {
15236            Log.i(TAG, "No secure containers found");
15237        } else {
15238            // Process list of secure containers and categorize them
15239            // as active or stale based on their package internal state.
15240
15241            // reader
15242            synchronized (mPackages) {
15243                for (String cid : list) {
15244                    // Leave stages untouched for now; installer service owns them
15245                    if (PackageInstallerService.isStageName(cid)) continue;
15246
15247                    if (DEBUG_SD_INSTALL)
15248                        Log.i(TAG, "Processing container " + cid);
15249                    String pkgName = getAsecPackageName(cid);
15250                    if (pkgName == null) {
15251                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15252                        continue;
15253                    }
15254                    if (DEBUG_SD_INSTALL)
15255                        Log.i(TAG, "Looking for pkg : " + pkgName);
15256
15257                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15258                    if (ps == null) {
15259                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15260                        continue;
15261                    }
15262
15263                    /*
15264                     * Skip packages that are not external if we're unmounting
15265                     * external storage.
15266                     */
15267                    if (externalStorage && !isMounted && !isExternal(ps)) {
15268                        continue;
15269                    }
15270
15271                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15272                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15273                    // The package status is changed only if the code path
15274                    // matches between settings and the container id.
15275                    if (ps.codePathString != null
15276                            && ps.codePathString.startsWith(args.getCodePath())) {
15277                        if (DEBUG_SD_INSTALL) {
15278                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15279                                    + " at code path: " + ps.codePathString);
15280                        }
15281
15282                        // We do have a valid package installed on sdcard
15283                        processCids.put(args, ps.codePathString);
15284                        final int uid = ps.appId;
15285                        if (uid != -1) {
15286                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15287                        }
15288                    } else {
15289                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15290                                + ps.codePathString);
15291                    }
15292                }
15293            }
15294
15295            Arrays.sort(uidArr);
15296        }
15297
15298        // Process packages with valid entries.
15299        if (isMounted) {
15300            if (DEBUG_SD_INSTALL)
15301                Log.i(TAG, "Loading packages");
15302            loadMediaPackages(processCids, uidArr);
15303            startCleaningPackages();
15304            mInstallerService.onSecureContainersAvailable();
15305        } else {
15306            if (DEBUG_SD_INSTALL)
15307                Log.i(TAG, "Unloading packages");
15308            unloadMediaPackages(processCids, uidArr, reportStatus);
15309        }
15310    }
15311
15312    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15313            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15314        final int size = infos.size();
15315        final String[] packageNames = new String[size];
15316        final int[] packageUids = new int[size];
15317        for (int i = 0; i < size; i++) {
15318            final ApplicationInfo info = infos.get(i);
15319            packageNames[i] = info.packageName;
15320            packageUids[i] = info.uid;
15321        }
15322        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15323                finishedReceiver);
15324    }
15325
15326    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15327            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15328        sendResourcesChangedBroadcast(mediaStatus, replacing,
15329                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15330    }
15331
15332    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15333            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15334        int size = pkgList.length;
15335        if (size > 0) {
15336            // Send broadcasts here
15337            Bundle extras = new Bundle();
15338            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15339            if (uidArr != null) {
15340                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15341            }
15342            if (replacing) {
15343                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15344            }
15345            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15346                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15347            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15348        }
15349    }
15350
15351   /*
15352     * Look at potentially valid container ids from processCids If package
15353     * information doesn't match the one on record or package scanning fails,
15354     * the cid is added to list of removeCids. We currently don't delete stale
15355     * containers.
15356     */
15357    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15358        ArrayList<String> pkgList = new ArrayList<String>();
15359        Set<AsecInstallArgs> keys = processCids.keySet();
15360
15361        for (AsecInstallArgs args : keys) {
15362            String codePath = processCids.get(args);
15363            if (DEBUG_SD_INSTALL)
15364                Log.i(TAG, "Loading container : " + args.cid);
15365            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15366            try {
15367                // Make sure there are no container errors first.
15368                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15369                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15370                            + " when installing from sdcard");
15371                    continue;
15372                }
15373                // Check code path here.
15374                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15375                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15376                            + " does not match one in settings " + codePath);
15377                    continue;
15378                }
15379                // Parse package
15380                int parseFlags = mDefParseFlags;
15381                if (args.isExternalAsec()) {
15382                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15383                }
15384                if (args.isFwdLocked()) {
15385                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15386                }
15387
15388                synchronized (mInstallLock) {
15389                    PackageParser.Package pkg = null;
15390                    try {
15391                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15392                    } catch (PackageManagerException e) {
15393                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15394                    }
15395                    // Scan the package
15396                    if (pkg != null) {
15397                        /*
15398                         * TODO why is the lock being held? doPostInstall is
15399                         * called in other places without the lock. This needs
15400                         * to be straightened out.
15401                         */
15402                        // writer
15403                        synchronized (mPackages) {
15404                            retCode = PackageManager.INSTALL_SUCCEEDED;
15405                            pkgList.add(pkg.packageName);
15406                            // Post process args
15407                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15408                                    pkg.applicationInfo.uid);
15409                        }
15410                    } else {
15411                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15412                    }
15413                }
15414
15415            } finally {
15416                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15417                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15418                }
15419            }
15420        }
15421        // writer
15422        synchronized (mPackages) {
15423            // If the platform SDK has changed since the last time we booted,
15424            // we need to re-grant app permission to catch any new ones that
15425            // appear. This is really a hack, and means that apps can in some
15426            // cases get permissions that the user didn't initially explicitly
15427            // allow... it would be nice to have some better way to handle
15428            // this situation.
15429            final VersionInfo ver = mSettings.getExternalVersion();
15430
15431            int updateFlags = UPDATE_PERMISSIONS_ALL;
15432            if (ver.sdkVersion != mSdkVersion) {
15433                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15434                        + mSdkVersion + "; regranting permissions for external");
15435                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15436            }
15437            updatePermissionsLPw(null, null, updateFlags);
15438
15439            // Yay, everything is now upgraded
15440            ver.forceCurrent();
15441
15442            // can downgrade to reader
15443            // Persist settings
15444            mSettings.writeLPr();
15445        }
15446        // Send a broadcast to let everyone know we are done processing
15447        if (pkgList.size() > 0) {
15448            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15449        }
15450    }
15451
15452   /*
15453     * Utility method to unload a list of specified containers
15454     */
15455    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15456        // Just unmount all valid containers.
15457        for (AsecInstallArgs arg : cidArgs) {
15458            synchronized (mInstallLock) {
15459                arg.doPostDeleteLI(false);
15460           }
15461       }
15462   }
15463
15464    /*
15465     * Unload packages mounted on external media. This involves deleting package
15466     * data from internal structures, sending broadcasts about diabled packages,
15467     * gc'ing to free up references, unmounting all secure containers
15468     * corresponding to packages on external media, and posting a
15469     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15470     * that we always have to post this message if status has been requested no
15471     * matter what.
15472     */
15473    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15474            final boolean reportStatus) {
15475        if (DEBUG_SD_INSTALL)
15476            Log.i(TAG, "unloading media packages");
15477        ArrayList<String> pkgList = new ArrayList<String>();
15478        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15479        final Set<AsecInstallArgs> keys = processCids.keySet();
15480        for (AsecInstallArgs args : keys) {
15481            String pkgName = args.getPackageName();
15482            if (DEBUG_SD_INSTALL)
15483                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15484            // Delete package internally
15485            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15486            synchronized (mInstallLock) {
15487                boolean res = deletePackageLI(pkgName, null, false, null, null,
15488                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15489                if (res) {
15490                    pkgList.add(pkgName);
15491                } else {
15492                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15493                    failedList.add(args);
15494                }
15495            }
15496        }
15497
15498        // reader
15499        synchronized (mPackages) {
15500            // We didn't update the settings after removing each package;
15501            // write them now for all packages.
15502            mSettings.writeLPr();
15503        }
15504
15505        // We have to absolutely send UPDATED_MEDIA_STATUS only
15506        // after confirming that all the receivers processed the ordered
15507        // broadcast when packages get disabled, force a gc to clean things up.
15508        // and unload all the containers.
15509        if (pkgList.size() > 0) {
15510            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15511                    new IIntentReceiver.Stub() {
15512                public void performReceive(Intent intent, int resultCode, String data,
15513                        Bundle extras, boolean ordered, boolean sticky,
15514                        int sendingUser) throws RemoteException {
15515                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15516                            reportStatus ? 1 : 0, 1, keys);
15517                    mHandler.sendMessage(msg);
15518                }
15519            });
15520        } else {
15521            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15522                    keys);
15523            mHandler.sendMessage(msg);
15524        }
15525    }
15526
15527    private void loadPrivatePackages(VolumeInfo vol) {
15528        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15529        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15530        synchronized (mInstallLock) {
15531        synchronized (mPackages) {
15532            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15533            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15534            for (PackageSetting ps : packages) {
15535                final PackageParser.Package pkg;
15536                try {
15537                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15538                    loaded.add(pkg.applicationInfo);
15539                } catch (PackageManagerException e) {
15540                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15541                }
15542
15543                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15544                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15545                }
15546            }
15547
15548            int updateFlags = UPDATE_PERMISSIONS_ALL;
15549            if (ver.sdkVersion != mSdkVersion) {
15550                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15551                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15552                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15553            }
15554            updatePermissionsLPw(null, null, updateFlags);
15555
15556            // Yay, everything is now upgraded
15557            ver.forceCurrent();
15558
15559            mSettings.writeLPr();
15560        }
15561        }
15562
15563        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15564        sendResourcesChangedBroadcast(true, false, loaded, null);
15565    }
15566
15567    private void unloadPrivatePackages(VolumeInfo vol) {
15568        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15569        synchronized (mInstallLock) {
15570        synchronized (mPackages) {
15571            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15572            for (PackageSetting ps : packages) {
15573                if (ps.pkg == null) continue;
15574
15575                final ApplicationInfo info = ps.pkg.applicationInfo;
15576                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15577                if (deletePackageLI(ps.name, null, false, null, null,
15578                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15579                    unloaded.add(info);
15580                } else {
15581                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15582                }
15583            }
15584
15585            mSettings.writeLPr();
15586        }
15587        }
15588
15589        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15590        sendResourcesChangedBroadcast(false, false, unloaded, null);
15591    }
15592
15593    /**
15594     * Examine all users present on given mounted volume, and destroy data
15595     * belonging to users that are no longer valid, or whose user ID has been
15596     * recycled.
15597     */
15598    private void reconcileUsers(String volumeUuid) {
15599        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15600        if (ArrayUtils.isEmpty(files)) {
15601            Slog.d(TAG, "No users found on " + volumeUuid);
15602            return;
15603        }
15604
15605        for (File file : files) {
15606            if (!file.isDirectory()) continue;
15607
15608            final int userId;
15609            final UserInfo info;
15610            try {
15611                userId = Integer.parseInt(file.getName());
15612                info = sUserManager.getUserInfo(userId);
15613            } catch (NumberFormatException e) {
15614                Slog.w(TAG, "Invalid user directory " + file);
15615                continue;
15616            }
15617
15618            boolean destroyUser = false;
15619            if (info == null) {
15620                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15621                        + " because no matching user was found");
15622                destroyUser = true;
15623            } else {
15624                try {
15625                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15626                } catch (IOException e) {
15627                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15628                            + " because we failed to enforce serial number: " + e);
15629                    destroyUser = true;
15630                }
15631            }
15632
15633            if (destroyUser) {
15634                synchronized (mInstallLock) {
15635                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15636                }
15637            }
15638        }
15639
15640        final UserManager um = mContext.getSystemService(UserManager.class);
15641        for (UserInfo user : um.getUsers()) {
15642            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15643            if (userDir.exists()) continue;
15644
15645            try {
15646                UserManagerService.prepareUserDirectory(userDir);
15647                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15648            } catch (IOException e) {
15649                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15650            }
15651        }
15652    }
15653
15654    /**
15655     * Examine all apps present on given mounted volume, and destroy apps that
15656     * aren't expected, either due to uninstallation or reinstallation on
15657     * another volume.
15658     */
15659    private void reconcileApps(String volumeUuid) {
15660        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15661        if (ArrayUtils.isEmpty(files)) {
15662            Slog.d(TAG, "No apps found on " + volumeUuid);
15663            return;
15664        }
15665
15666        for (File file : files) {
15667            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15668                    && !PackageInstallerService.isStageName(file.getName());
15669            if (!isPackage) {
15670                // Ignore entries which are not packages
15671                continue;
15672            }
15673
15674            boolean destroyApp = false;
15675            String packageName = null;
15676            try {
15677                final PackageLite pkg = PackageParser.parsePackageLite(file,
15678                        PackageParser.PARSE_MUST_BE_APK);
15679                packageName = pkg.packageName;
15680
15681                synchronized (mPackages) {
15682                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15683                    if (ps == null) {
15684                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15685                                + volumeUuid + " because we found no install record");
15686                        destroyApp = true;
15687                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15688                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15689                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15690                        destroyApp = true;
15691                    }
15692                }
15693
15694            } catch (PackageParserException e) {
15695                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15696                destroyApp = true;
15697            }
15698
15699            if (destroyApp) {
15700                synchronized (mInstallLock) {
15701                    if (packageName != null) {
15702                        removeDataDirsLI(volumeUuid, packageName);
15703                    }
15704                    if (file.isDirectory()) {
15705                        mInstaller.rmPackageDir(file.getAbsolutePath());
15706                    } else {
15707                        file.delete();
15708                    }
15709                }
15710            }
15711        }
15712    }
15713
15714    private void unfreezePackage(String packageName) {
15715        synchronized (mPackages) {
15716            final PackageSetting ps = mSettings.mPackages.get(packageName);
15717            if (ps != null) {
15718                ps.frozen = false;
15719            }
15720        }
15721    }
15722
15723    @Override
15724    public int movePackage(final String packageName, final String volumeUuid) {
15725        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15726
15727        final int moveId = mNextMoveId.getAndIncrement();
15728        try {
15729            movePackageInternal(packageName, volumeUuid, moveId);
15730        } catch (PackageManagerException e) {
15731            Slog.w(TAG, "Failed to move " + packageName, e);
15732            mMoveCallbacks.notifyStatusChanged(moveId,
15733                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15734        }
15735        return moveId;
15736    }
15737
15738    private void movePackageInternal(final String packageName, final String volumeUuid,
15739            final int moveId) throws PackageManagerException {
15740        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15741        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15742        final PackageManager pm = mContext.getPackageManager();
15743
15744        final boolean currentAsec;
15745        final String currentVolumeUuid;
15746        final File codeFile;
15747        final String installerPackageName;
15748        final String packageAbiOverride;
15749        final int appId;
15750        final String seinfo;
15751        final String label;
15752
15753        // reader
15754        synchronized (mPackages) {
15755            final PackageParser.Package pkg = mPackages.get(packageName);
15756            final PackageSetting ps = mSettings.mPackages.get(packageName);
15757            if (pkg == null || ps == null) {
15758                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15759            }
15760
15761            if (pkg.applicationInfo.isSystemApp()) {
15762                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15763                        "Cannot move system application");
15764            }
15765
15766            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15767                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15768                        "Package already moved to " + volumeUuid);
15769            }
15770
15771            final File probe = new File(pkg.codePath);
15772            final File probeOat = new File(probe, "oat");
15773            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15774                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15775                        "Move only supported for modern cluster style installs");
15776            }
15777
15778            if (ps.frozen) {
15779                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15780                        "Failed to move already frozen package");
15781            }
15782            ps.frozen = true;
15783
15784            currentAsec = pkg.applicationInfo.isForwardLocked()
15785                    || pkg.applicationInfo.isExternalAsec();
15786            currentVolumeUuid = ps.volumeUuid;
15787            codeFile = new File(pkg.codePath);
15788            installerPackageName = ps.installerPackageName;
15789            packageAbiOverride = ps.cpuAbiOverrideString;
15790            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15791            seinfo = pkg.applicationInfo.seinfo;
15792            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15793        }
15794
15795        // Now that we're guarded by frozen state, kill app during move
15796        killApplication(packageName, appId, "move pkg");
15797
15798        final Bundle extras = new Bundle();
15799        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15800        extras.putString(Intent.EXTRA_TITLE, label);
15801        mMoveCallbacks.notifyCreated(moveId, extras);
15802
15803        int installFlags;
15804        final boolean moveCompleteApp;
15805        final File measurePath;
15806
15807        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15808            installFlags = INSTALL_INTERNAL;
15809            moveCompleteApp = !currentAsec;
15810            measurePath = Environment.getDataAppDirectory(volumeUuid);
15811        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15812            installFlags = INSTALL_EXTERNAL;
15813            moveCompleteApp = false;
15814            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15815        } else {
15816            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15817            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15818                    || !volume.isMountedWritable()) {
15819                unfreezePackage(packageName);
15820                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15821                        "Move location not mounted private volume");
15822            }
15823
15824            Preconditions.checkState(!currentAsec);
15825
15826            installFlags = INSTALL_INTERNAL;
15827            moveCompleteApp = true;
15828            measurePath = Environment.getDataAppDirectory(volumeUuid);
15829        }
15830
15831        final PackageStats stats = new PackageStats(null, -1);
15832        synchronized (mInstaller) {
15833            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15834                unfreezePackage(packageName);
15835                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15836                        "Failed to measure package size");
15837            }
15838        }
15839
15840        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15841                + stats.dataSize);
15842
15843        final long startFreeBytes = measurePath.getFreeSpace();
15844        final long sizeBytes;
15845        if (moveCompleteApp) {
15846            sizeBytes = stats.codeSize + stats.dataSize;
15847        } else {
15848            sizeBytes = stats.codeSize;
15849        }
15850
15851        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15852            unfreezePackage(packageName);
15853            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15854                    "Not enough free space to move");
15855        }
15856
15857        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15858
15859        final CountDownLatch installedLatch = new CountDownLatch(1);
15860        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15861            @Override
15862            public void onUserActionRequired(Intent intent) throws RemoteException {
15863                throw new IllegalStateException();
15864            }
15865
15866            @Override
15867            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15868                    Bundle extras) throws RemoteException {
15869                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15870                        + PackageManager.installStatusToString(returnCode, msg));
15871
15872                installedLatch.countDown();
15873
15874                // Regardless of success or failure of the move operation,
15875                // always unfreeze the package
15876                unfreezePackage(packageName);
15877
15878                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15879                switch (status) {
15880                    case PackageInstaller.STATUS_SUCCESS:
15881                        mMoveCallbacks.notifyStatusChanged(moveId,
15882                                PackageManager.MOVE_SUCCEEDED);
15883                        break;
15884                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15885                        mMoveCallbacks.notifyStatusChanged(moveId,
15886                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15887                        break;
15888                    default:
15889                        mMoveCallbacks.notifyStatusChanged(moveId,
15890                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15891                        break;
15892                }
15893            }
15894        };
15895
15896        final MoveInfo move;
15897        if (moveCompleteApp) {
15898            // Kick off a thread to report progress estimates
15899            new Thread() {
15900                @Override
15901                public void run() {
15902                    while (true) {
15903                        try {
15904                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15905                                break;
15906                            }
15907                        } catch (InterruptedException ignored) {
15908                        }
15909
15910                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15911                        final int progress = 10 + (int) MathUtils.constrain(
15912                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15913                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15914                    }
15915                }
15916            }.start();
15917
15918            final String dataAppName = codeFile.getName();
15919            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15920                    dataAppName, appId, seinfo);
15921        } else {
15922            move = null;
15923        }
15924
15925        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15926
15927        final Message msg = mHandler.obtainMessage(INIT_COPY);
15928        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15929        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15930                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
15931        mHandler.sendMessage(msg);
15932    }
15933
15934    @Override
15935    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15937
15938        final int realMoveId = mNextMoveId.getAndIncrement();
15939        final Bundle extras = new Bundle();
15940        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15941        mMoveCallbacks.notifyCreated(realMoveId, extras);
15942
15943        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15944            @Override
15945            public void onCreated(int moveId, Bundle extras) {
15946                // Ignored
15947            }
15948
15949            @Override
15950            public void onStatusChanged(int moveId, int status, long estMillis) {
15951                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15952            }
15953        };
15954
15955        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15956        storage.setPrimaryStorageUuid(volumeUuid, callback);
15957        return realMoveId;
15958    }
15959
15960    @Override
15961    public int getMoveStatus(int moveId) {
15962        mContext.enforceCallingOrSelfPermission(
15963                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15964        return mMoveCallbacks.mLastStatus.get(moveId);
15965    }
15966
15967    @Override
15968    public void registerMoveCallback(IPackageMoveObserver callback) {
15969        mContext.enforceCallingOrSelfPermission(
15970                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15971        mMoveCallbacks.register(callback);
15972    }
15973
15974    @Override
15975    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15976        mContext.enforceCallingOrSelfPermission(
15977                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15978        mMoveCallbacks.unregister(callback);
15979    }
15980
15981    @Override
15982    public boolean setInstallLocation(int loc) {
15983        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15984                null);
15985        if (getInstallLocation() == loc) {
15986            return true;
15987        }
15988        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15989                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15990            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15991                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15992            return true;
15993        }
15994        return false;
15995   }
15996
15997    @Override
15998    public int getInstallLocation() {
15999        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16000                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16001                PackageHelper.APP_INSTALL_AUTO);
16002    }
16003
16004    /** Called by UserManagerService */
16005    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16006        mDirtyUsers.remove(userHandle);
16007        mSettings.removeUserLPw(userHandle);
16008        mPendingBroadcasts.remove(userHandle);
16009        if (mInstaller != null) {
16010            // Technically, we shouldn't be doing this with the package lock
16011            // held.  However, this is very rare, and there is already so much
16012            // other disk I/O going on, that we'll let it slide for now.
16013            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16014            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16015                final String volumeUuid = vol.getFsUuid();
16016                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16017                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16018            }
16019        }
16020        mUserNeedsBadging.delete(userHandle);
16021        removeUnusedPackagesLILPw(userManager, userHandle);
16022    }
16023
16024    /**
16025     * We're removing userHandle and would like to remove any downloaded packages
16026     * that are no longer in use by any other user.
16027     * @param userHandle the user being removed
16028     */
16029    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16030        final boolean DEBUG_CLEAN_APKS = false;
16031        int [] users = userManager.getUserIdsLPr();
16032        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16033        while (psit.hasNext()) {
16034            PackageSetting ps = psit.next();
16035            if (ps.pkg == null) {
16036                continue;
16037            }
16038            final String packageName = ps.pkg.packageName;
16039            // Skip over if system app
16040            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16041                continue;
16042            }
16043            if (DEBUG_CLEAN_APKS) {
16044                Slog.i(TAG, "Checking package " + packageName);
16045            }
16046            boolean keep = false;
16047            for (int i = 0; i < users.length; i++) {
16048                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16049                    keep = true;
16050                    if (DEBUG_CLEAN_APKS) {
16051                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16052                                + users[i]);
16053                    }
16054                    break;
16055                }
16056            }
16057            if (!keep) {
16058                if (DEBUG_CLEAN_APKS) {
16059                    Slog.i(TAG, "  Removing package " + packageName);
16060                }
16061                mHandler.post(new Runnable() {
16062                    public void run() {
16063                        deletePackageX(packageName, userHandle, 0);
16064                    } //end run
16065                });
16066            }
16067        }
16068    }
16069
16070    /** Called by UserManagerService */
16071    void createNewUserLILPw(int userHandle) {
16072        if (mInstaller != null) {
16073            mInstaller.createUserConfig(userHandle);
16074            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16075            applyFactoryDefaultBrowserLPw(userHandle);
16076            primeDomainVerificationsLPw(userHandle);
16077        }
16078    }
16079
16080    void newUserCreated(final int userHandle) {
16081        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16082    }
16083
16084    @Override
16085    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16086        mContext.enforceCallingOrSelfPermission(
16087                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16088                "Only package verification agents can read the verifier device identity");
16089
16090        synchronized (mPackages) {
16091            return mSettings.getVerifierDeviceIdentityLPw();
16092        }
16093    }
16094
16095    @Override
16096    public void setPermissionEnforced(String permission, boolean enforced) {
16097        // TODO: Now that we no longer change GID for storage, this should to away.
16098        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16099                "setPermissionEnforced");
16100        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16101            synchronized (mPackages) {
16102                if (mSettings.mReadExternalStorageEnforced == null
16103                        || mSettings.mReadExternalStorageEnforced != enforced) {
16104                    mSettings.mReadExternalStorageEnforced = enforced;
16105                    mSettings.writeLPr();
16106                }
16107            }
16108            // kill any non-foreground processes so we restart them and
16109            // grant/revoke the GID.
16110            final IActivityManager am = ActivityManagerNative.getDefault();
16111            if (am != null) {
16112                final long token = Binder.clearCallingIdentity();
16113                try {
16114                    am.killProcessesBelowForeground("setPermissionEnforcement");
16115                } catch (RemoteException e) {
16116                } finally {
16117                    Binder.restoreCallingIdentity(token);
16118                }
16119            }
16120        } else {
16121            throw new IllegalArgumentException("No selective enforcement for " + permission);
16122        }
16123    }
16124
16125    @Override
16126    @Deprecated
16127    public boolean isPermissionEnforced(String permission) {
16128        return true;
16129    }
16130
16131    @Override
16132    public boolean isStorageLow() {
16133        final long token = Binder.clearCallingIdentity();
16134        try {
16135            final DeviceStorageMonitorInternal
16136                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16137            if (dsm != null) {
16138                return dsm.isMemoryLow();
16139            } else {
16140                return false;
16141            }
16142        } finally {
16143            Binder.restoreCallingIdentity(token);
16144        }
16145    }
16146
16147    @Override
16148    public IPackageInstaller getPackageInstaller() {
16149        return mInstallerService;
16150    }
16151
16152    private boolean userNeedsBadging(int userId) {
16153        int index = mUserNeedsBadging.indexOfKey(userId);
16154        if (index < 0) {
16155            final UserInfo userInfo;
16156            final long token = Binder.clearCallingIdentity();
16157            try {
16158                userInfo = sUserManager.getUserInfo(userId);
16159            } finally {
16160                Binder.restoreCallingIdentity(token);
16161            }
16162            final boolean b;
16163            if (userInfo != null && userInfo.isManagedProfile()) {
16164                b = true;
16165            } else {
16166                b = false;
16167            }
16168            mUserNeedsBadging.put(userId, b);
16169            return b;
16170        }
16171        return mUserNeedsBadging.valueAt(index);
16172    }
16173
16174    @Override
16175    public KeySet getKeySetByAlias(String packageName, String alias) {
16176        if (packageName == null || alias == null) {
16177            return null;
16178        }
16179        synchronized(mPackages) {
16180            final PackageParser.Package pkg = mPackages.get(packageName);
16181            if (pkg == null) {
16182                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16183                throw new IllegalArgumentException("Unknown package: " + packageName);
16184            }
16185            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16186            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16187        }
16188    }
16189
16190    @Override
16191    public KeySet getSigningKeySet(String packageName) {
16192        if (packageName == null) {
16193            return null;
16194        }
16195        synchronized(mPackages) {
16196            final PackageParser.Package pkg = mPackages.get(packageName);
16197            if (pkg == null) {
16198                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16199                throw new IllegalArgumentException("Unknown package: " + packageName);
16200            }
16201            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16202                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16203                throw new SecurityException("May not access signing KeySet of other apps.");
16204            }
16205            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16206            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16207        }
16208    }
16209
16210    @Override
16211    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16212        if (packageName == null || ks == null) {
16213            return false;
16214        }
16215        synchronized(mPackages) {
16216            final PackageParser.Package pkg = mPackages.get(packageName);
16217            if (pkg == null) {
16218                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16219                throw new IllegalArgumentException("Unknown package: " + packageName);
16220            }
16221            IBinder ksh = ks.getToken();
16222            if (ksh instanceof KeySetHandle) {
16223                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16224                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16225            }
16226            return false;
16227        }
16228    }
16229
16230    @Override
16231    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16232        if (packageName == null || ks == null) {
16233            return false;
16234        }
16235        synchronized(mPackages) {
16236            final PackageParser.Package pkg = mPackages.get(packageName);
16237            if (pkg == null) {
16238                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16239                throw new IllegalArgumentException("Unknown package: " + packageName);
16240            }
16241            IBinder ksh = ks.getToken();
16242            if (ksh instanceof KeySetHandle) {
16243                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16244                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16245            }
16246            return false;
16247        }
16248    }
16249
16250    public void getUsageStatsIfNoPackageUsageInfo() {
16251        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16252            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16253            if (usm == null) {
16254                throw new IllegalStateException("UsageStatsManager must be initialized");
16255            }
16256            long now = System.currentTimeMillis();
16257            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16258            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16259                String packageName = entry.getKey();
16260                PackageParser.Package pkg = mPackages.get(packageName);
16261                if (pkg == null) {
16262                    continue;
16263                }
16264                UsageStats usage = entry.getValue();
16265                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16266                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16267            }
16268        }
16269    }
16270
16271    /**
16272     * Check and throw if the given before/after packages would be considered a
16273     * downgrade.
16274     */
16275    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16276            throws PackageManagerException {
16277        if (after.versionCode < before.mVersionCode) {
16278            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16279                    "Update version code " + after.versionCode + " is older than current "
16280                    + before.mVersionCode);
16281        } else if (after.versionCode == before.mVersionCode) {
16282            if (after.baseRevisionCode < before.baseRevisionCode) {
16283                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16284                        "Update base revision code " + after.baseRevisionCode
16285                        + " is older than current " + before.baseRevisionCode);
16286            }
16287
16288            if (!ArrayUtils.isEmpty(after.splitNames)) {
16289                for (int i = 0; i < after.splitNames.length; i++) {
16290                    final String splitName = after.splitNames[i];
16291                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16292                    if (j != -1) {
16293                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16294                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16295                                    "Update split " + splitName + " revision code "
16296                                    + after.splitRevisionCodes[i] + " is older than current "
16297                                    + before.splitRevisionCodes[j]);
16298                        }
16299                    }
16300                }
16301            }
16302        }
16303    }
16304
16305    private static class MoveCallbacks extends Handler {
16306        private static final int MSG_CREATED = 1;
16307        private static final int MSG_STATUS_CHANGED = 2;
16308
16309        private final RemoteCallbackList<IPackageMoveObserver>
16310                mCallbacks = new RemoteCallbackList<>();
16311
16312        private final SparseIntArray mLastStatus = new SparseIntArray();
16313
16314        public MoveCallbacks(Looper looper) {
16315            super(looper);
16316        }
16317
16318        public void register(IPackageMoveObserver callback) {
16319            mCallbacks.register(callback);
16320        }
16321
16322        public void unregister(IPackageMoveObserver callback) {
16323            mCallbacks.unregister(callback);
16324        }
16325
16326        @Override
16327        public void handleMessage(Message msg) {
16328            final SomeArgs args = (SomeArgs) msg.obj;
16329            final int n = mCallbacks.beginBroadcast();
16330            for (int i = 0; i < n; i++) {
16331                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16332                try {
16333                    invokeCallback(callback, msg.what, args);
16334                } catch (RemoteException ignored) {
16335                }
16336            }
16337            mCallbacks.finishBroadcast();
16338            args.recycle();
16339        }
16340
16341        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16342                throws RemoteException {
16343            switch (what) {
16344                case MSG_CREATED: {
16345                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16346                    break;
16347                }
16348                case MSG_STATUS_CHANGED: {
16349                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16350                    break;
16351                }
16352            }
16353        }
16354
16355        private void notifyCreated(int moveId, Bundle extras) {
16356            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16357
16358            final SomeArgs args = SomeArgs.obtain();
16359            args.argi1 = moveId;
16360            args.arg2 = extras;
16361            obtainMessage(MSG_CREATED, args).sendToTarget();
16362        }
16363
16364        private void notifyStatusChanged(int moveId, int status) {
16365            notifyStatusChanged(moveId, status, -1);
16366        }
16367
16368        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16369            Slog.v(TAG, "Move " + moveId + " status " + status);
16370
16371            final SomeArgs args = SomeArgs.obtain();
16372            args.argi1 = moveId;
16373            args.argi2 = status;
16374            args.arg3 = estMillis;
16375            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16376
16377            synchronized (mLastStatus) {
16378                mLastStatus.put(moveId, status);
16379            }
16380        }
16381    }
16382
16383    private final class OnPermissionChangeListeners extends Handler {
16384        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16385
16386        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16387                new RemoteCallbackList<>();
16388
16389        public OnPermissionChangeListeners(Looper looper) {
16390            super(looper);
16391        }
16392
16393        @Override
16394        public void handleMessage(Message msg) {
16395            switch (msg.what) {
16396                case MSG_ON_PERMISSIONS_CHANGED: {
16397                    final int uid = msg.arg1;
16398                    handleOnPermissionsChanged(uid);
16399                } break;
16400            }
16401        }
16402
16403        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16404            mPermissionListeners.register(listener);
16405
16406        }
16407
16408        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16409            mPermissionListeners.unregister(listener);
16410        }
16411
16412        public void onPermissionsChanged(int uid) {
16413            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16414                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16415            }
16416        }
16417
16418        private void handleOnPermissionsChanged(int uid) {
16419            final int count = mPermissionListeners.beginBroadcast();
16420            try {
16421                for (int i = 0; i < count; i++) {
16422                    IOnPermissionsChangeListener callback = mPermissionListeners
16423                            .getBroadcastItem(i);
16424                    try {
16425                        callback.onPermissionsChanged(uid);
16426                    } catch (RemoteException e) {
16427                        Log.e(TAG, "Permission listener is dead", e);
16428                    }
16429                }
16430            } finally {
16431                mPermissionListeners.finishBroadcast();
16432            }
16433        }
16434    }
16435
16436    private class PackageManagerInternalImpl extends PackageManagerInternal {
16437        @Override
16438        public void setLocationPackagesProvider(PackagesProvider provider) {
16439            synchronized (mPackages) {
16440                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16441            }
16442        }
16443
16444        @Override
16445        public void setImePackagesProvider(PackagesProvider provider) {
16446            synchronized (mPackages) {
16447                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16448            }
16449        }
16450
16451        @Override
16452        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16453            synchronized (mPackages) {
16454                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16455            }
16456        }
16457
16458        @Override
16459        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16460            synchronized (mPackages) {
16461                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16462            }
16463        }
16464
16465        @Override
16466        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16467            synchronized (mPackages) {
16468                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16469            }
16470        }
16471
16472        @Override
16473        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16474            synchronized (mPackages) {
16475                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16476            }
16477        }
16478
16479        @Override
16480        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16481            synchronized (mPackages) {
16482                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16483                        packageName, userId);
16484            }
16485        }
16486
16487        @Override
16488        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16489            synchronized (mPackages) {
16490                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16491                        packageName, userId);
16492            }
16493        }
16494    }
16495
16496    @Override
16497    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16498        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16499        synchronized (mPackages) {
16500            final long identity = Binder.clearCallingIdentity();
16501            try {
16502                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16503                        packageNames, userId);
16504            } finally {
16505                Binder.restoreCallingIdentity(identity);
16506            }
16507        }
16508    }
16509
16510    private static void enforceSystemOrPhoneCaller(String tag) {
16511        int callingUid = Binder.getCallingUid();
16512        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16513            throw new SecurityException(
16514                    "Cannot call " + tag + " from UID " + callingUid);
16515        }
16516    }
16517}
16518