PackageManagerService.java revision 4fab7fbeb01026e5dc81f9d0dc445042e91c8f80
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.system.OsConstants.O_CREAT;
71import static android.system.OsConstants.O_RDWR;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76import static com.android.internal.util.ArrayUtils.appendInt;
77import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
78import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
86
87import android.Manifest;
88import android.app.ActivityManager;
89import android.app.ActivityManagerNative;
90import android.app.AppGlobals;
91import android.app.IActivityManager;
92import android.app.admin.IDevicePolicyManager;
93import android.app.backup.IBackupManager;
94import android.app.usage.UsageStats;
95import android.app.usage.UsageStatsManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.FeatureInfo;
108import android.content.pm.IOnPermissionsChangeListener;
109import android.content.pm.IPackageDataObserver;
110import android.content.pm.IPackageDeleteObserver;
111import android.content.pm.IPackageDeleteObserver2;
112import android.content.pm.IPackageInstallObserver2;
113import android.content.pm.IPackageInstaller;
114import android.content.pm.IPackageManager;
115import android.content.pm.IPackageMoveObserver;
116import android.content.pm.IPackageStatsObserver;
117import android.content.pm.InstrumentationInfo;
118import android.content.pm.IntentFilterVerificationInfo;
119import android.content.pm.KeySet;
120import android.content.pm.ManifestDigest;
121import android.content.pm.PackageCleanItem;
122import android.content.pm.PackageInfo;
123import android.content.pm.PackageInfoLite;
124import android.content.pm.PackageInstaller;
125import android.content.pm.PackageManager;
126import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
127import android.content.pm.PackageManagerInternal;
128import android.content.pm.PackageParser;
129import android.content.pm.PackageParser.ActivityIntentInfo;
130import android.content.pm.PackageParser.PackageLite;
131import android.content.pm.PackageParser.PackageParserException;
132import android.content.pm.PackageStats;
133import android.content.pm.PackageUserState;
134import android.content.pm.ParceledListSlice;
135import android.content.pm.PermissionGroupInfo;
136import android.content.pm.PermissionInfo;
137import android.content.pm.ProviderInfo;
138import android.content.pm.ResolveInfo;
139import android.content.pm.ServiceInfo;
140import android.content.pm.Signature;
141import android.content.pm.UserInfo;
142import android.content.pm.VerificationParams;
143import android.content.pm.VerifierDeviceIdentity;
144import android.content.pm.VerifierInfo;
145import android.content.res.Resources;
146import android.hardware.display.DisplayManager;
147import android.net.Uri;
148import android.os.Debug;
149import android.os.Binder;
150import android.os.Build;
151import android.os.Bundle;
152import android.os.Environment;
153import android.os.Environment.UserEnvironment;
154import android.os.FileUtils;
155import android.os.Handler;
156import android.os.IBinder;
157import android.os.Looper;
158import android.os.Message;
159import android.os.Parcel;
160import android.os.ParcelFileDescriptor;
161import android.os.Process;
162import android.os.RemoteCallbackList;
163import android.os.RemoteException;
164import android.os.SELinux;
165import android.os.ServiceManager;
166import android.os.SystemClock;
167import android.os.SystemProperties;
168import android.os.UserHandle;
169import android.os.UserManager;
170import android.os.storage.IMountService;
171import android.os.storage.MountServiceInternal;
172import android.os.storage.StorageEventListener;
173import android.os.storage.StorageManager;
174import android.os.storage.VolumeInfo;
175import android.os.storage.VolumeRecord;
176import android.security.KeyStore;
177import android.security.SystemKeyStore;
178import android.system.ErrnoException;
179import android.system.Os;
180import android.system.StructStat;
181import android.text.TextUtils;
182import android.text.format.DateUtils;
183import android.util.ArrayMap;
184import android.util.ArraySet;
185import android.util.AtomicFile;
186import android.util.DisplayMetrics;
187import android.util.EventLog;
188import android.util.ExceptionUtils;
189import android.util.Log;
190import android.util.LogPrinter;
191import android.util.MathUtils;
192import android.util.PrintStreamPrinter;
193import android.util.Slog;
194import android.util.SparseArray;
195import android.util.SparseBooleanArray;
196import android.util.SparseIntArray;
197import android.util.Xml;
198import android.view.Display;
199
200import dalvik.system.DexFile;
201import dalvik.system.VMRuntime;
202
203import libcore.io.IoUtils;
204import libcore.util.EmptyArray;
205
206import com.android.internal.R;
207import com.android.internal.annotations.GuardedBy;
208import com.android.internal.app.IMediaContainerService;
209import com.android.internal.app.ResolverActivity;
210import com.android.internal.content.NativeLibraryHelper;
211import com.android.internal.content.PackageHelper;
212import com.android.internal.os.IParcelFileDescriptorFactory;
213import com.android.internal.os.SomeArgs;
214import com.android.internal.os.Zygote;
215import com.android.internal.util.ArrayUtils;
216import com.android.internal.util.FastPrintWriter;
217import com.android.internal.util.FastXmlSerializer;
218import com.android.internal.util.IndentingPrintWriter;
219import com.android.internal.util.Preconditions;
220import com.android.server.EventLogTags;
221import com.android.server.FgThread;
222import com.android.server.IntentResolver;
223import com.android.server.LocalServices;
224import com.android.server.ServiceThread;
225import com.android.server.SystemConfig;
226import com.android.server.Watchdog;
227import com.android.server.pm.PermissionsState.PermissionState;
228import com.android.server.pm.Settings.DatabaseVersion;
229import com.android.server.pm.Settings.VersionInfo;
230import com.android.server.storage.DeviceStorageMonitorInternal;
231
232import org.xmlpull.v1.XmlPullParser;
233import org.xmlpull.v1.XmlPullParserException;
234import org.xmlpull.v1.XmlSerializer;
235
236import java.io.BufferedInputStream;
237import java.io.BufferedOutputStream;
238import java.io.BufferedReader;
239import java.io.ByteArrayInputStream;
240import java.io.ByteArrayOutputStream;
241import java.io.File;
242import java.io.FileDescriptor;
243import java.io.FileNotFoundException;
244import java.io.FileOutputStream;
245import java.io.FileReader;
246import java.io.FilenameFilter;
247import java.io.IOException;
248import java.io.InputStream;
249import java.io.PrintWriter;
250import java.nio.charset.StandardCharsets;
251import java.security.NoSuchAlgorithmException;
252import java.security.PublicKey;
253import java.security.cert.CertificateEncodingException;
254import java.security.cert.CertificateException;
255import java.text.SimpleDateFormat;
256import java.util.ArrayList;
257import java.util.Arrays;
258import java.util.Collection;
259import java.util.Collections;
260import java.util.Comparator;
261import java.util.Date;
262import java.util.Iterator;
263import java.util.List;
264import java.util.Map;
265import java.util.Objects;
266import java.util.Set;
267import java.util.concurrent.CountDownLatch;
268import java.util.concurrent.TimeUnit;
269import java.util.concurrent.atomic.AtomicBoolean;
270import java.util.concurrent.atomic.AtomicInteger;
271import java.util.concurrent.atomic.AtomicLong;
272
273/**
274 * Keep track of all those .apks everywhere.
275 *
276 * This is very central to the platform's security; please run the unit
277 * tests whenever making modifications here:
278 *
279mmm frameworks/base/tests/AndroidTests
280adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
281adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
282 *
283 * {@hide}
284 */
285public class PackageManagerService extends IPackageManager.Stub {
286    static final String TAG = "PackageManager";
287    static final boolean DEBUG_SETTINGS = false;
288    static final boolean DEBUG_PREFERRED = false;
289    static final boolean DEBUG_UPGRADE = false;
290    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
291    private static final boolean DEBUG_BACKUP = false;
292    private static final boolean DEBUG_INSTALL = false;
293    private static final boolean DEBUG_REMOVE = false;
294    private static final boolean DEBUG_BROADCASTS = false;
295    private static final boolean DEBUG_SHOW_INFO = false;
296    private static final boolean DEBUG_PACKAGE_INFO = false;
297    private static final boolean DEBUG_INTENT_MATCHING = false;
298    private static final boolean DEBUG_PACKAGE_SCANNING = false;
299    private static final boolean DEBUG_VERIFY = false;
300    private static final boolean DEBUG_DEXOPT = false;
301    private static final boolean DEBUG_ABI_SELECTION = false;
302
303    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
304
305    private static final int RADIO_UID = Process.PHONE_UID;
306    private static final int LOG_UID = Process.LOG_UID;
307    private static final int NFC_UID = Process.NFC_UID;
308    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
309    private static final int SHELL_UID = Process.SHELL_UID;
310
311    // Cap the size of permission trees that 3rd party apps can define
312    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
313
314    // Suffix used during package installation when copying/moving
315    // package apks to install directory.
316    private static final String INSTALL_PACKAGE_SUFFIX = "-";
317
318    static final int SCAN_NO_DEX = 1<<1;
319    static final int SCAN_FORCE_DEX = 1<<2;
320    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
321    static final int SCAN_NEW_INSTALL = 1<<4;
322    static final int SCAN_NO_PATHS = 1<<5;
323    static final int SCAN_UPDATE_TIME = 1<<6;
324    static final int SCAN_DEFER_DEX = 1<<7;
325    static final int SCAN_BOOTING = 1<<8;
326    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
327    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
328    static final int SCAN_REPLACING = 1<<11;
329    static final int SCAN_REQUIRE_KNOWN = 1<<12;
330    static final int SCAN_MOVE = 1<<13;
331    static final int SCAN_INITIAL = 1<<14;
332
333    static final int REMOVE_CHATTY = 1<<16;
334
335    private static final int[] EMPTY_INT_ARRAY = new int[0];
336
337    /**
338     * Timeout (in milliseconds) after which the watchdog should declare that
339     * our handler thread is wedged.  The usual default for such things is one
340     * minute but we sometimes do very lengthy I/O operations on this thread,
341     * such as installing multi-gigabyte applications, so ours needs to be longer.
342     */
343    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
344
345    /**
346     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
347     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
348     * settings entry if available, otherwise we use the hardcoded default.  If it's been
349     * more than this long since the last fstrim, we force one during the boot sequence.
350     *
351     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
352     * one gets run at the next available charging+idle time.  This final mandatory
353     * no-fstrim check kicks in only of the other scheduling criteria is never met.
354     */
355    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
356
357    /**
358     * Whether verification is enabled by default.
359     */
360    private static final boolean DEFAULT_VERIFY_ENABLE = true;
361
362    /**
363     * The default maximum time to wait for the verification agent to return in
364     * milliseconds.
365     */
366    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
367
368    /**
369     * The default response for package verification timeout.
370     *
371     * This can be either PackageManager.VERIFICATION_ALLOW or
372     * PackageManager.VERIFICATION_REJECT.
373     */
374    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
375
376    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
377
378    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
379            DEFAULT_CONTAINER_PACKAGE,
380            "com.android.defcontainer.DefaultContainerService");
381
382    private static final String KILL_APP_REASON_GIDS_CHANGED =
383            "permission grant or revoke changed gids";
384
385    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
386            "permissions revoked";
387
388    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
389
390    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
391
392    /** Permission grant: not grant the permission. */
393    private static final int GRANT_DENIED = 1;
394
395    /** Permission grant: grant the permission as an install permission. */
396    private static final int GRANT_INSTALL = 2;
397
398    /** Permission grant: grant the permission as an install permission for a legacy app. */
399    private static final int GRANT_INSTALL_LEGACY = 3;
400
401    /** Permission grant: grant the permission as a runtime one. */
402    private static final int GRANT_RUNTIME = 4;
403
404    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
405    private static final int GRANT_UPGRADE = 5;
406
407    /** Canonical intent used to identify what counts as a "web browser" app */
408    private static final Intent sBrowserIntent;
409    static {
410        sBrowserIntent = new Intent();
411        sBrowserIntent.setAction(Intent.ACTION_VIEW);
412        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
413        sBrowserIntent.setData(Uri.parse("http:"));
414    }
415
416    final ServiceThread mHandlerThread;
417
418    final PackageHandler mHandler;
419
420    /**
421     * Messages for {@link #mHandler} that need to wait for system ready before
422     * being dispatched.
423     */
424    private ArrayList<Message> mPostSystemReadyMessages;
425
426    final int mSdkVersion = Build.VERSION.SDK_INT;
427
428    final Context mContext;
429    final boolean mFactoryTest;
430    final boolean mOnlyCore;
431    final boolean mLazyDexOpt;
432    final long mDexOptLRUThresholdInMills;
433    final DisplayMetrics mMetrics;
434    final int mDefParseFlags;
435    final String[] mSeparateProcesses;
436    final boolean mIsUpgrade;
437
438    // This is where all application persistent data goes.
439    final File mAppDataDir;
440
441    // This is where all application persistent data goes for secondary users.
442    final File mUserAppDataDir;
443
444    /** The location for ASEC container files on internal storage. */
445    final String mAsecInternalPath;
446
447    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
448    // LOCK HELD.  Can be called with mInstallLock held.
449    @GuardedBy("mInstallLock")
450    final Installer mInstaller;
451
452    /** Directory where installed third-party apps stored */
453    final File mAppInstallDir;
454
455    /**
456     * Directory to which applications installed internally have their
457     * 32 bit native libraries copied.
458     */
459    private File mAppLib32InstallDir;
460
461    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
462    // apps.
463    final File mDrmAppPrivateInstallDir;
464
465    // ----------------------------------------------------------------
466
467    // Lock for state used when installing and doing other long running
468    // operations.  Methods that must be called with this lock held have
469    // the suffix "LI".
470    final Object mInstallLock = new Object();
471
472    // ----------------------------------------------------------------
473
474    // Keys are String (package name), values are Package.  This also serves
475    // as the lock for the global state.  Methods that must be called with
476    // this lock held have the prefix "LP".
477    @GuardedBy("mPackages")
478    final ArrayMap<String, PackageParser.Package> mPackages =
479            new ArrayMap<String, PackageParser.Package>();
480
481    // Tracks available target package names -> overlay package paths.
482    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
483        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
484
485    /**
486     * Tracks new system packages [received in an OTA] that we expect to
487     * find updated user-installed versions. Keys are package name, values
488     * are package location.
489     */
490    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
491
492    /**
493     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
494     */
495    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
496    /**
497     * Whether or not system app permissions should be promoted from install to runtime.
498     */
499    boolean mPromoteSystemApps;
500
501    final Settings mSettings;
502    boolean mRestoredSettings;
503
504    // System configuration read by SystemConfig.
505    final int[] mGlobalGids;
506    final SparseArray<ArraySet<String>> mSystemPermissions;
507    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
508
509    // If mac_permissions.xml was found for seinfo labeling.
510    boolean mFoundPolicyFile;
511
512    // If a recursive restorecon of /data/data/<pkg> is needed.
513    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
514
515    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
602            = new SparseArray<IntentFilterVerificationState>();
603
604    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
605            new DefaultPermissionGrantPolicy(this);
606
607    private static class IFVerificationParams {
608        PackageParser.Package pkg;
609        boolean replacing;
610        int userId;
611        int verifierUid;
612
613        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
614                int _userId, int _verifierUid) {
615            pkg = _pkg;
616            replacing = _replacing;
617            userId = _userId;
618            replacing = _replacing;
619            verifierUid = _verifierUid;
620        }
621    }
622
623    private interface IntentFilterVerifier<T extends IntentFilter> {
624        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
625                                               T filter, String packageName);
626        void startVerifications(int userId);
627        void receiveVerificationResponse(int verificationId);
628    }
629
630    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
631        private Context mContext;
632        private ComponentName mIntentFilterVerifierComponent;
633        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
634
635        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
636            mContext = context;
637            mIntentFilterVerifierComponent = verifierComponent;
638        }
639
640        private String getDefaultScheme() {
641            return IntentFilter.SCHEME_HTTPS;
642        }
643
644        @Override
645        public void startVerifications(int userId) {
646            // Launch verifications requests
647            int count = mCurrentIntentFilterVerifications.size();
648            for (int n=0; n<count; n++) {
649                int verificationId = mCurrentIntentFilterVerifications.get(n);
650                final IntentFilterVerificationState ivs =
651                        mIntentFilterVerificationStates.get(verificationId);
652
653                String packageName = ivs.getPackageName();
654
655                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656                final int filterCount = filters.size();
657                ArraySet<String> domainsSet = new ArraySet<>();
658                for (int m=0; m<filterCount; m++) {
659                    PackageParser.ActivityIntentInfo filter = filters.get(m);
660                    domainsSet.addAll(filter.getHostsList());
661                }
662                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
663                synchronized (mPackages) {
664                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
665                            packageName, domainsList) != null) {
666                        scheduleWriteSettingsLocked();
667                    }
668                }
669                sendVerificationRequest(userId, verificationId, ivs);
670            }
671            mCurrentIntentFilterVerifications.clear();
672        }
673
674        private void sendVerificationRequest(int userId, int verificationId,
675                IntentFilterVerificationState ivs) {
676
677            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
678            verificationIntent.putExtra(
679                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
680                    verificationId);
681            verificationIntent.putExtra(
682                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
683                    getDefaultScheme());
684            verificationIntent.putExtra(
685                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
686                    ivs.getHostsString());
687            verificationIntent.putExtra(
688                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
689                    ivs.getPackageName());
690            verificationIntent.setComponent(mIntentFilterVerifierComponent);
691            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
692
693            UserHandle user = new UserHandle(userId);
694            mContext.sendBroadcastAsUser(verificationIntent, user);
695            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
696                    "Sending IntentFilter verification broadcast");
697        }
698
699        public void receiveVerificationResponse(int verificationId) {
700            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
701
702            final boolean verified = ivs.isVerified();
703
704            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
705            final int count = filters.size();
706            if (DEBUG_DOMAIN_VERIFICATION) {
707                Slog.i(TAG, "Received verification response " + verificationId
708                        + " for " + count + " filters, verified=" + verified);
709            }
710            for (int n=0; n<count; n++) {
711                PackageParser.ActivityIntentInfo filter = filters.get(n);
712                filter.setVerified(verified);
713
714                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
715                        + " verified with result:" + verified + " and hosts:"
716                        + ivs.getHostsString());
717            }
718
719            mIntentFilterVerificationStates.remove(verificationId);
720
721            final String packageName = ivs.getPackageName();
722            IntentFilterVerificationInfo ivi = null;
723
724            synchronized (mPackages) {
725                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
726            }
727            if (ivi == null) {
728                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
729                        + verificationId + " packageName:" + packageName);
730                return;
731            }
732            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
733                    "Updating IntentFilterVerificationInfo for package " + packageName
734                            +" verificationId:" + verificationId);
735
736            synchronized (mPackages) {
737                if (verified) {
738                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
739                } else {
740                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
741                }
742                scheduleWriteSettingsLocked();
743
744                final int userId = ivs.getUserId();
745                if (userId != UserHandle.USER_ALL) {
746                    final int userStatus =
747                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
748
749                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
750                    boolean needUpdate = false;
751
752                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
753                    // already been set by the User thru the Disambiguation dialog
754                    switch (userStatus) {
755                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
756                            if (verified) {
757                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
758                            } else {
759                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
760                            }
761                            needUpdate = true;
762                            break;
763
764                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
765                            if (verified) {
766                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
767                                needUpdate = true;
768                            }
769                            break;
770
771                        default:
772                            // Nothing to do
773                    }
774
775                    if (needUpdate) {
776                        mSettings.updateIntentFilterVerificationStatusLPw(
777                                packageName, updatedStatus, userId);
778                        scheduleWritePackageRestrictionsLocked(userId);
779                    }
780                }
781            }
782        }
783
784        @Override
785        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
786                    ActivityIntentInfo filter, String packageName) {
787            if (!hasValidDomains(filter)) {
788                return false;
789            }
790            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
791            if (ivs == null) {
792                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
793                        packageName);
794            }
795            if (DEBUG_DOMAIN_VERIFICATION) {
796                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
797            }
798            ivs.addFilter(filter);
799            return true;
800        }
801
802        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
803                int userId, int verificationId, String packageName) {
804            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
805                    verifierUid, userId, packageName);
806            ivs.setPendingState();
807            synchronized (mPackages) {
808                mIntentFilterVerificationStates.append(verificationId, ivs);
809                mCurrentIntentFilterVerifications.add(verificationId);
810            }
811            return ivs;
812        }
813    }
814
815    private static boolean hasValidDomains(ActivityIntentInfo filter) {
816        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
817                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
818                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
819    }
820
821    private IntentFilterVerifier mIntentFilterVerifier;
822
823    // Set of pending broadcasts for aggregating enable/disable of components.
824    static class PendingPackageBroadcasts {
825        // for each user id, a map of <package name -> components within that package>
826        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
827
828        public PendingPackageBroadcasts() {
829            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
830        }
831
832        public ArrayList<String> get(int userId, String packageName) {
833            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
834            return packages.get(packageName);
835        }
836
837        public void put(int userId, String packageName, ArrayList<String> components) {
838            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
839            packages.put(packageName, components);
840        }
841
842        public void remove(int userId, String packageName) {
843            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
844            if (packages != null) {
845                packages.remove(packageName);
846            }
847        }
848
849        public void remove(int userId) {
850            mUidMap.remove(userId);
851        }
852
853        public int userIdCount() {
854            return mUidMap.size();
855        }
856
857        public int userIdAt(int n) {
858            return mUidMap.keyAt(n);
859        }
860
861        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
862            return mUidMap.get(userId);
863        }
864
865        public int size() {
866            // total number of pending broadcast entries across all userIds
867            int num = 0;
868            for (int i = 0; i< mUidMap.size(); i++) {
869                num += mUidMap.valueAt(i).size();
870            }
871            return num;
872        }
873
874        public void clear() {
875            mUidMap.clear();
876        }
877
878        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
879            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
880            if (map == null) {
881                map = new ArrayMap<String, ArrayList<String>>();
882                mUidMap.put(userId, map);
883            }
884            return map;
885        }
886    }
887    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
888
889    // Service Connection to remote media container service to copy
890    // package uri's from external media onto secure containers
891    // or internal storage.
892    private IMediaContainerService mContainerService = null;
893
894    static final int SEND_PENDING_BROADCAST = 1;
895    static final int MCS_BOUND = 3;
896    static final int END_COPY = 4;
897    static final int INIT_COPY = 5;
898    static final int MCS_UNBIND = 6;
899    static final int START_CLEANING_PACKAGE = 7;
900    static final int FIND_INSTALL_LOC = 8;
901    static final int POST_INSTALL = 9;
902    static final int MCS_RECONNECT = 10;
903    static final int MCS_GIVE_UP = 11;
904    static final int UPDATED_MEDIA_STATUS = 12;
905    static final int WRITE_SETTINGS = 13;
906    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
907    static final int PACKAGE_VERIFIED = 15;
908    static final int CHECK_PENDING_VERIFICATION = 16;
909    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
910    static final int INTENT_FILTER_VERIFIED = 18;
911
912    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
913
914    // Delay time in millisecs
915    static final int BROADCAST_DELAY = 10 * 1000;
916
917    static UserManagerService sUserManager;
918
919    // Stores a list of users whose package restrictions file needs to be updated
920    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
921
922    final private DefaultContainerConnection mDefContainerConn =
923            new DefaultContainerConnection();
924    class DefaultContainerConnection implements ServiceConnection {
925        public void onServiceConnected(ComponentName name, IBinder service) {
926            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
927            IMediaContainerService imcs =
928                IMediaContainerService.Stub.asInterface(service);
929            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
930        }
931
932        public void onServiceDisconnected(ComponentName name) {
933            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
934        }
935    }
936
937    // Recordkeeping of restore-after-install operations that are currently in flight
938    // between the Package Manager and the Backup Manager
939    class PostInstallData {
940        public InstallArgs args;
941        public PackageInstalledInfo res;
942
943        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
944            args = _a;
945            res = _r;
946        }
947    }
948
949    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
950    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
951
952    // XML tags for backup/restore of various bits of state
953    private static final String TAG_PREFERRED_BACKUP = "pa";
954    private static final String TAG_DEFAULT_APPS = "da";
955    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
956
957    final String mRequiredVerifierPackage;
958    final String mRequiredInstallerPackage;
959
960    private final PackageUsage mPackageUsage = new PackageUsage();
961
962    private class PackageUsage {
963        private static final int WRITE_INTERVAL
964            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
965
966        private final Object mFileLock = new Object();
967        private final AtomicLong mLastWritten = new AtomicLong(0);
968        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
969
970        private boolean mIsHistoricalPackageUsageAvailable = true;
971
972        boolean isHistoricalPackageUsageAvailable() {
973            return mIsHistoricalPackageUsageAvailable;
974        }
975
976        void write(boolean force) {
977            if (force) {
978                writeInternal();
979                return;
980            }
981            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
982                && !DEBUG_DEXOPT) {
983                return;
984            }
985            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
986                new Thread("PackageUsage_DiskWriter") {
987                    @Override
988                    public void run() {
989                        try {
990                            writeInternal();
991                        } finally {
992                            mBackgroundWriteRunning.set(false);
993                        }
994                    }
995                }.start();
996            }
997        }
998
999        private void writeInternal() {
1000            synchronized (mPackages) {
1001                synchronized (mFileLock) {
1002                    AtomicFile file = getFile();
1003                    FileOutputStream f = null;
1004                    try {
1005                        f = file.startWrite();
1006                        BufferedOutputStream out = new BufferedOutputStream(f);
1007                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1008                        StringBuilder sb = new StringBuilder();
1009                        for (PackageParser.Package pkg : mPackages.values()) {
1010                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1011                                continue;
1012                            }
1013                            sb.setLength(0);
1014                            sb.append(pkg.packageName);
1015                            sb.append(' ');
1016                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1017                            sb.append('\n');
1018                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1019                        }
1020                        out.flush();
1021                        file.finishWrite(f);
1022                    } catch (IOException e) {
1023                        if (f != null) {
1024                            file.failWrite(f);
1025                        }
1026                        Log.e(TAG, "Failed to write package usage times", e);
1027                    }
1028                }
1029            }
1030            mLastWritten.set(SystemClock.elapsedRealtime());
1031        }
1032
1033        void readLP() {
1034            synchronized (mFileLock) {
1035                AtomicFile file = getFile();
1036                BufferedInputStream in = null;
1037                try {
1038                    in = new BufferedInputStream(file.openRead());
1039                    StringBuffer sb = new StringBuffer();
1040                    while (true) {
1041                        String packageName = readToken(in, sb, ' ');
1042                        if (packageName == null) {
1043                            break;
1044                        }
1045                        String timeInMillisString = readToken(in, sb, '\n');
1046                        if (timeInMillisString == null) {
1047                            throw new IOException("Failed to find last usage time for package "
1048                                                  + packageName);
1049                        }
1050                        PackageParser.Package pkg = mPackages.get(packageName);
1051                        if (pkg == null) {
1052                            continue;
1053                        }
1054                        long timeInMillis;
1055                        try {
1056                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1057                        } catch (NumberFormatException e) {
1058                            throw new IOException("Failed to parse " + timeInMillisString
1059                                                  + " as a long.", e);
1060                        }
1061                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1062                    }
1063                } catch (FileNotFoundException expected) {
1064                    mIsHistoricalPackageUsageAvailable = false;
1065                } catch (IOException e) {
1066                    Log.w(TAG, "Failed to read package usage times", e);
1067                } finally {
1068                    IoUtils.closeQuietly(in);
1069                }
1070            }
1071            mLastWritten.set(SystemClock.elapsedRealtime());
1072        }
1073
1074        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1075                throws IOException {
1076            sb.setLength(0);
1077            while (true) {
1078                int ch = in.read();
1079                if (ch == -1) {
1080                    if (sb.length() == 0) {
1081                        return null;
1082                    }
1083                    throw new IOException("Unexpected EOF");
1084                }
1085                if (ch == endOfToken) {
1086                    return sb.toString();
1087                }
1088                sb.append((char)ch);
1089            }
1090        }
1091
1092        private AtomicFile getFile() {
1093            File dataDir = Environment.getDataDirectory();
1094            File systemDir = new File(dataDir, "system");
1095            File fname = new File(systemDir, "package-usage.list");
1096            return new AtomicFile(fname);
1097        }
1098    }
1099
1100    class PackageHandler extends Handler {
1101        private boolean mBound = false;
1102        final ArrayList<HandlerParams> mPendingInstalls =
1103            new ArrayList<HandlerParams>();
1104
1105        private boolean connectToService() {
1106            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1107                    " DefaultContainerService");
1108            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1109            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1111                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1112                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113                mBound = true;
1114                return true;
1115            }
1116            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117            return false;
1118        }
1119
1120        private void disconnectService() {
1121            mContainerService = null;
1122            mBound = false;
1123            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124            mContext.unbindService(mDefContainerConn);
1125            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126        }
1127
1128        PackageHandler(Looper looper) {
1129            super(looper);
1130        }
1131
1132        public void handleMessage(Message msg) {
1133            try {
1134                doHandleMessage(msg);
1135            } finally {
1136                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137            }
1138        }
1139
1140        void doHandleMessage(Message msg) {
1141            switch (msg.what) {
1142                case INIT_COPY: {
1143                    HandlerParams params = (HandlerParams) msg.obj;
1144                    int idx = mPendingInstalls.size();
1145                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1146                    // If a bind was already initiated we dont really
1147                    // need to do anything. The pending install
1148                    // will be processed later on.
1149                    if (!mBound) {
1150                        // If this is the only one pending we might
1151                        // have to bind to the service again.
1152                        if (!connectToService()) {
1153                            Slog.e(TAG, "Failed to bind to media container service");
1154                            params.serviceError();
1155                            return;
1156                        } else {
1157                            // Once we bind to the service, the first
1158                            // pending request will be processed.
1159                            mPendingInstalls.add(idx, params);
1160                        }
1161                    } else {
1162                        mPendingInstalls.add(idx, params);
1163                        // Already bound to the service. Just make
1164                        // sure we trigger off processing the first request.
1165                        if (idx == 0) {
1166                            mHandler.sendEmptyMessage(MCS_BOUND);
1167                        }
1168                    }
1169                    break;
1170                }
1171                case MCS_BOUND: {
1172                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1173                    if (msg.obj != null) {
1174                        mContainerService = (IMediaContainerService) msg.obj;
1175                    }
1176                    if (mContainerService == null) {
1177                        if (!mBound) {
1178                            // Something seriously wrong since we are not bound and we are not
1179                            // waiting for connection. Bail out.
1180                            Slog.e(TAG, "Cannot bind to media container service");
1181                            for (HandlerParams params : mPendingInstalls) {
1182                                // Indicate service bind error
1183                                params.serviceError();
1184                            }
1185                            mPendingInstalls.clear();
1186                        } else {
1187                            Slog.w(TAG, "Waiting to connect to media container service");
1188                        }
1189                    } else if (mPendingInstalls.size() > 0) {
1190                        HandlerParams params = mPendingInstalls.get(0);
1191                        if (params != null) {
1192                            if (params.startCopy()) {
1193                                // We are done...  look for more work or to
1194                                // go idle.
1195                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1196                                        "Checking for more work or unbind...");
1197                                // Delete pending install
1198                                if (mPendingInstalls.size() > 0) {
1199                                    mPendingInstalls.remove(0);
1200                                }
1201                                if (mPendingInstalls.size() == 0) {
1202                                    if (mBound) {
1203                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                                "Posting delayed MCS_UNBIND");
1205                                        removeMessages(MCS_UNBIND);
1206                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1207                                        // Unbind after a little delay, to avoid
1208                                        // continual thrashing.
1209                                        sendMessageDelayed(ubmsg, 10000);
1210                                    }
1211                                } else {
1212                                    // There are more pending requests in queue.
1213                                    // Just post MCS_BOUND message to trigger processing
1214                                    // of next pending install.
1215                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1216                                            "Posting MCS_BOUND for next work");
1217                                    mHandler.sendEmptyMessage(MCS_BOUND);
1218                                }
1219                            }
1220                        }
1221                    } else {
1222                        // Should never happen ideally.
1223                        Slog.w(TAG, "Empty queue");
1224                    }
1225                    break;
1226                }
1227                case MCS_RECONNECT: {
1228                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1229                    if (mPendingInstalls.size() > 0) {
1230                        if (mBound) {
1231                            disconnectService();
1232                        }
1233                        if (!connectToService()) {
1234                            Slog.e(TAG, "Failed to bind to media container service");
1235                            for (HandlerParams params : mPendingInstalls) {
1236                                // Indicate service bind error
1237                                params.serviceError();
1238                            }
1239                            mPendingInstalls.clear();
1240                        }
1241                    }
1242                    break;
1243                }
1244                case MCS_UNBIND: {
1245                    // If there is no actual work left, then time to unbind.
1246                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1247
1248                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1249                        if (mBound) {
1250                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1251
1252                            disconnectService();
1253                        }
1254                    } else if (mPendingInstalls.size() > 0) {
1255                        // There are more pending requests in queue.
1256                        // Just post MCS_BOUND message to trigger processing
1257                        // of next pending install.
1258                        mHandler.sendEmptyMessage(MCS_BOUND);
1259                    }
1260
1261                    break;
1262                }
1263                case MCS_GIVE_UP: {
1264                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1265                    mPendingInstalls.remove(0);
1266                    break;
1267                }
1268                case SEND_PENDING_BROADCAST: {
1269                    String packages[];
1270                    ArrayList<String> components[];
1271                    int size = 0;
1272                    int uids[];
1273                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1274                    synchronized (mPackages) {
1275                        if (mPendingBroadcasts == null) {
1276                            return;
1277                        }
1278                        size = mPendingBroadcasts.size();
1279                        if (size <= 0) {
1280                            // Nothing to be done. Just return
1281                            return;
1282                        }
1283                        packages = new String[size];
1284                        components = new ArrayList[size];
1285                        uids = new int[size];
1286                        int i = 0;  // filling out the above arrays
1287
1288                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1289                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1290                            Iterator<Map.Entry<String, ArrayList<String>>> it
1291                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1292                                            .entrySet().iterator();
1293                            while (it.hasNext() && i < size) {
1294                                Map.Entry<String, ArrayList<String>> ent = it.next();
1295                                packages[i] = ent.getKey();
1296                                components[i] = ent.getValue();
1297                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1298                                uids[i] = (ps != null)
1299                                        ? UserHandle.getUid(packageUserId, ps.appId)
1300                                        : -1;
1301                                i++;
1302                            }
1303                        }
1304                        size = i;
1305                        mPendingBroadcasts.clear();
1306                    }
1307                    // Send broadcasts
1308                    for (int i = 0; i < size; i++) {
1309                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1310                    }
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1312                    break;
1313                }
1314                case START_CLEANING_PACKAGE: {
1315                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1316                    final String packageName = (String)msg.obj;
1317                    final int userId = msg.arg1;
1318                    final boolean andCode = msg.arg2 != 0;
1319                    synchronized (mPackages) {
1320                        if (userId == UserHandle.USER_ALL) {
1321                            int[] users = sUserManager.getUserIds();
1322                            for (int user : users) {
1323                                mSettings.addPackageToCleanLPw(
1324                                        new PackageCleanItem(user, packageName, andCode));
1325                            }
1326                        } else {
1327                            mSettings.addPackageToCleanLPw(
1328                                    new PackageCleanItem(userId, packageName, andCode));
1329                        }
1330                    }
1331                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1332                    startCleaningPackages();
1333                } break;
1334                case POST_INSTALL: {
1335                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1336                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1337                    mRunningInstalls.delete(msg.arg1);
1338                    boolean deleteOld = false;
1339
1340                    if (data != null) {
1341                        InstallArgs args = data.args;
1342                        PackageInstalledInfo res = data.res;
1343
1344                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1345                            final String packageName = res.pkg.applicationInfo.packageName;
1346                            res.removedInfo.sendBroadcast(false, true, false);
1347                            Bundle extras = new Bundle(1);
1348                            extras.putInt(Intent.EXTRA_UID, res.uid);
1349
1350                            // Now that we successfully installed the package, grant runtime
1351                            // permissions if requested before broadcasting the install.
1352                            if ((args.installFlags
1353                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1354                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1355                                        args.installGrantPermissions);
1356                            }
1357
1358                            // Determine the set of users who are adding this
1359                            // package for the first time vs. those who are seeing
1360                            // an update.
1361                            int[] firstUsers;
1362                            int[] updateUsers = new int[0];
1363                            if (res.origUsers == null || res.origUsers.length == 0) {
1364                                firstUsers = res.newUsers;
1365                            } else {
1366                                firstUsers = new int[0];
1367                                for (int i=0; i<res.newUsers.length; i++) {
1368                                    int user = res.newUsers[i];
1369                                    boolean isNew = true;
1370                                    for (int j=0; j<res.origUsers.length; j++) {
1371                                        if (res.origUsers[j] == user) {
1372                                            isNew = false;
1373                                            break;
1374                                        }
1375                                    }
1376                                    if (isNew) {
1377                                        int[] newFirst = new int[firstUsers.length+1];
1378                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1379                                                firstUsers.length);
1380                                        newFirst[firstUsers.length] = user;
1381                                        firstUsers = newFirst;
1382                                    } else {
1383                                        int[] newUpdate = new int[updateUsers.length+1];
1384                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1385                                                updateUsers.length);
1386                                        newUpdate[updateUsers.length] = user;
1387                                        updateUsers = newUpdate;
1388                                    }
1389                                }
1390                            }
1391                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1392                                    packageName, extras, null, null, firstUsers);
1393                            final boolean update = res.removedInfo.removedPackage != null;
1394                            if (update) {
1395                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1396                            }
1397                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1398                                    packageName, extras, null, null, updateUsers);
1399                            if (update) {
1400                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1401                                        packageName, extras, null, null, updateUsers);
1402                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1403                                        null, null, packageName, null, updateUsers);
1404
1405                                // treat asec-hosted packages like removable media on upgrade
1406                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1407                                    if (DEBUG_INSTALL) {
1408                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1409                                                + " is ASEC-hosted -> AVAILABLE");
1410                                    }
1411                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1412                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1413                                    pkgList.add(packageName);
1414                                    sendResourcesChangedBroadcast(true, true,
1415                                            pkgList,uidArray, null);
1416                                }
1417                            }
1418                            if (res.removedInfo.args != null) {
1419                                // Remove the replaced package's older resources safely now
1420                                deleteOld = true;
1421                            }
1422
1423                            // If this app is a browser and it's newly-installed for some
1424                            // users, clear any default-browser state in those users
1425                            if (firstUsers.length > 0) {
1426                                // the app's nature doesn't depend on the user, so we can just
1427                                // check its browser nature in any user and generalize.
1428                                if (packageIsBrowser(packageName, firstUsers[0])) {
1429                                    synchronized (mPackages) {
1430                                        for (int userId : firstUsers) {
1431                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1432                                        }
1433                                    }
1434                                }
1435                            }
1436                            // Log current value of "unknown sources" setting
1437                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1438                                getUnknownSourcesSettings());
1439                        }
1440                        // Force a gc to clear up things
1441                        Runtime.getRuntime().gc();
1442                        // We delete after a gc for applications  on sdcard.
1443                        if (deleteOld) {
1444                            synchronized (mInstallLock) {
1445                                res.removedInfo.args.doPostDeleteLI(true);
1446                            }
1447                        }
1448                        if (args.observer != null) {
1449                            try {
1450                                Bundle extras = extrasForInstallResult(res);
1451                                args.observer.onPackageInstalled(res.name, res.returnCode,
1452                                        res.returnMsg, extras);
1453                            } catch (RemoteException e) {
1454                                Slog.i(TAG, "Observer no longer exists.");
1455                            }
1456                        }
1457                    } else {
1458                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1459                    }
1460                } break;
1461                case UPDATED_MEDIA_STATUS: {
1462                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1463                    boolean reportStatus = msg.arg1 == 1;
1464                    boolean doGc = msg.arg2 == 1;
1465                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1466                    if (doGc) {
1467                        // Force a gc to clear up stale containers.
1468                        Runtime.getRuntime().gc();
1469                    }
1470                    if (msg.obj != null) {
1471                        @SuppressWarnings("unchecked")
1472                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1473                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1474                        // Unload containers
1475                        unloadAllContainers(args);
1476                    }
1477                    if (reportStatus) {
1478                        try {
1479                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1480                            PackageHelper.getMountService().finishMediaUpdate();
1481                        } catch (RemoteException e) {
1482                            Log.e(TAG, "MountService not running?");
1483                        }
1484                    }
1485                } break;
1486                case WRITE_SETTINGS: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    synchronized (mPackages) {
1489                        removeMessages(WRITE_SETTINGS);
1490                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1491                        mSettings.writeLPr();
1492                        mDirtyUsers.clear();
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                } break;
1496                case WRITE_PACKAGE_RESTRICTIONS: {
1497                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498                    synchronized (mPackages) {
1499                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1500                        for (int userId : mDirtyUsers) {
1501                            mSettings.writePackageRestrictionsLPr(userId);
1502                        }
1503                        mDirtyUsers.clear();
1504                    }
1505                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1506                } break;
1507                case CHECK_PENDING_VERIFICATION: {
1508                    final int verificationId = msg.arg1;
1509                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1510
1511                    if ((state != null) && !state.timeoutExtended()) {
1512                        final InstallArgs args = state.getInstallArgs();
1513                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1514
1515                        Slog.i(TAG, "Verification timed out for " + originUri);
1516                        mPendingVerification.remove(verificationId);
1517
1518                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1519
1520                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1521                            Slog.i(TAG, "Continuing with installation of " + originUri);
1522                            state.setVerifierResponse(Binder.getCallingUid(),
1523                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1524                            broadcastPackageVerified(verificationId, originUri,
1525                                    PackageManager.VERIFICATION_ALLOW,
1526                                    state.getInstallArgs().getUser());
1527                            try {
1528                                ret = args.copyApk(mContainerService, true);
1529                            } catch (RemoteException e) {
1530                                Slog.e(TAG, "Could not contact the ContainerService");
1531                            }
1532                        } else {
1533                            broadcastPackageVerified(verificationId, originUri,
1534                                    PackageManager.VERIFICATION_REJECT,
1535                                    state.getInstallArgs().getUser());
1536                        }
1537
1538                        processPendingInstall(args, ret);
1539                        mHandler.sendEmptyMessage(MCS_UNBIND);
1540                    }
1541                    break;
1542                }
1543                case PACKAGE_VERIFIED: {
1544                    final int verificationId = msg.arg1;
1545
1546                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1547                    if (state == null) {
1548                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1549                        break;
1550                    }
1551
1552                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1553
1554                    state.setVerifierResponse(response.callerUid, response.code);
1555
1556                    if (state.isVerificationComplete()) {
1557                        mPendingVerification.remove(verificationId);
1558
1559                        final InstallArgs args = state.getInstallArgs();
1560                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1561
1562                        int ret;
1563                        if (state.isInstallAllowed()) {
1564                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1565                            broadcastPackageVerified(verificationId, originUri,
1566                                    response.code, state.getInstallArgs().getUser());
1567                            try {
1568                                ret = args.copyApk(mContainerService, true);
1569                            } catch (RemoteException e) {
1570                                Slog.e(TAG, "Could not contact the ContainerService");
1571                            }
1572                        } else {
1573                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1574                        }
1575
1576                        processPendingInstall(args, ret);
1577
1578                        mHandler.sendEmptyMessage(MCS_UNBIND);
1579                    }
1580
1581                    break;
1582                }
1583                case START_INTENT_FILTER_VERIFICATIONS: {
1584                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1585                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1586                            params.replacing, params.pkg);
1587                    break;
1588                }
1589                case INTENT_FILTER_VERIFIED: {
1590                    final int verificationId = msg.arg1;
1591
1592                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1593                            verificationId);
1594                    if (state == null) {
1595                        Slog.w(TAG, "Invalid IntentFilter verification token "
1596                                + verificationId + " received");
1597                        break;
1598                    }
1599
1600                    final int userId = state.getUserId();
1601
1602                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1603                            "Processing IntentFilter verification with token:"
1604                            + verificationId + " and userId:" + userId);
1605
1606                    final IntentFilterVerificationResponse response =
1607                            (IntentFilterVerificationResponse) msg.obj;
1608
1609                    state.setVerifierResponse(response.callerUid, response.code);
1610
1611                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                            "IntentFilter verification with token:" + verificationId
1613                            + " and userId:" + userId
1614                            + " is settings verifier response with response code:"
1615                            + response.code);
1616
1617                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1618                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1619                                + response.getFailedDomainsString());
1620                    }
1621
1622                    if (state.isVerificationComplete()) {
1623                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1624                    } else {
1625                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1626                                "IntentFilter verification with token:" + verificationId
1627                                + " was not said to be complete");
1628                    }
1629
1630                    break;
1631                }
1632            }
1633        }
1634    }
1635
1636    private StorageEventListener mStorageListener = new StorageEventListener() {
1637        @Override
1638        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1639            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1640                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1641                    final String volumeUuid = vol.getFsUuid();
1642
1643                    // Clean up any users or apps that were removed or recreated
1644                    // while this volume was missing
1645                    reconcileUsers(volumeUuid);
1646                    reconcileApps(volumeUuid);
1647
1648                    // Clean up any install sessions that expired or were
1649                    // cancelled while this volume was missing
1650                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1651
1652                    loadPrivatePackages(vol);
1653
1654                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1655                    unloadPrivatePackages(vol);
1656                }
1657            }
1658
1659            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1660                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1661                    updateExternalMediaStatus(true, false);
1662                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1663                    updateExternalMediaStatus(false, false);
1664                }
1665            }
1666        }
1667
1668        @Override
1669        public void onVolumeForgotten(String fsUuid) {
1670            if (TextUtils.isEmpty(fsUuid)) {
1671                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1672                return;
1673            }
1674
1675            // Remove any apps installed on the forgotten volume
1676            synchronized (mPackages) {
1677                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1678                for (PackageSetting ps : packages) {
1679                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1680                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1681                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1682                }
1683
1684                mSettings.onVolumeForgotten(fsUuid);
1685                mSettings.writeLPr();
1686            }
1687        }
1688    };
1689
1690    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1691            String[] grantedPermissions) {
1692        if (userId >= UserHandle.USER_OWNER) {
1693            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1694        } else if (userId == UserHandle.USER_ALL) {
1695            final int[] userIds;
1696            synchronized (mPackages) {
1697                userIds = UserManagerService.getInstance().getUserIds();
1698            }
1699            for (int someUserId : userIds) {
1700                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1701            }
1702        }
1703
1704        // We could have touched GID membership, so flush out packages.list
1705        synchronized (mPackages) {
1706            mSettings.writePackageListLPr();
1707        }
1708    }
1709
1710    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1711            String[] grantedPermissions) {
1712        SettingBase sb = (SettingBase) pkg.mExtras;
1713        if (sb == null) {
1714            return;
1715        }
1716
1717        PermissionsState permissionsState = sb.getPermissionsState();
1718
1719        for (String permission : pkg.requestedPermissions) {
1720            BasePermission bp = mSettings.mPermissions.get(permission);
1721            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1722                    || ArrayUtils.contains(grantedPermissions, permission))) {
1723                permissionsState.grantRuntimePermission(bp, userId);
1724            }
1725        }
1726    }
1727
1728    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1729        Bundle extras = null;
1730        switch (res.returnCode) {
1731            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1732                extras = new Bundle();
1733                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1734                        res.origPermission);
1735                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1736                        res.origPackage);
1737                break;
1738            }
1739            case PackageManager.INSTALL_SUCCEEDED: {
1740                extras = new Bundle();
1741                extras.putBoolean(Intent.EXTRA_REPLACING,
1742                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1743                break;
1744            }
1745        }
1746        return extras;
1747    }
1748
1749    void scheduleWriteSettingsLocked() {
1750        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1751            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1752        }
1753    }
1754
1755    void scheduleWritePackageRestrictionsLocked(int userId) {
1756        if (!sUserManager.exists(userId)) return;
1757        mDirtyUsers.add(userId);
1758        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1759            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1760        }
1761    }
1762
1763    public static PackageManagerService main(Context context, Installer installer,
1764            boolean factoryTest, boolean onlyCore) {
1765        PackageManagerService m = new PackageManagerService(context, installer,
1766                factoryTest, onlyCore);
1767        ServiceManager.addService("package", m);
1768        return m;
1769    }
1770
1771    static String[] splitString(String str, char sep) {
1772        int count = 1;
1773        int i = 0;
1774        while ((i=str.indexOf(sep, i)) >= 0) {
1775            count++;
1776            i++;
1777        }
1778
1779        String[] res = new String[count];
1780        i=0;
1781        count = 0;
1782        int lastI=0;
1783        while ((i=str.indexOf(sep, i)) >= 0) {
1784            res[count] = str.substring(lastI, i);
1785            count++;
1786            i++;
1787            lastI = i;
1788        }
1789        res[count] = str.substring(lastI, str.length());
1790        return res;
1791    }
1792
1793    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1794        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1795                Context.DISPLAY_SERVICE);
1796        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1797    }
1798
1799    public PackageManagerService(Context context, Installer installer,
1800            boolean factoryTest, boolean onlyCore) {
1801        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1802                SystemClock.uptimeMillis());
1803
1804        if (mSdkVersion <= 0) {
1805            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1806        }
1807
1808        mContext = context;
1809        mFactoryTest = factoryTest;
1810        mOnlyCore = onlyCore;
1811        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1812        mMetrics = new DisplayMetrics();
1813        mSettings = new Settings(mPackages);
1814        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1815                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1816        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1817                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1818        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1819                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1820        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1821                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1822        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1823                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1824        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1825                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1826
1827        // TODO: add a property to control this?
1828        long dexOptLRUThresholdInMinutes;
1829        if (mLazyDexOpt) {
1830            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1831        } else {
1832            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1833        }
1834        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1835
1836        String separateProcesses = SystemProperties.get("debug.separate_processes");
1837        if (separateProcesses != null && separateProcesses.length() > 0) {
1838            if ("*".equals(separateProcesses)) {
1839                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1840                mSeparateProcesses = null;
1841                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1842            } else {
1843                mDefParseFlags = 0;
1844                mSeparateProcesses = separateProcesses.split(",");
1845                Slog.w(TAG, "Running with debug.separate_processes: "
1846                        + separateProcesses);
1847            }
1848        } else {
1849            mDefParseFlags = 0;
1850            mSeparateProcesses = null;
1851        }
1852
1853        mInstaller = installer;
1854        mPackageDexOptimizer = new PackageDexOptimizer(this);
1855        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1856
1857        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1858                FgThread.get().getLooper());
1859
1860        getDefaultDisplayMetrics(context, mMetrics);
1861
1862        SystemConfig systemConfig = SystemConfig.getInstance();
1863        mGlobalGids = systemConfig.getGlobalGids();
1864        mSystemPermissions = systemConfig.getSystemPermissions();
1865        mAvailableFeatures = systemConfig.getAvailableFeatures();
1866
1867        synchronized (mInstallLock) {
1868        // writer
1869        synchronized (mPackages) {
1870            mHandlerThread = new ServiceThread(TAG,
1871                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1872            mHandlerThread.start();
1873            mHandler = new PackageHandler(mHandlerThread.getLooper());
1874            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1875
1876            File dataDir = Environment.getDataDirectory();
1877            mAppDataDir = new File(dataDir, "data");
1878            mAppInstallDir = new File(dataDir, "app");
1879            mAppLib32InstallDir = new File(dataDir, "app-lib");
1880            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1881            mUserAppDataDir = new File(dataDir, "user");
1882            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1883
1884            sUserManager = new UserManagerService(context, this,
1885                    mInstallLock, mPackages);
1886
1887            // Propagate permission configuration in to package manager.
1888            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1889                    = systemConfig.getPermissions();
1890            for (int i=0; i<permConfig.size(); i++) {
1891                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1892                BasePermission bp = mSettings.mPermissions.get(perm.name);
1893                if (bp == null) {
1894                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1895                    mSettings.mPermissions.put(perm.name, bp);
1896                }
1897                if (perm.gids != null) {
1898                    bp.setGids(perm.gids, perm.perUser);
1899                }
1900            }
1901
1902            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1903            for (int i=0; i<libConfig.size(); i++) {
1904                mSharedLibraries.put(libConfig.keyAt(i),
1905                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1906            }
1907
1908            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1909
1910            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1911                    mSdkVersion, mOnlyCore);
1912
1913            String customResolverActivity = Resources.getSystem().getString(
1914                    R.string.config_customResolverActivity);
1915            if (TextUtils.isEmpty(customResolverActivity)) {
1916                customResolverActivity = null;
1917            } else {
1918                mCustomResolverComponentName = ComponentName.unflattenFromString(
1919                        customResolverActivity);
1920            }
1921
1922            long startTime = SystemClock.uptimeMillis();
1923
1924            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1925                    startTime);
1926
1927            // Set flag to monitor and not change apk file paths when
1928            // scanning install directories.
1929            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1930
1931            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1932
1933            /**
1934             * Add everything in the in the boot class path to the
1935             * list of process files because dexopt will have been run
1936             * if necessary during zygote startup.
1937             */
1938            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1939            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1940
1941            if (bootClassPath != null) {
1942                String[] bootClassPathElements = splitString(bootClassPath, ':');
1943                for (String element : bootClassPathElements) {
1944                    alreadyDexOpted.add(element);
1945                }
1946            } else {
1947                Slog.w(TAG, "No BOOTCLASSPATH found!");
1948            }
1949
1950            if (systemServerClassPath != null) {
1951                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1952                for (String element : systemServerClassPathElements) {
1953                    alreadyDexOpted.add(element);
1954                }
1955            } else {
1956                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1957            }
1958
1959            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1960            final String[] dexCodeInstructionSets =
1961                    getDexCodeInstructionSets(
1962                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1963
1964            /**
1965             * Ensure all external libraries have had dexopt run on them.
1966             */
1967            if (mSharedLibraries.size() > 0) {
1968                // NOTE: For now, we're compiling these system "shared libraries"
1969                // (and framework jars) into all available architectures. It's possible
1970                // to compile them only when we come across an app that uses them (there's
1971                // already logic for that in scanPackageLI) but that adds some complexity.
1972                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1973                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1974                        final String lib = libEntry.path;
1975                        if (lib == null) {
1976                            continue;
1977                        }
1978
1979                        try {
1980                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1981                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1982                                alreadyDexOpted.add(lib);
1983                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
1984                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
1985                            }
1986                        } catch (FileNotFoundException e) {
1987                            Slog.w(TAG, "Library not found: " + lib);
1988                        } catch (IOException e) {
1989                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1990                                    + e.getMessage());
1991                        }
1992                    }
1993                }
1994            }
1995
1996            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1997
1998            // Gross hack for now: we know this file doesn't contain any
1999            // code, so don't dexopt it to avoid the resulting log spew.
2000            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2001
2002            // Gross hack for now: we know this file is only part of
2003            // the boot class path for art, so don't dexopt it to
2004            // avoid the resulting log spew.
2005            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2006
2007            /**
2008             * There are a number of commands implemented in Java, which
2009             * we currently need to do the dexopt on so that they can be
2010             * run from a non-root shell.
2011             */
2012            String[] frameworkFiles = frameworkDir.list();
2013            if (frameworkFiles != null) {
2014                // TODO: We could compile these only for the most preferred ABI. We should
2015                // first double check that the dex files for these commands are not referenced
2016                // by other system apps.
2017                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2018                    for (int i=0; i<frameworkFiles.length; i++) {
2019                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2020                        String path = libPath.getPath();
2021                        // Skip the file if we already did it.
2022                        if (alreadyDexOpted.contains(path)) {
2023                            continue;
2024                        }
2025                        // Skip the file if it is not a type we want to dexopt.
2026                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2027                            continue;
2028                        }
2029                        try {
2030                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2031                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2032                                mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet,
2033                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2034                            }
2035                        } catch (FileNotFoundException e) {
2036                            Slog.w(TAG, "Jar not found: " + path);
2037                        } catch (IOException e) {
2038                            Slog.w(TAG, "Exception reading jar: " + path, e);
2039                        }
2040                    }
2041                }
2042            }
2043
2044            final VersionInfo ver = mSettings.getInternalVersion();
2045            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2046            // when upgrading from pre-M, promote system app permissions from install to runtime
2047            mPromoteSystemApps =
2048                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2049
2050            // save off the names of pre-existing system packages prior to scanning; we don't
2051            // want to automatically grant runtime permissions for new system apps
2052            if (mPromoteSystemApps) {
2053                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2054                while (pkgSettingIter.hasNext()) {
2055                    PackageSetting ps = pkgSettingIter.next();
2056                    if (isSystemApp(ps)) {
2057                        mExistingSystemPackages.add(ps.name);
2058                    }
2059                }
2060            }
2061
2062            // Collect vendor overlay packages.
2063            // (Do this before scanning any apps.)
2064            // For security and version matching reason, only consider
2065            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2066            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2067            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2068                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2069
2070            // Find base frameworks (resource packages without code).
2071            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2072                    | PackageParser.PARSE_IS_SYSTEM_DIR
2073                    | PackageParser.PARSE_IS_PRIVILEGED,
2074                    scanFlags | SCAN_NO_DEX, 0);
2075
2076            // Collected privileged system packages.
2077            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2078            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2079                    | PackageParser.PARSE_IS_SYSTEM_DIR
2080                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2081
2082            // Collect ordinary system packages.
2083            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2084            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2085                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2086
2087            // Collect all vendor packages.
2088            File vendorAppDir = new File("/vendor/app");
2089            try {
2090                vendorAppDir = vendorAppDir.getCanonicalFile();
2091            } catch (IOException e) {
2092                // failed to look up canonical path, continue with original one
2093            }
2094            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2095                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2096
2097            // Collect all OEM packages.
2098            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2099            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2100                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2101
2102            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2103            mInstaller.moveFiles();
2104
2105            // Prune any system packages that no longer exist.
2106            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2107            if (!mOnlyCore) {
2108                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2109                while (psit.hasNext()) {
2110                    PackageSetting ps = psit.next();
2111
2112                    /*
2113                     * If this is not a system app, it can't be a
2114                     * disable system app.
2115                     */
2116                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2117                        continue;
2118                    }
2119
2120                    /*
2121                     * If the package is scanned, it's not erased.
2122                     */
2123                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2124                    if (scannedPkg != null) {
2125                        /*
2126                         * If the system app is both scanned and in the
2127                         * disabled packages list, then it must have been
2128                         * added via OTA. Remove it from the currently
2129                         * scanned package so the previously user-installed
2130                         * application can be scanned.
2131                         */
2132                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2133                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2134                                    + ps.name + "; removing system app.  Last known codePath="
2135                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2136                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2137                                    + scannedPkg.mVersionCode);
2138                            removePackageLI(ps, true);
2139                            mExpectingBetter.put(ps.name, ps.codePath);
2140                        }
2141
2142                        continue;
2143                    }
2144
2145                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2146                        psit.remove();
2147                        logCriticalInfo(Log.WARN, "System package " + ps.name
2148                                + " no longer exists; wiping its data");
2149                        removeDataDirsLI(null, ps.name);
2150                    } else {
2151                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2152                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2153                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2154                        }
2155                    }
2156                }
2157            }
2158
2159            //look for any incomplete package installations
2160            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2161            //clean up list
2162            for(int i = 0; i < deletePkgsList.size(); i++) {
2163                //clean up here
2164                cleanupInstallFailedPackage(deletePkgsList.get(i));
2165            }
2166            //delete tmp files
2167            deleteTempPackageFiles();
2168
2169            // Remove any shared userIDs that have no associated packages
2170            mSettings.pruneSharedUsersLPw();
2171
2172            if (!mOnlyCore) {
2173                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2174                        SystemClock.uptimeMillis());
2175                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2176
2177                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2178                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2179
2180                /**
2181                 * Remove disable package settings for any updated system
2182                 * apps that were removed via an OTA. If they're not a
2183                 * previously-updated app, remove them completely.
2184                 * Otherwise, just revoke their system-level permissions.
2185                 */
2186                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2187                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2188                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2189
2190                    String msg;
2191                    if (deletedPkg == null) {
2192                        msg = "Updated system package " + deletedAppName
2193                                + " no longer exists; wiping its data";
2194                        removeDataDirsLI(null, deletedAppName);
2195                    } else {
2196                        msg = "Updated system app + " + deletedAppName
2197                                + " no longer present; removing system privileges for "
2198                                + deletedAppName;
2199
2200                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2201
2202                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2203                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2204                    }
2205                    logCriticalInfo(Log.WARN, msg);
2206                }
2207
2208                /**
2209                 * Make sure all system apps that we expected to appear on
2210                 * the userdata partition actually showed up. If they never
2211                 * appeared, crawl back and revive the system version.
2212                 */
2213                for (int i = 0; i < mExpectingBetter.size(); i++) {
2214                    final String packageName = mExpectingBetter.keyAt(i);
2215                    if (!mPackages.containsKey(packageName)) {
2216                        final File scanFile = mExpectingBetter.valueAt(i);
2217
2218                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2219                                + " but never showed up; reverting to system");
2220
2221                        final int reparseFlags;
2222                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2223                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2224                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2225                                    | PackageParser.PARSE_IS_PRIVILEGED;
2226                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2227                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2228                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2229                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2230                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2231                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2232                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2233                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2234                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2235                        } else {
2236                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2237                            continue;
2238                        }
2239
2240                        mSettings.enableSystemPackageLPw(packageName);
2241
2242                        try {
2243                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2244                        } catch (PackageManagerException e) {
2245                            Slog.e(TAG, "Failed to parse original system package: "
2246                                    + e.getMessage());
2247                        }
2248                    }
2249                }
2250            }
2251            mExpectingBetter.clear();
2252
2253            // Now that we know all of the shared libraries, update all clients to have
2254            // the correct library paths.
2255            updateAllSharedLibrariesLPw();
2256
2257            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2258                // NOTE: We ignore potential failures here during a system scan (like
2259                // the rest of the commands above) because there's precious little we
2260                // can do about it. A settings error is reported, though.
2261                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2262                        false /* force dexopt */, false /* defer dexopt */,
2263                        false /* boot complete */);
2264            }
2265
2266            // Now that we know all the packages we are keeping,
2267            // read and update their last usage times.
2268            mPackageUsage.readLP();
2269
2270            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2271                    SystemClock.uptimeMillis());
2272            Slog.i(TAG, "Time to scan packages: "
2273                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2274                    + " seconds");
2275
2276            // If the platform SDK has changed since the last time we booted,
2277            // we need to re-grant app permission to catch any new ones that
2278            // appear.  This is really a hack, and means that apps can in some
2279            // cases get permissions that the user didn't initially explicitly
2280            // allow...  it would be nice to have some better way to handle
2281            // this situation.
2282            int updateFlags = UPDATE_PERMISSIONS_ALL;
2283            if (ver.sdkVersion != mSdkVersion) {
2284                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2285                        + mSdkVersion + "; regranting permissions for internal storage");
2286                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2287            }
2288            updatePermissionsLPw(null, null, updateFlags);
2289            ver.sdkVersion = mSdkVersion;
2290
2291            // If this is the first boot or an update from pre-M, and it is a normal
2292            // boot, then we need to initialize the default preferred apps across
2293            // all defined users.
2294            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2295                for (UserInfo user : sUserManager.getUsers(true)) {
2296                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2297                    applyFactoryDefaultBrowserLPw(user.id);
2298                    primeDomainVerificationsLPw(user.id);
2299                }
2300            }
2301
2302            // If this is first boot after an OTA, and a normal boot, then
2303            // we need to clear code cache directories.
2304            if (mIsUpgrade && !onlyCore) {
2305                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2306                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2307                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2308                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2309                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2310                    }
2311                }
2312                ver.fingerprint = Build.FINGERPRINT;
2313            }
2314
2315            checkDefaultBrowser();
2316
2317            // clear only after permissions and other defaults have been updated
2318            mExistingSystemPackages.clear();
2319            mPromoteSystemApps = false;
2320
2321            // All the changes are done during package scanning.
2322            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2323
2324            // can downgrade to reader
2325            mSettings.writeLPr();
2326
2327            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2328                    SystemClock.uptimeMillis());
2329
2330            mRequiredVerifierPackage = getRequiredVerifierLPr();
2331            mRequiredInstallerPackage = getRequiredInstallerLPr();
2332
2333            mInstallerService = new PackageInstallerService(context, this);
2334
2335            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2336            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2337                    mIntentFilterVerifierComponent);
2338
2339        } // synchronized (mPackages)
2340        } // synchronized (mInstallLock)
2341
2342        // Now after opening every single application zip, make sure they
2343        // are all flushed.  Not really needed, but keeps things nice and
2344        // tidy.
2345        Runtime.getRuntime().gc();
2346
2347        // Expose private service for system components to use.
2348        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2349    }
2350
2351    @Override
2352    public boolean isFirstBoot() {
2353        return !mRestoredSettings;
2354    }
2355
2356    @Override
2357    public boolean isOnlyCoreApps() {
2358        return mOnlyCore;
2359    }
2360
2361    @Override
2362    public boolean isUpgrade() {
2363        return mIsUpgrade;
2364    }
2365
2366    private String getRequiredVerifierLPr() {
2367        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2368        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2369                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2370
2371        String requiredVerifier = null;
2372
2373        final int N = receivers.size();
2374        for (int i = 0; i < N; i++) {
2375            final ResolveInfo info = receivers.get(i);
2376
2377            if (info.activityInfo == null) {
2378                continue;
2379            }
2380
2381            final String packageName = info.activityInfo.packageName;
2382
2383            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2384                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2385                continue;
2386            }
2387
2388            if (requiredVerifier != null) {
2389                throw new RuntimeException("There can be only one required verifier");
2390            }
2391
2392            requiredVerifier = packageName;
2393        }
2394
2395        return requiredVerifier;
2396    }
2397
2398    private String getRequiredInstallerLPr() {
2399        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2400        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2401        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2402
2403        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2404                PACKAGE_MIME_TYPE, 0, 0);
2405
2406        String requiredInstaller = null;
2407
2408        final int N = installers.size();
2409        for (int i = 0; i < N; i++) {
2410            final ResolveInfo info = installers.get(i);
2411            final String packageName = info.activityInfo.packageName;
2412
2413            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2414                continue;
2415            }
2416
2417            if (requiredInstaller != null) {
2418                throw new RuntimeException("There must be one required installer");
2419            }
2420
2421            requiredInstaller = packageName;
2422        }
2423
2424        if (requiredInstaller == null) {
2425            throw new RuntimeException("There must be one required installer");
2426        }
2427
2428        return requiredInstaller;
2429    }
2430
2431    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2432        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2433        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2434                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2435
2436        ComponentName verifierComponentName = null;
2437
2438        int priority = -1000;
2439        final int N = receivers.size();
2440        for (int i = 0; i < N; i++) {
2441            final ResolveInfo info = receivers.get(i);
2442
2443            if (info.activityInfo == null) {
2444                continue;
2445            }
2446
2447            final String packageName = info.activityInfo.packageName;
2448
2449            final PackageSetting ps = mSettings.mPackages.get(packageName);
2450            if (ps == null) {
2451                continue;
2452            }
2453
2454            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2455                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2456                continue;
2457            }
2458
2459            // Select the IntentFilterVerifier with the highest priority
2460            if (priority < info.priority) {
2461                priority = info.priority;
2462                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2463                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2464                        + verifierComponentName + " with priority: " + info.priority);
2465            }
2466        }
2467
2468        return verifierComponentName;
2469    }
2470
2471    private void primeDomainVerificationsLPw(int userId) {
2472        if (DEBUG_DOMAIN_VERIFICATION) {
2473            Slog.d(TAG, "Priming domain verifications in user " + userId);
2474        }
2475
2476        SystemConfig systemConfig = SystemConfig.getInstance();
2477        ArraySet<String> packages = systemConfig.getLinkedApps();
2478        ArraySet<String> domains = new ArraySet<String>();
2479
2480        for (String packageName : packages) {
2481            PackageParser.Package pkg = mPackages.get(packageName);
2482            if (pkg != null) {
2483                if (!pkg.isSystemApp()) {
2484                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2485                    continue;
2486                }
2487
2488                domains.clear();
2489                for (PackageParser.Activity a : pkg.activities) {
2490                    for (ActivityIntentInfo filter : a.intents) {
2491                        if (hasValidDomains(filter)) {
2492                            domains.addAll(filter.getHostsList());
2493                        }
2494                    }
2495                }
2496
2497                if (domains.size() > 0) {
2498                    if (DEBUG_DOMAIN_VERIFICATION) {
2499                        Slog.v(TAG, "      + " + packageName);
2500                    }
2501                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2502                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2503                    // and then 'always' in the per-user state actually used for intent resolution.
2504                    final IntentFilterVerificationInfo ivi;
2505                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2506                            new ArrayList<String>(domains));
2507                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2508                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2509                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2510                } else {
2511                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2512                            + "' does not handle web links");
2513                }
2514            } else {
2515                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2516            }
2517        }
2518
2519        scheduleWritePackageRestrictionsLocked(userId);
2520        scheduleWriteSettingsLocked();
2521    }
2522
2523    private void applyFactoryDefaultBrowserLPw(int userId) {
2524        // The default browser app's package name is stored in a string resource,
2525        // with a product-specific overlay used for vendor customization.
2526        String browserPkg = mContext.getResources().getString(
2527                com.android.internal.R.string.default_browser);
2528        if (!TextUtils.isEmpty(browserPkg)) {
2529            // non-empty string => required to be a known package
2530            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2531            if (ps == null) {
2532                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2533                browserPkg = null;
2534            } else {
2535                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2536            }
2537        }
2538
2539        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2540        // default.  If there's more than one, just leave everything alone.
2541        if (browserPkg == null) {
2542            calculateDefaultBrowserLPw(userId);
2543        }
2544    }
2545
2546    private void calculateDefaultBrowserLPw(int userId) {
2547        List<String> allBrowsers = resolveAllBrowserApps(userId);
2548        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2549        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2550    }
2551
2552    private List<String> resolveAllBrowserApps(int userId) {
2553        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2554        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2555                PackageManager.MATCH_ALL, userId);
2556
2557        final int count = list.size();
2558        List<String> result = new ArrayList<String>(count);
2559        for (int i=0; i<count; i++) {
2560            ResolveInfo info = list.get(i);
2561            if (info.activityInfo == null
2562                    || !info.handleAllWebDataURI
2563                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2564                    || result.contains(info.activityInfo.packageName)) {
2565                continue;
2566            }
2567            result.add(info.activityInfo.packageName);
2568        }
2569
2570        return result;
2571    }
2572
2573    private boolean packageIsBrowser(String packageName, int userId) {
2574        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2575                PackageManager.MATCH_ALL, userId);
2576        final int N = list.size();
2577        for (int i = 0; i < N; i++) {
2578            ResolveInfo info = list.get(i);
2579            if (packageName.equals(info.activityInfo.packageName)) {
2580                return true;
2581            }
2582        }
2583        return false;
2584    }
2585
2586    private void checkDefaultBrowser() {
2587        final int myUserId = UserHandle.myUserId();
2588        final String packageName = getDefaultBrowserPackageName(myUserId);
2589        if (packageName != null) {
2590            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2591            if (info == null) {
2592                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2593                synchronized (mPackages) {
2594                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2595                }
2596            }
2597        }
2598    }
2599
2600    @Override
2601    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2602            throws RemoteException {
2603        try {
2604            return super.onTransact(code, data, reply, flags);
2605        } catch (RuntimeException e) {
2606            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2607                Slog.wtf(TAG, "Package Manager Crash", e);
2608            }
2609            throw e;
2610        }
2611    }
2612
2613    void cleanupInstallFailedPackage(PackageSetting ps) {
2614        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2615
2616        removeDataDirsLI(ps.volumeUuid, ps.name);
2617        if (ps.codePath != null) {
2618            if (ps.codePath.isDirectory()) {
2619                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2620            } else {
2621                ps.codePath.delete();
2622            }
2623        }
2624        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2625            if (ps.resourcePath.isDirectory()) {
2626                FileUtils.deleteContents(ps.resourcePath);
2627            }
2628            ps.resourcePath.delete();
2629        }
2630        mSettings.removePackageLPw(ps.name);
2631    }
2632
2633    static int[] appendInts(int[] cur, int[] add) {
2634        if (add == null) return cur;
2635        if (cur == null) return add;
2636        final int N = add.length;
2637        for (int i=0; i<N; i++) {
2638            cur = appendInt(cur, add[i]);
2639        }
2640        return cur;
2641    }
2642
2643    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2644        if (!sUserManager.exists(userId)) return null;
2645        final PackageSetting ps = (PackageSetting) p.mExtras;
2646        if (ps == null) {
2647            return null;
2648        }
2649
2650        final PermissionsState permissionsState = ps.getPermissionsState();
2651
2652        final int[] gids = permissionsState.computeGids(userId);
2653        final Set<String> permissions = permissionsState.getPermissions(userId);
2654        final PackageUserState state = ps.readUserState(userId);
2655
2656        return PackageParser.generatePackageInfo(p, gids, flags,
2657                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2658    }
2659
2660    @Override
2661    public boolean isPackageFrozen(String packageName) {
2662        synchronized (mPackages) {
2663            final PackageSetting ps = mSettings.mPackages.get(packageName);
2664            if (ps != null) {
2665                return ps.frozen;
2666            }
2667        }
2668        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2669        return true;
2670    }
2671
2672    @Override
2673    public boolean isPackageAvailable(String packageName, int userId) {
2674        if (!sUserManager.exists(userId)) return false;
2675        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2676        synchronized (mPackages) {
2677            PackageParser.Package p = mPackages.get(packageName);
2678            if (p != null) {
2679                final PackageSetting ps = (PackageSetting) p.mExtras;
2680                if (ps != null) {
2681                    final PackageUserState state = ps.readUserState(userId);
2682                    if (state != null) {
2683                        return PackageParser.isAvailable(state);
2684                    }
2685                }
2686            }
2687        }
2688        return false;
2689    }
2690
2691    @Override
2692    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2693        if (!sUserManager.exists(userId)) return null;
2694        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2695        // reader
2696        synchronized (mPackages) {
2697            PackageParser.Package p = mPackages.get(packageName);
2698            if (DEBUG_PACKAGE_INFO)
2699                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2700            if (p != null) {
2701                return generatePackageInfo(p, flags, userId);
2702            }
2703            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2704                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2705            }
2706        }
2707        return null;
2708    }
2709
2710    @Override
2711    public String[] currentToCanonicalPackageNames(String[] names) {
2712        String[] out = new String[names.length];
2713        // reader
2714        synchronized (mPackages) {
2715            for (int i=names.length-1; i>=0; i--) {
2716                PackageSetting ps = mSettings.mPackages.get(names[i]);
2717                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2718            }
2719        }
2720        return out;
2721    }
2722
2723    @Override
2724    public String[] canonicalToCurrentPackageNames(String[] names) {
2725        String[] out = new String[names.length];
2726        // reader
2727        synchronized (mPackages) {
2728            for (int i=names.length-1; i>=0; i--) {
2729                String cur = mSettings.mRenamedPackages.get(names[i]);
2730                out[i] = cur != null ? cur : names[i];
2731            }
2732        }
2733        return out;
2734    }
2735
2736    @Override
2737    public int getPackageUid(String packageName, int userId) {
2738        if (!sUserManager.exists(userId)) return -1;
2739        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2740
2741        // reader
2742        synchronized (mPackages) {
2743            PackageParser.Package p = mPackages.get(packageName);
2744            if(p != null) {
2745                return UserHandle.getUid(userId, p.applicationInfo.uid);
2746            }
2747            PackageSetting ps = mSettings.mPackages.get(packageName);
2748            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2749                return -1;
2750            }
2751            p = ps.pkg;
2752            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2753        }
2754    }
2755
2756    @Override
2757    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2758        if (!sUserManager.exists(userId)) {
2759            return null;
2760        }
2761
2762        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2763                "getPackageGids");
2764
2765        // reader
2766        synchronized (mPackages) {
2767            PackageParser.Package p = mPackages.get(packageName);
2768            if (DEBUG_PACKAGE_INFO) {
2769                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2770            }
2771            if (p != null) {
2772                PackageSetting ps = (PackageSetting) p.mExtras;
2773                return ps.getPermissionsState().computeGids(userId);
2774            }
2775        }
2776
2777        return null;
2778    }
2779
2780    static PermissionInfo generatePermissionInfo(
2781            BasePermission bp, int flags) {
2782        if (bp.perm != null) {
2783            return PackageParser.generatePermissionInfo(bp.perm, flags);
2784        }
2785        PermissionInfo pi = new PermissionInfo();
2786        pi.name = bp.name;
2787        pi.packageName = bp.sourcePackage;
2788        pi.nonLocalizedLabel = bp.name;
2789        pi.protectionLevel = bp.protectionLevel;
2790        return pi;
2791    }
2792
2793    @Override
2794    public PermissionInfo getPermissionInfo(String name, int flags) {
2795        // reader
2796        synchronized (mPackages) {
2797            final BasePermission p = mSettings.mPermissions.get(name);
2798            if (p != null) {
2799                return generatePermissionInfo(p, flags);
2800            }
2801            return null;
2802        }
2803    }
2804
2805    @Override
2806    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2807        // reader
2808        synchronized (mPackages) {
2809            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2810            for (BasePermission p : mSettings.mPermissions.values()) {
2811                if (group == null) {
2812                    if (p.perm == null || p.perm.info.group == null) {
2813                        out.add(generatePermissionInfo(p, flags));
2814                    }
2815                } else {
2816                    if (p.perm != null && group.equals(p.perm.info.group)) {
2817                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2818                    }
2819                }
2820            }
2821
2822            if (out.size() > 0) {
2823                return out;
2824            }
2825            return mPermissionGroups.containsKey(group) ? out : null;
2826        }
2827    }
2828
2829    @Override
2830    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2831        // reader
2832        synchronized (mPackages) {
2833            return PackageParser.generatePermissionGroupInfo(
2834                    mPermissionGroups.get(name), flags);
2835        }
2836    }
2837
2838    @Override
2839    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2840        // reader
2841        synchronized (mPackages) {
2842            final int N = mPermissionGroups.size();
2843            ArrayList<PermissionGroupInfo> out
2844                    = new ArrayList<PermissionGroupInfo>(N);
2845            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2846                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2847            }
2848            return out;
2849        }
2850    }
2851
2852    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2853            int userId) {
2854        if (!sUserManager.exists(userId)) return null;
2855        PackageSetting ps = mSettings.mPackages.get(packageName);
2856        if (ps != null) {
2857            if (ps.pkg == null) {
2858                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2859                        flags, userId);
2860                if (pInfo != null) {
2861                    return pInfo.applicationInfo;
2862                }
2863                return null;
2864            }
2865            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2866                    ps.readUserState(userId), userId);
2867        }
2868        return null;
2869    }
2870
2871    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2872            int userId) {
2873        if (!sUserManager.exists(userId)) return null;
2874        PackageSetting ps = mSettings.mPackages.get(packageName);
2875        if (ps != null) {
2876            PackageParser.Package pkg = ps.pkg;
2877            if (pkg == null) {
2878                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2879                    return null;
2880                }
2881                // Only data remains, so we aren't worried about code paths
2882                pkg = new PackageParser.Package(packageName);
2883                pkg.applicationInfo.packageName = packageName;
2884                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2885                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2886                pkg.applicationInfo.dataDir = Environment
2887                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2888                        .getAbsolutePath();
2889                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2890                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2891            }
2892            return generatePackageInfo(pkg, flags, userId);
2893        }
2894        return null;
2895    }
2896
2897    @Override
2898    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2899        if (!sUserManager.exists(userId)) return null;
2900        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2901        // writer
2902        synchronized (mPackages) {
2903            PackageParser.Package p = mPackages.get(packageName);
2904            if (DEBUG_PACKAGE_INFO) Log.v(
2905                    TAG, "getApplicationInfo " + packageName
2906                    + ": " + p);
2907            if (p != null) {
2908                PackageSetting ps = mSettings.mPackages.get(packageName);
2909                if (ps == null) return null;
2910                // Note: isEnabledLP() does not apply here - always return info
2911                return PackageParser.generateApplicationInfo(
2912                        p, flags, ps.readUserState(userId), userId);
2913            }
2914            if ("android".equals(packageName)||"system".equals(packageName)) {
2915                return mAndroidApplication;
2916            }
2917            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2918                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2919            }
2920        }
2921        return null;
2922    }
2923
2924    @Override
2925    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2926            final IPackageDataObserver observer) {
2927        mContext.enforceCallingOrSelfPermission(
2928                android.Manifest.permission.CLEAR_APP_CACHE, null);
2929        // Queue up an async operation since clearing cache may take a little while.
2930        mHandler.post(new Runnable() {
2931            public void run() {
2932                mHandler.removeCallbacks(this);
2933                int retCode = -1;
2934                synchronized (mInstallLock) {
2935                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2936                    if (retCode < 0) {
2937                        Slog.w(TAG, "Couldn't clear application caches");
2938                    }
2939                }
2940                if (observer != null) {
2941                    try {
2942                        observer.onRemoveCompleted(null, (retCode >= 0));
2943                    } catch (RemoteException e) {
2944                        Slog.w(TAG, "RemoveException when invoking call back");
2945                    }
2946                }
2947            }
2948        });
2949    }
2950
2951    @Override
2952    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2953            final IntentSender pi) {
2954        mContext.enforceCallingOrSelfPermission(
2955                android.Manifest.permission.CLEAR_APP_CACHE, null);
2956        // Queue up an async operation since clearing cache may take a little while.
2957        mHandler.post(new Runnable() {
2958            public void run() {
2959                mHandler.removeCallbacks(this);
2960                int retCode = -1;
2961                synchronized (mInstallLock) {
2962                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2963                    if (retCode < 0) {
2964                        Slog.w(TAG, "Couldn't clear application caches");
2965                    }
2966                }
2967                if(pi != null) {
2968                    try {
2969                        // Callback via pending intent
2970                        int code = (retCode >= 0) ? 1 : 0;
2971                        pi.sendIntent(null, code, null,
2972                                null, null);
2973                    } catch (SendIntentException e1) {
2974                        Slog.i(TAG, "Failed to send pending intent");
2975                    }
2976                }
2977            }
2978        });
2979    }
2980
2981    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2982        synchronized (mInstallLock) {
2983            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2984                throw new IOException("Failed to free enough space");
2985            }
2986        }
2987    }
2988
2989    @Override
2990    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2991        if (!sUserManager.exists(userId)) return null;
2992        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2993        synchronized (mPackages) {
2994            PackageParser.Activity a = mActivities.mActivities.get(component);
2995
2996            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2997            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2998                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2999                if (ps == null) return null;
3000                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3001                        userId);
3002            }
3003            if (mResolveComponentName.equals(component)) {
3004                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3005                        new PackageUserState(), userId);
3006            }
3007        }
3008        return null;
3009    }
3010
3011    @Override
3012    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3013            String resolvedType) {
3014        synchronized (mPackages) {
3015            if (component.equals(mResolveComponentName)) {
3016                // The resolver supports EVERYTHING!
3017                return true;
3018            }
3019            PackageParser.Activity a = mActivities.mActivities.get(component);
3020            if (a == null) {
3021                return false;
3022            }
3023            for (int i=0; i<a.intents.size(); i++) {
3024                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3025                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3026                    return true;
3027                }
3028            }
3029            return false;
3030        }
3031    }
3032
3033    @Override
3034    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3035        if (!sUserManager.exists(userId)) return null;
3036        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3037        synchronized (mPackages) {
3038            PackageParser.Activity a = mReceivers.mActivities.get(component);
3039            if (DEBUG_PACKAGE_INFO) Log.v(
3040                TAG, "getReceiverInfo " + component + ": " + a);
3041            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3042                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3043                if (ps == null) return null;
3044                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3045                        userId);
3046            }
3047        }
3048        return null;
3049    }
3050
3051    @Override
3052    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3053        if (!sUserManager.exists(userId)) return null;
3054        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3055        synchronized (mPackages) {
3056            PackageParser.Service s = mServices.mServices.get(component);
3057            if (DEBUG_PACKAGE_INFO) Log.v(
3058                TAG, "getServiceInfo " + component + ": " + s);
3059            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3060                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3061                if (ps == null) return null;
3062                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3063                        userId);
3064            }
3065        }
3066        return null;
3067    }
3068
3069    @Override
3070    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3071        if (!sUserManager.exists(userId)) return null;
3072        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3073        synchronized (mPackages) {
3074            PackageParser.Provider p = mProviders.mProviders.get(component);
3075            if (DEBUG_PACKAGE_INFO) Log.v(
3076                TAG, "getProviderInfo " + component + ": " + p);
3077            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3078                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3079                if (ps == null) return null;
3080                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3081                        userId);
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public String[] getSystemSharedLibraryNames() {
3089        Set<String> libSet;
3090        synchronized (mPackages) {
3091            libSet = mSharedLibraries.keySet();
3092            int size = libSet.size();
3093            if (size > 0) {
3094                String[] libs = new String[size];
3095                libSet.toArray(libs);
3096                return libs;
3097            }
3098        }
3099        return null;
3100    }
3101
3102    /**
3103     * @hide
3104     */
3105    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3106        synchronized (mPackages) {
3107            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3108            if (lib != null && lib.apk != null) {
3109                return mPackages.get(lib.apk);
3110            }
3111        }
3112        return null;
3113    }
3114
3115    @Override
3116    public FeatureInfo[] getSystemAvailableFeatures() {
3117        Collection<FeatureInfo> featSet;
3118        synchronized (mPackages) {
3119            featSet = mAvailableFeatures.values();
3120            int size = featSet.size();
3121            if (size > 0) {
3122                FeatureInfo[] features = new FeatureInfo[size+1];
3123                featSet.toArray(features);
3124                FeatureInfo fi = new FeatureInfo();
3125                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3126                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3127                features[size] = fi;
3128                return features;
3129            }
3130        }
3131        return null;
3132    }
3133
3134    @Override
3135    public boolean hasSystemFeature(String name) {
3136        synchronized (mPackages) {
3137            return mAvailableFeatures.containsKey(name);
3138        }
3139    }
3140
3141    private void checkValidCaller(int uid, int userId) {
3142        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3143            return;
3144
3145        throw new SecurityException("Caller uid=" + uid
3146                + " is not privileged to communicate with user=" + userId);
3147    }
3148
3149    @Override
3150    public int checkPermission(String permName, String pkgName, int userId) {
3151        if (!sUserManager.exists(userId)) {
3152            return PackageManager.PERMISSION_DENIED;
3153        }
3154
3155        synchronized (mPackages) {
3156            final PackageParser.Package p = mPackages.get(pkgName);
3157            if (p != null && p.mExtras != null) {
3158                final PackageSetting ps = (PackageSetting) p.mExtras;
3159                final PermissionsState permissionsState = ps.getPermissionsState();
3160                if (permissionsState.hasPermission(permName, userId)) {
3161                    return PackageManager.PERMISSION_GRANTED;
3162                }
3163                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3164                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3165                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3166                    return PackageManager.PERMISSION_GRANTED;
3167                }
3168            }
3169        }
3170
3171        return PackageManager.PERMISSION_DENIED;
3172    }
3173
3174    @Override
3175    public int checkUidPermission(String permName, int uid) {
3176        final int userId = UserHandle.getUserId(uid);
3177
3178        if (!sUserManager.exists(userId)) {
3179            return PackageManager.PERMISSION_DENIED;
3180        }
3181
3182        synchronized (mPackages) {
3183            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3184            if (obj != null) {
3185                final SettingBase ps = (SettingBase) obj;
3186                final PermissionsState permissionsState = ps.getPermissionsState();
3187                if (permissionsState.hasPermission(permName, userId)) {
3188                    return PackageManager.PERMISSION_GRANTED;
3189                }
3190                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3191                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3192                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3193                    return PackageManager.PERMISSION_GRANTED;
3194                }
3195            } else {
3196                ArraySet<String> perms = mSystemPermissions.get(uid);
3197                if (perms != null) {
3198                    if (perms.contains(permName)) {
3199                        return PackageManager.PERMISSION_GRANTED;
3200                    }
3201                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3202                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3203                        return PackageManager.PERMISSION_GRANTED;
3204                    }
3205                }
3206            }
3207        }
3208
3209        return PackageManager.PERMISSION_DENIED;
3210    }
3211
3212    @Override
3213    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3214        if (UserHandle.getCallingUserId() != userId) {
3215            mContext.enforceCallingPermission(
3216                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3217                    "isPermissionRevokedByPolicy for user " + userId);
3218        }
3219
3220        if (checkPermission(permission, packageName, userId)
3221                == PackageManager.PERMISSION_GRANTED) {
3222            return false;
3223        }
3224
3225        final long identity = Binder.clearCallingIdentity();
3226        try {
3227            final int flags = getPermissionFlags(permission, packageName, userId);
3228            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3229        } finally {
3230            Binder.restoreCallingIdentity(identity);
3231        }
3232    }
3233
3234    @Override
3235    public String getPermissionControllerPackageName() {
3236        synchronized (mPackages) {
3237            return mRequiredInstallerPackage;
3238        }
3239    }
3240
3241    /**
3242     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3243     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3244     * @param checkShell TODO(yamasani):
3245     * @param message the message to log on security exception
3246     */
3247    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3248            boolean checkShell, String message) {
3249        if (userId < 0) {
3250            throw new IllegalArgumentException("Invalid userId " + userId);
3251        }
3252        if (checkShell) {
3253            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3254        }
3255        if (userId == UserHandle.getUserId(callingUid)) return;
3256        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3257            if (requireFullPermission) {
3258                mContext.enforceCallingOrSelfPermission(
3259                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3260            } else {
3261                try {
3262                    mContext.enforceCallingOrSelfPermission(
3263                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3264                } catch (SecurityException se) {
3265                    mContext.enforceCallingOrSelfPermission(
3266                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3267                }
3268            }
3269        }
3270    }
3271
3272    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3273        if (callingUid == Process.SHELL_UID) {
3274            if (userHandle >= 0
3275                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3276                throw new SecurityException("Shell does not have permission to access user "
3277                        + userHandle);
3278            } else if (userHandle < 0) {
3279                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3280                        + Debug.getCallers(3));
3281            }
3282        }
3283    }
3284
3285    private BasePermission findPermissionTreeLP(String permName) {
3286        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3287            if (permName.startsWith(bp.name) &&
3288                    permName.length() > bp.name.length() &&
3289                    permName.charAt(bp.name.length()) == '.') {
3290                return bp;
3291            }
3292        }
3293        return null;
3294    }
3295
3296    private BasePermission checkPermissionTreeLP(String permName) {
3297        if (permName != null) {
3298            BasePermission bp = findPermissionTreeLP(permName);
3299            if (bp != null) {
3300                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3301                    return bp;
3302                }
3303                throw new SecurityException("Calling uid "
3304                        + Binder.getCallingUid()
3305                        + " is not allowed to add to permission tree "
3306                        + bp.name + " owned by uid " + bp.uid);
3307            }
3308        }
3309        throw new SecurityException("No permission tree found for " + permName);
3310    }
3311
3312    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3313        if (s1 == null) {
3314            return s2 == null;
3315        }
3316        if (s2 == null) {
3317            return false;
3318        }
3319        if (s1.getClass() != s2.getClass()) {
3320            return false;
3321        }
3322        return s1.equals(s2);
3323    }
3324
3325    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3326        if (pi1.icon != pi2.icon) return false;
3327        if (pi1.logo != pi2.logo) return false;
3328        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3329        if (!compareStrings(pi1.name, pi2.name)) return false;
3330        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3331        // We'll take care of setting this one.
3332        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3333        // These are not currently stored in settings.
3334        //if (!compareStrings(pi1.group, pi2.group)) return false;
3335        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3336        //if (pi1.labelRes != pi2.labelRes) return false;
3337        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3338        return true;
3339    }
3340
3341    int permissionInfoFootprint(PermissionInfo info) {
3342        int size = info.name.length();
3343        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3344        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3345        return size;
3346    }
3347
3348    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3349        int size = 0;
3350        for (BasePermission perm : mSettings.mPermissions.values()) {
3351            if (perm.uid == tree.uid) {
3352                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3353            }
3354        }
3355        return size;
3356    }
3357
3358    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3359        // We calculate the max size of permissions defined by this uid and throw
3360        // if that plus the size of 'info' would exceed our stated maximum.
3361        if (tree.uid != Process.SYSTEM_UID) {
3362            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3363            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3364                throw new SecurityException("Permission tree size cap exceeded");
3365            }
3366        }
3367    }
3368
3369    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3370        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3371            throw new SecurityException("Label must be specified in permission");
3372        }
3373        BasePermission tree = checkPermissionTreeLP(info.name);
3374        BasePermission bp = mSettings.mPermissions.get(info.name);
3375        boolean added = bp == null;
3376        boolean changed = true;
3377        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3378        if (added) {
3379            enforcePermissionCapLocked(info, tree);
3380            bp = new BasePermission(info.name, tree.sourcePackage,
3381                    BasePermission.TYPE_DYNAMIC);
3382        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3383            throw new SecurityException(
3384                    "Not allowed to modify non-dynamic permission "
3385                    + info.name);
3386        } else {
3387            if (bp.protectionLevel == fixedLevel
3388                    && bp.perm.owner.equals(tree.perm.owner)
3389                    && bp.uid == tree.uid
3390                    && comparePermissionInfos(bp.perm.info, info)) {
3391                changed = false;
3392            }
3393        }
3394        bp.protectionLevel = fixedLevel;
3395        info = new PermissionInfo(info);
3396        info.protectionLevel = fixedLevel;
3397        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3398        bp.perm.info.packageName = tree.perm.info.packageName;
3399        bp.uid = tree.uid;
3400        if (added) {
3401            mSettings.mPermissions.put(info.name, bp);
3402        }
3403        if (changed) {
3404            if (!async) {
3405                mSettings.writeLPr();
3406            } else {
3407                scheduleWriteSettingsLocked();
3408            }
3409        }
3410        return added;
3411    }
3412
3413    @Override
3414    public boolean addPermission(PermissionInfo info) {
3415        synchronized (mPackages) {
3416            return addPermissionLocked(info, false);
3417        }
3418    }
3419
3420    @Override
3421    public boolean addPermissionAsync(PermissionInfo info) {
3422        synchronized (mPackages) {
3423            return addPermissionLocked(info, true);
3424        }
3425    }
3426
3427    @Override
3428    public void removePermission(String name) {
3429        synchronized (mPackages) {
3430            checkPermissionTreeLP(name);
3431            BasePermission bp = mSettings.mPermissions.get(name);
3432            if (bp != null) {
3433                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3434                    throw new SecurityException(
3435                            "Not allowed to modify non-dynamic permission "
3436                            + name);
3437                }
3438                mSettings.mPermissions.remove(name);
3439                mSettings.writeLPr();
3440            }
3441        }
3442    }
3443
3444    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3445            BasePermission bp) {
3446        int index = pkg.requestedPermissions.indexOf(bp.name);
3447        if (index == -1) {
3448            throw new SecurityException("Package " + pkg.packageName
3449                    + " has not requested permission " + bp.name);
3450        }
3451        if (!bp.isRuntime() && !bp.isDevelopment()) {
3452            throw new SecurityException("Permission " + bp.name
3453                    + " is not a changeable permission type");
3454        }
3455    }
3456
3457    @Override
3458    public void grantRuntimePermission(String packageName, String name, final int userId) {
3459        if (!sUserManager.exists(userId)) {
3460            Log.e(TAG, "No such user:" + userId);
3461            return;
3462        }
3463
3464        mContext.enforceCallingOrSelfPermission(
3465                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3466                "grantRuntimePermission");
3467
3468        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3469                "grantRuntimePermission");
3470
3471        final int uid;
3472        final SettingBase sb;
3473
3474        synchronized (mPackages) {
3475            final PackageParser.Package pkg = mPackages.get(packageName);
3476            if (pkg == null) {
3477                throw new IllegalArgumentException("Unknown package: " + packageName);
3478            }
3479
3480            final BasePermission bp = mSettings.mPermissions.get(name);
3481            if (bp == null) {
3482                throw new IllegalArgumentException("Unknown permission: " + name);
3483            }
3484
3485            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3486
3487            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3488            sb = (SettingBase) pkg.mExtras;
3489            if (sb == null) {
3490                throw new IllegalArgumentException("Unknown package: " + packageName);
3491            }
3492
3493            final PermissionsState permissionsState = sb.getPermissionsState();
3494
3495            final int flags = permissionsState.getPermissionFlags(name, userId);
3496            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3497                throw new SecurityException("Cannot grant system fixed permission: "
3498                        + name + " for package: " + packageName);
3499            }
3500
3501            if (bp.isDevelopment()) {
3502                // Development permissions must be handled specially, since they are not
3503                // normal runtime permissions.  For now they apply to all users.
3504                if (permissionsState.grantInstallPermission(bp) !=
3505                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3506                    scheduleWriteSettingsLocked();
3507                }
3508                return;
3509            }
3510
3511            final int result = permissionsState.grantRuntimePermission(bp, userId);
3512            switch (result) {
3513                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3514                    return;
3515                }
3516
3517                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3518                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3519                    mHandler.post(new Runnable() {
3520                        @Override
3521                        public void run() {
3522                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3523                        }
3524                    });
3525                } break;
3526            }
3527
3528            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3529
3530            // Not critical if that is lost - app has to request again.
3531            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3532        }
3533
3534        // Only need to do this if user is initialized. Otherwise it's a new user
3535        // and there are no processes running as the user yet and there's no need
3536        // to make an expensive call to remount processes for the changed permissions.
3537        if (READ_EXTERNAL_STORAGE.equals(name)
3538                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3539            final long token = Binder.clearCallingIdentity();
3540            try {
3541                if (sUserManager.isInitialized(userId)) {
3542                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3543                            MountServiceInternal.class);
3544                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3545                }
3546            } finally {
3547                Binder.restoreCallingIdentity(token);
3548            }
3549        }
3550    }
3551
3552    @Override
3553    public void revokeRuntimePermission(String packageName, String name, int userId) {
3554        if (!sUserManager.exists(userId)) {
3555            Log.e(TAG, "No such user:" + userId);
3556            return;
3557        }
3558
3559        mContext.enforceCallingOrSelfPermission(
3560                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3561                "revokeRuntimePermission");
3562
3563        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3564                "revokeRuntimePermission");
3565
3566        final int appId;
3567
3568        synchronized (mPackages) {
3569            final PackageParser.Package pkg = mPackages.get(packageName);
3570            if (pkg == null) {
3571                throw new IllegalArgumentException("Unknown package: " + packageName);
3572            }
3573
3574            final BasePermission bp = mSettings.mPermissions.get(name);
3575            if (bp == null) {
3576                throw new IllegalArgumentException("Unknown permission: " + name);
3577            }
3578
3579            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3580
3581            SettingBase sb = (SettingBase) pkg.mExtras;
3582            if (sb == null) {
3583                throw new IllegalArgumentException("Unknown package: " + packageName);
3584            }
3585
3586            final PermissionsState permissionsState = sb.getPermissionsState();
3587
3588            final int flags = permissionsState.getPermissionFlags(name, userId);
3589            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3590                throw new SecurityException("Cannot revoke system fixed permission: "
3591                        + name + " for package: " + packageName);
3592            }
3593
3594            if (bp.isDevelopment()) {
3595                // Development permissions must be handled specially, since they are not
3596                // normal runtime permissions.  For now they apply to all users.
3597                if (permissionsState.revokeInstallPermission(bp) !=
3598                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3599                    scheduleWriteSettingsLocked();
3600                }
3601                return;
3602            }
3603
3604            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3605                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3606                return;
3607            }
3608
3609            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3610
3611            // Critical, after this call app should never have the permission.
3612            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3613
3614            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3615        }
3616
3617        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3618    }
3619
3620    @Override
3621    public void resetRuntimePermissions() {
3622        mContext.enforceCallingOrSelfPermission(
3623                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3624                "revokeRuntimePermission");
3625
3626        int callingUid = Binder.getCallingUid();
3627        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3628            mContext.enforceCallingOrSelfPermission(
3629                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3630                    "resetRuntimePermissions");
3631        }
3632
3633        synchronized (mPackages) {
3634            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3635            for (int userId : UserManagerService.getInstance().getUserIds()) {
3636                final int packageCount = mPackages.size();
3637                for (int i = 0; i < packageCount; i++) {
3638                    PackageParser.Package pkg = mPackages.valueAt(i);
3639                    if (!(pkg.mExtras instanceof PackageSetting)) {
3640                        continue;
3641                    }
3642                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3643                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3644                }
3645            }
3646        }
3647    }
3648
3649    @Override
3650    public int getPermissionFlags(String name, String packageName, int userId) {
3651        if (!sUserManager.exists(userId)) {
3652            return 0;
3653        }
3654
3655        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3656
3657        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3658                "getPermissionFlags");
3659
3660        synchronized (mPackages) {
3661            final PackageParser.Package pkg = mPackages.get(packageName);
3662            if (pkg == null) {
3663                throw new IllegalArgumentException("Unknown package: " + packageName);
3664            }
3665
3666            final BasePermission bp = mSettings.mPermissions.get(name);
3667            if (bp == null) {
3668                throw new IllegalArgumentException("Unknown permission: " + name);
3669            }
3670
3671            SettingBase sb = (SettingBase) pkg.mExtras;
3672            if (sb == null) {
3673                throw new IllegalArgumentException("Unknown package: " + packageName);
3674            }
3675
3676            PermissionsState permissionsState = sb.getPermissionsState();
3677            return permissionsState.getPermissionFlags(name, userId);
3678        }
3679    }
3680
3681    @Override
3682    public void updatePermissionFlags(String name, String packageName, int flagMask,
3683            int flagValues, int userId) {
3684        if (!sUserManager.exists(userId)) {
3685            return;
3686        }
3687
3688        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3689
3690        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3691                "updatePermissionFlags");
3692
3693        // Only the system can change these flags and nothing else.
3694        if (getCallingUid() != Process.SYSTEM_UID) {
3695            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3696            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3697            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3698            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3699        }
3700
3701        synchronized (mPackages) {
3702            final PackageParser.Package pkg = mPackages.get(packageName);
3703            if (pkg == null) {
3704                throw new IllegalArgumentException("Unknown package: " + packageName);
3705            }
3706
3707            final BasePermission bp = mSettings.mPermissions.get(name);
3708            if (bp == null) {
3709                throw new IllegalArgumentException("Unknown permission: " + name);
3710            }
3711
3712            SettingBase sb = (SettingBase) pkg.mExtras;
3713            if (sb == null) {
3714                throw new IllegalArgumentException("Unknown package: " + packageName);
3715            }
3716
3717            PermissionsState permissionsState = sb.getPermissionsState();
3718
3719            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3720
3721            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3722                // Install and runtime permissions are stored in different places,
3723                // so figure out what permission changed and persist the change.
3724                if (permissionsState.getInstallPermissionState(name) != null) {
3725                    scheduleWriteSettingsLocked();
3726                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3727                        || hadState) {
3728                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3729                }
3730            }
3731        }
3732    }
3733
3734    /**
3735     * Update the permission flags for all packages and runtime permissions of a user in order
3736     * to allow device or profile owner to remove POLICY_FIXED.
3737     */
3738    @Override
3739    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3740        if (!sUserManager.exists(userId)) {
3741            return;
3742        }
3743
3744        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3745
3746        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3747                "updatePermissionFlagsForAllApps");
3748
3749        // Only the system can change system fixed flags.
3750        if (getCallingUid() != Process.SYSTEM_UID) {
3751            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3752            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3753        }
3754
3755        synchronized (mPackages) {
3756            boolean changed = false;
3757            final int packageCount = mPackages.size();
3758            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3759                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3760                SettingBase sb = (SettingBase) pkg.mExtras;
3761                if (sb == null) {
3762                    continue;
3763                }
3764                PermissionsState permissionsState = sb.getPermissionsState();
3765                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3766                        userId, flagMask, flagValues);
3767            }
3768            if (changed) {
3769                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3770            }
3771        }
3772    }
3773
3774    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3775        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3776                != PackageManager.PERMISSION_GRANTED
3777            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3778                != PackageManager.PERMISSION_GRANTED) {
3779            throw new SecurityException(message + " requires "
3780                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3781                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3782        }
3783    }
3784
3785    @Override
3786    public boolean shouldShowRequestPermissionRationale(String permissionName,
3787            String packageName, int userId) {
3788        if (UserHandle.getCallingUserId() != userId) {
3789            mContext.enforceCallingPermission(
3790                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3791                    "canShowRequestPermissionRationale for user " + userId);
3792        }
3793
3794        final int uid = getPackageUid(packageName, userId);
3795        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3796            return false;
3797        }
3798
3799        if (checkPermission(permissionName, packageName, userId)
3800                == PackageManager.PERMISSION_GRANTED) {
3801            return false;
3802        }
3803
3804        final int flags;
3805
3806        final long identity = Binder.clearCallingIdentity();
3807        try {
3808            flags = getPermissionFlags(permissionName,
3809                    packageName, userId);
3810        } finally {
3811            Binder.restoreCallingIdentity(identity);
3812        }
3813
3814        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3815                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3816                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3817
3818        if ((flags & fixedFlags) != 0) {
3819            return false;
3820        }
3821
3822        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3823    }
3824
3825    @Override
3826    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3827        mContext.enforceCallingOrSelfPermission(
3828                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3829                "addOnPermissionsChangeListener");
3830
3831        synchronized (mPackages) {
3832            mOnPermissionChangeListeners.addListenerLocked(listener);
3833        }
3834    }
3835
3836    @Override
3837    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3838        synchronized (mPackages) {
3839            mOnPermissionChangeListeners.removeListenerLocked(listener);
3840        }
3841    }
3842
3843    @Override
3844    public boolean isProtectedBroadcast(String actionName) {
3845        synchronized (mPackages) {
3846            return mProtectedBroadcasts.contains(actionName);
3847        }
3848    }
3849
3850    @Override
3851    public int checkSignatures(String pkg1, String pkg2) {
3852        synchronized (mPackages) {
3853            final PackageParser.Package p1 = mPackages.get(pkg1);
3854            final PackageParser.Package p2 = mPackages.get(pkg2);
3855            if (p1 == null || p1.mExtras == null
3856                    || p2 == null || p2.mExtras == null) {
3857                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3858            }
3859            return compareSignatures(p1.mSignatures, p2.mSignatures);
3860        }
3861    }
3862
3863    @Override
3864    public int checkUidSignatures(int uid1, int uid2) {
3865        // Map to base uids.
3866        uid1 = UserHandle.getAppId(uid1);
3867        uid2 = UserHandle.getAppId(uid2);
3868        // reader
3869        synchronized (mPackages) {
3870            Signature[] s1;
3871            Signature[] s2;
3872            Object obj = mSettings.getUserIdLPr(uid1);
3873            if (obj != null) {
3874                if (obj instanceof SharedUserSetting) {
3875                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3876                } else if (obj instanceof PackageSetting) {
3877                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3878                } else {
3879                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3880                }
3881            } else {
3882                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3883            }
3884            obj = mSettings.getUserIdLPr(uid2);
3885            if (obj != null) {
3886                if (obj instanceof SharedUserSetting) {
3887                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3888                } else if (obj instanceof PackageSetting) {
3889                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3890                } else {
3891                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3892                }
3893            } else {
3894                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3895            }
3896            return compareSignatures(s1, s2);
3897        }
3898    }
3899
3900    private void killUid(int appId, int userId, String reason) {
3901        final long identity = Binder.clearCallingIdentity();
3902        try {
3903            IActivityManager am = ActivityManagerNative.getDefault();
3904            if (am != null) {
3905                try {
3906                    am.killUid(appId, userId, reason);
3907                } catch (RemoteException e) {
3908                    /* ignore - same process */
3909                }
3910            }
3911        } finally {
3912            Binder.restoreCallingIdentity(identity);
3913        }
3914    }
3915
3916    /**
3917     * Compares two sets of signatures. Returns:
3918     * <br />
3919     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3920     * <br />
3921     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3922     * <br />
3923     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3924     * <br />
3925     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3926     * <br />
3927     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3928     */
3929    static int compareSignatures(Signature[] s1, Signature[] s2) {
3930        if (s1 == null) {
3931            return s2 == null
3932                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3933                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3934        }
3935
3936        if (s2 == null) {
3937            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3938        }
3939
3940        if (s1.length != s2.length) {
3941            return PackageManager.SIGNATURE_NO_MATCH;
3942        }
3943
3944        // Since both signature sets are of size 1, we can compare without HashSets.
3945        if (s1.length == 1) {
3946            return s1[0].equals(s2[0]) ?
3947                    PackageManager.SIGNATURE_MATCH :
3948                    PackageManager.SIGNATURE_NO_MATCH;
3949        }
3950
3951        ArraySet<Signature> set1 = new ArraySet<Signature>();
3952        for (Signature sig : s1) {
3953            set1.add(sig);
3954        }
3955        ArraySet<Signature> set2 = new ArraySet<Signature>();
3956        for (Signature sig : s2) {
3957            set2.add(sig);
3958        }
3959        // Make sure s2 contains all signatures in s1.
3960        if (set1.equals(set2)) {
3961            return PackageManager.SIGNATURE_MATCH;
3962        }
3963        return PackageManager.SIGNATURE_NO_MATCH;
3964    }
3965
3966    /**
3967     * If the database version for this type of package (internal storage or
3968     * external storage) is less than the version where package signatures
3969     * were updated, return true.
3970     */
3971    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3972        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3973        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3974    }
3975
3976    /**
3977     * Used for backward compatibility to make sure any packages with
3978     * certificate chains get upgraded to the new style. {@code existingSigs}
3979     * will be in the old format (since they were stored on disk from before the
3980     * system upgrade) and {@code scannedSigs} will be in the newer format.
3981     */
3982    private int compareSignaturesCompat(PackageSignatures existingSigs,
3983            PackageParser.Package scannedPkg) {
3984        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3985            return PackageManager.SIGNATURE_NO_MATCH;
3986        }
3987
3988        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3989        for (Signature sig : existingSigs.mSignatures) {
3990            existingSet.add(sig);
3991        }
3992        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3993        for (Signature sig : scannedPkg.mSignatures) {
3994            try {
3995                Signature[] chainSignatures = sig.getChainSignatures();
3996                for (Signature chainSig : chainSignatures) {
3997                    scannedCompatSet.add(chainSig);
3998                }
3999            } catch (CertificateEncodingException e) {
4000                scannedCompatSet.add(sig);
4001            }
4002        }
4003        /*
4004         * Make sure the expanded scanned set contains all signatures in the
4005         * existing one.
4006         */
4007        if (scannedCompatSet.equals(existingSet)) {
4008            // Migrate the old signatures to the new scheme.
4009            existingSigs.assignSignatures(scannedPkg.mSignatures);
4010            // The new KeySets will be re-added later in the scanning process.
4011            synchronized (mPackages) {
4012                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4013            }
4014            return PackageManager.SIGNATURE_MATCH;
4015        }
4016        return PackageManager.SIGNATURE_NO_MATCH;
4017    }
4018
4019    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4020        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4021        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4022    }
4023
4024    private int compareSignaturesRecover(PackageSignatures existingSigs,
4025            PackageParser.Package scannedPkg) {
4026        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4027            return PackageManager.SIGNATURE_NO_MATCH;
4028        }
4029
4030        String msg = null;
4031        try {
4032            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4033                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4034                        + scannedPkg.packageName);
4035                return PackageManager.SIGNATURE_MATCH;
4036            }
4037        } catch (CertificateException e) {
4038            msg = e.getMessage();
4039        }
4040
4041        logCriticalInfo(Log.INFO,
4042                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4043        return PackageManager.SIGNATURE_NO_MATCH;
4044    }
4045
4046    @Override
4047    public String[] getPackagesForUid(int uid) {
4048        uid = UserHandle.getAppId(uid);
4049        // reader
4050        synchronized (mPackages) {
4051            Object obj = mSettings.getUserIdLPr(uid);
4052            if (obj instanceof SharedUserSetting) {
4053                final SharedUserSetting sus = (SharedUserSetting) obj;
4054                final int N = sus.packages.size();
4055                final String[] res = new String[N];
4056                final Iterator<PackageSetting> it = sus.packages.iterator();
4057                int i = 0;
4058                while (it.hasNext()) {
4059                    res[i++] = it.next().name;
4060                }
4061                return res;
4062            } else if (obj instanceof PackageSetting) {
4063                final PackageSetting ps = (PackageSetting) obj;
4064                return new String[] { ps.name };
4065            }
4066        }
4067        return null;
4068    }
4069
4070    @Override
4071    public String getNameForUid(int uid) {
4072        // reader
4073        synchronized (mPackages) {
4074            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4075            if (obj instanceof SharedUserSetting) {
4076                final SharedUserSetting sus = (SharedUserSetting) obj;
4077                return sus.name + ":" + sus.userId;
4078            } else if (obj instanceof PackageSetting) {
4079                final PackageSetting ps = (PackageSetting) obj;
4080                return ps.name;
4081            }
4082        }
4083        return null;
4084    }
4085
4086    @Override
4087    public int getUidForSharedUser(String sharedUserName) {
4088        if(sharedUserName == null) {
4089            return -1;
4090        }
4091        // reader
4092        synchronized (mPackages) {
4093            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4094            if (suid == null) {
4095                return -1;
4096            }
4097            return suid.userId;
4098        }
4099    }
4100
4101    @Override
4102    public int getFlagsForUid(int uid) {
4103        synchronized (mPackages) {
4104            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4105            if (obj instanceof SharedUserSetting) {
4106                final SharedUserSetting sus = (SharedUserSetting) obj;
4107                return sus.pkgFlags;
4108            } else if (obj instanceof PackageSetting) {
4109                final PackageSetting ps = (PackageSetting) obj;
4110                return ps.pkgFlags;
4111            }
4112        }
4113        return 0;
4114    }
4115
4116    @Override
4117    public int getPrivateFlagsForUid(int uid) {
4118        synchronized (mPackages) {
4119            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4120            if (obj instanceof SharedUserSetting) {
4121                final SharedUserSetting sus = (SharedUserSetting) obj;
4122                return sus.pkgPrivateFlags;
4123            } else if (obj instanceof PackageSetting) {
4124                final PackageSetting ps = (PackageSetting) obj;
4125                return ps.pkgPrivateFlags;
4126            }
4127        }
4128        return 0;
4129    }
4130
4131    @Override
4132    public boolean isUidPrivileged(int uid) {
4133        uid = UserHandle.getAppId(uid);
4134        // reader
4135        synchronized (mPackages) {
4136            Object obj = mSettings.getUserIdLPr(uid);
4137            if (obj instanceof SharedUserSetting) {
4138                final SharedUserSetting sus = (SharedUserSetting) obj;
4139                final Iterator<PackageSetting> it = sus.packages.iterator();
4140                while (it.hasNext()) {
4141                    if (it.next().isPrivileged()) {
4142                        return true;
4143                    }
4144                }
4145            } else if (obj instanceof PackageSetting) {
4146                final PackageSetting ps = (PackageSetting) obj;
4147                return ps.isPrivileged();
4148            }
4149        }
4150        return false;
4151    }
4152
4153    @Override
4154    public String[] getAppOpPermissionPackages(String permissionName) {
4155        synchronized (mPackages) {
4156            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4157            if (pkgs == null) {
4158                return null;
4159            }
4160            return pkgs.toArray(new String[pkgs.size()]);
4161        }
4162    }
4163
4164    @Override
4165    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4166            int flags, int userId) {
4167        if (!sUserManager.exists(userId)) return null;
4168        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4169        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4170        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4171    }
4172
4173    @Override
4174    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4175            IntentFilter filter, int match, ComponentName activity) {
4176        final int userId = UserHandle.getCallingUserId();
4177        if (DEBUG_PREFERRED) {
4178            Log.v(TAG, "setLastChosenActivity intent=" + intent
4179                + " resolvedType=" + resolvedType
4180                + " flags=" + flags
4181                + " filter=" + filter
4182                + " match=" + match
4183                + " activity=" + activity);
4184            filter.dump(new PrintStreamPrinter(System.out), "    ");
4185        }
4186        intent.setComponent(null);
4187        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4188        // Find any earlier preferred or last chosen entries and nuke them
4189        findPreferredActivity(intent, resolvedType,
4190                flags, query, 0, false, true, false, userId);
4191        // Add the new activity as the last chosen for this filter
4192        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4193                "Setting last chosen");
4194    }
4195
4196    @Override
4197    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4198        final int userId = UserHandle.getCallingUserId();
4199        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4200        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4201        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4202                false, false, false, userId);
4203    }
4204
4205    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4206            int flags, List<ResolveInfo> query, int userId) {
4207        if (query != null) {
4208            final int N = query.size();
4209            if (N == 1) {
4210                return query.get(0);
4211            } else if (N > 1) {
4212                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4213                // If there is more than one activity with the same priority,
4214                // then let the user decide between them.
4215                ResolveInfo r0 = query.get(0);
4216                ResolveInfo r1 = query.get(1);
4217                if (DEBUG_INTENT_MATCHING || debug) {
4218                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4219                            + r1.activityInfo.name + "=" + r1.priority);
4220                }
4221                // If the first activity has a higher priority, or a different
4222                // default, then it is always desireable to pick it.
4223                if (r0.priority != r1.priority
4224                        || r0.preferredOrder != r1.preferredOrder
4225                        || r0.isDefault != r1.isDefault) {
4226                    return query.get(0);
4227                }
4228                // If we have saved a preference for a preferred activity for
4229                // this Intent, use that.
4230                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4231                        flags, query, r0.priority, true, false, debug, userId);
4232                if (ri != null) {
4233                    return ri;
4234                }
4235                ri = new ResolveInfo(mResolveInfo);
4236                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4237                ri.activityInfo.applicationInfo = new ApplicationInfo(
4238                        ri.activityInfo.applicationInfo);
4239                if (userId != 0) {
4240                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4241                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4242                }
4243                // Make sure that the resolver is displayable in car mode
4244                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4245                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4246                return ri;
4247            }
4248        }
4249        return null;
4250    }
4251
4252    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4253            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4254        final int N = query.size();
4255        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4256                .get(userId);
4257        // Get the list of persistent preferred activities that handle the intent
4258        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4259        List<PersistentPreferredActivity> pprefs = ppir != null
4260                ? ppir.queryIntent(intent, resolvedType,
4261                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4262                : null;
4263        if (pprefs != null && pprefs.size() > 0) {
4264            final int M = pprefs.size();
4265            for (int i=0; i<M; i++) {
4266                final PersistentPreferredActivity ppa = pprefs.get(i);
4267                if (DEBUG_PREFERRED || debug) {
4268                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4269                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4270                            + "\n  component=" + ppa.mComponent);
4271                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4272                }
4273                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4274                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4275                if (DEBUG_PREFERRED || debug) {
4276                    Slog.v(TAG, "Found persistent preferred activity:");
4277                    if (ai != null) {
4278                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4279                    } else {
4280                        Slog.v(TAG, "  null");
4281                    }
4282                }
4283                if (ai == null) {
4284                    // This previously registered persistent preferred activity
4285                    // component is no longer known. Ignore it and do NOT remove it.
4286                    continue;
4287                }
4288                for (int j=0; j<N; j++) {
4289                    final ResolveInfo ri = query.get(j);
4290                    if (!ri.activityInfo.applicationInfo.packageName
4291                            .equals(ai.applicationInfo.packageName)) {
4292                        continue;
4293                    }
4294                    if (!ri.activityInfo.name.equals(ai.name)) {
4295                        continue;
4296                    }
4297                    //  Found a persistent preference that can handle the intent.
4298                    if (DEBUG_PREFERRED || debug) {
4299                        Slog.v(TAG, "Returning persistent preferred activity: " +
4300                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4301                    }
4302                    return ri;
4303                }
4304            }
4305        }
4306        return null;
4307    }
4308
4309    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4310            List<ResolveInfo> query, int priority, boolean always,
4311            boolean removeMatches, boolean debug, int userId) {
4312        if (!sUserManager.exists(userId)) return null;
4313        // writer
4314        synchronized (mPackages) {
4315            if (intent.getSelector() != null) {
4316                intent = intent.getSelector();
4317            }
4318            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4319
4320            // Try to find a matching persistent preferred activity.
4321            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4322                    debug, userId);
4323
4324            // If a persistent preferred activity matched, use it.
4325            if (pri != null) {
4326                return pri;
4327            }
4328
4329            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4330            // Get the list of preferred activities that handle the intent
4331            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4332            List<PreferredActivity> prefs = pir != null
4333                    ? pir.queryIntent(intent, resolvedType,
4334                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4335                    : null;
4336            if (prefs != null && prefs.size() > 0) {
4337                boolean changed = false;
4338                try {
4339                    // First figure out how good the original match set is.
4340                    // We will only allow preferred activities that came
4341                    // from the same match quality.
4342                    int match = 0;
4343
4344                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4345
4346                    final int N = query.size();
4347                    for (int j=0; j<N; j++) {
4348                        final ResolveInfo ri = query.get(j);
4349                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4350                                + ": 0x" + Integer.toHexString(match));
4351                        if (ri.match > match) {
4352                            match = ri.match;
4353                        }
4354                    }
4355
4356                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4357                            + Integer.toHexString(match));
4358
4359                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4360                    final int M = prefs.size();
4361                    for (int i=0; i<M; i++) {
4362                        final PreferredActivity pa = prefs.get(i);
4363                        if (DEBUG_PREFERRED || debug) {
4364                            Slog.v(TAG, "Checking PreferredActivity ds="
4365                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4366                                    + "\n  component=" + pa.mPref.mComponent);
4367                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4368                        }
4369                        if (pa.mPref.mMatch != match) {
4370                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4371                                    + Integer.toHexString(pa.mPref.mMatch));
4372                            continue;
4373                        }
4374                        // If it's not an "always" type preferred activity and that's what we're
4375                        // looking for, skip it.
4376                        if (always && !pa.mPref.mAlways) {
4377                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4378                            continue;
4379                        }
4380                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4381                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4382                        if (DEBUG_PREFERRED || debug) {
4383                            Slog.v(TAG, "Found preferred activity:");
4384                            if (ai != null) {
4385                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4386                            } else {
4387                                Slog.v(TAG, "  null");
4388                            }
4389                        }
4390                        if (ai == null) {
4391                            // This previously registered preferred activity
4392                            // component is no longer known.  Most likely an update
4393                            // to the app was installed and in the new version this
4394                            // component no longer exists.  Clean it up by removing
4395                            // it from the preferred activities list, and skip it.
4396                            Slog.w(TAG, "Removing dangling preferred activity: "
4397                                    + pa.mPref.mComponent);
4398                            pir.removeFilter(pa);
4399                            changed = true;
4400                            continue;
4401                        }
4402                        for (int j=0; j<N; j++) {
4403                            final ResolveInfo ri = query.get(j);
4404                            if (!ri.activityInfo.applicationInfo.packageName
4405                                    .equals(ai.applicationInfo.packageName)) {
4406                                continue;
4407                            }
4408                            if (!ri.activityInfo.name.equals(ai.name)) {
4409                                continue;
4410                            }
4411
4412                            if (removeMatches) {
4413                                pir.removeFilter(pa);
4414                                changed = true;
4415                                if (DEBUG_PREFERRED) {
4416                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4417                                }
4418                                break;
4419                            }
4420
4421                            // Okay we found a previously set preferred or last chosen app.
4422                            // If the result set is different from when this
4423                            // was created, we need to clear it and re-ask the
4424                            // user their preference, if we're looking for an "always" type entry.
4425                            if (always && !pa.mPref.sameSet(query)) {
4426                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4427                                        + intent + " type " + resolvedType);
4428                                if (DEBUG_PREFERRED) {
4429                                    Slog.v(TAG, "Removing preferred activity since set changed "
4430                                            + pa.mPref.mComponent);
4431                                }
4432                                pir.removeFilter(pa);
4433                                // Re-add the filter as a "last chosen" entry (!always)
4434                                PreferredActivity lastChosen = new PreferredActivity(
4435                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4436                                pir.addFilter(lastChosen);
4437                                changed = true;
4438                                return null;
4439                            }
4440
4441                            // Yay! Either the set matched or we're looking for the last chosen
4442                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4443                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4444                            return ri;
4445                        }
4446                    }
4447                } finally {
4448                    if (changed) {
4449                        if (DEBUG_PREFERRED) {
4450                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4451                        }
4452                        scheduleWritePackageRestrictionsLocked(userId);
4453                    }
4454                }
4455            }
4456        }
4457        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4458        return null;
4459    }
4460
4461    /*
4462     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4463     */
4464    @Override
4465    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4466            int targetUserId) {
4467        mContext.enforceCallingOrSelfPermission(
4468                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4469        List<CrossProfileIntentFilter> matches =
4470                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4471        if (matches != null) {
4472            int size = matches.size();
4473            for (int i = 0; i < size; i++) {
4474                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4475            }
4476        }
4477        if (hasWebURI(intent)) {
4478            // cross-profile app linking works only towards the parent.
4479            final UserInfo parent = getProfileParent(sourceUserId);
4480            synchronized(mPackages) {
4481                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4482                        intent, resolvedType, 0, sourceUserId, parent.id);
4483                return xpDomainInfo != null;
4484            }
4485        }
4486        return false;
4487    }
4488
4489    private UserInfo getProfileParent(int userId) {
4490        final long identity = Binder.clearCallingIdentity();
4491        try {
4492            return sUserManager.getProfileParent(userId);
4493        } finally {
4494            Binder.restoreCallingIdentity(identity);
4495        }
4496    }
4497
4498    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4499            String resolvedType, int userId) {
4500        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4501        if (resolver != null) {
4502            return resolver.queryIntent(intent, resolvedType, false, userId);
4503        }
4504        return null;
4505    }
4506
4507    @Override
4508    public List<ResolveInfo> queryIntentActivities(Intent intent,
4509            String resolvedType, int flags, int userId) {
4510        if (!sUserManager.exists(userId)) return Collections.emptyList();
4511        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4512        ComponentName comp = intent.getComponent();
4513        if (comp == null) {
4514            if (intent.getSelector() != null) {
4515                intent = intent.getSelector();
4516                comp = intent.getComponent();
4517            }
4518        }
4519
4520        if (comp != null) {
4521            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4522            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4523            if (ai != null) {
4524                final ResolveInfo ri = new ResolveInfo();
4525                ri.activityInfo = ai;
4526                list.add(ri);
4527            }
4528            return list;
4529        }
4530
4531        // reader
4532        synchronized (mPackages) {
4533            final String pkgName = intent.getPackage();
4534            if (pkgName == null) {
4535                List<CrossProfileIntentFilter> matchingFilters =
4536                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4537                // Check for results that need to skip the current profile.
4538                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4539                        resolvedType, flags, userId);
4540                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4541                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4542                    result.add(xpResolveInfo);
4543                    return filterIfNotPrimaryUser(result, userId);
4544                }
4545
4546                // Check for results in the current profile.
4547                List<ResolveInfo> result = mActivities.queryIntent(
4548                        intent, resolvedType, flags, userId);
4549
4550                // Check for cross profile results.
4551                xpResolveInfo = queryCrossProfileIntents(
4552                        matchingFilters, intent, resolvedType, flags, userId);
4553                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4554                    result.add(xpResolveInfo);
4555                    Collections.sort(result, mResolvePrioritySorter);
4556                }
4557                result = filterIfNotPrimaryUser(result, userId);
4558                if (hasWebURI(intent)) {
4559                    CrossProfileDomainInfo xpDomainInfo = null;
4560                    final UserInfo parent = getProfileParent(userId);
4561                    if (parent != null) {
4562                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4563                                flags, userId, parent.id);
4564                    }
4565                    if (xpDomainInfo != null) {
4566                        if (xpResolveInfo != null) {
4567                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4568                            // in the result.
4569                            result.remove(xpResolveInfo);
4570                        }
4571                        if (result.size() == 0) {
4572                            result.add(xpDomainInfo.resolveInfo);
4573                            return result;
4574                        }
4575                    } else if (result.size() <= 1) {
4576                        return result;
4577                    }
4578                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4579                            xpDomainInfo, userId);
4580                    Collections.sort(result, mResolvePrioritySorter);
4581                }
4582                return result;
4583            }
4584            final PackageParser.Package pkg = mPackages.get(pkgName);
4585            if (pkg != null) {
4586                return filterIfNotPrimaryUser(
4587                        mActivities.queryIntentForPackage(
4588                                intent, resolvedType, flags, pkg.activities, userId),
4589                        userId);
4590            }
4591            return new ArrayList<ResolveInfo>();
4592        }
4593    }
4594
4595    private static class CrossProfileDomainInfo {
4596        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4597        ResolveInfo resolveInfo;
4598        /* Best domain verification status of the activities found in the other profile */
4599        int bestDomainVerificationStatus;
4600    }
4601
4602    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4603            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4604        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4605                sourceUserId)) {
4606            return null;
4607        }
4608        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4609                resolvedType, flags, parentUserId);
4610
4611        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4612            return null;
4613        }
4614        CrossProfileDomainInfo result = null;
4615        int size = resultTargetUser.size();
4616        for (int i = 0; i < size; i++) {
4617            ResolveInfo riTargetUser = resultTargetUser.get(i);
4618            // Intent filter verification is only for filters that specify a host. So don't return
4619            // those that handle all web uris.
4620            if (riTargetUser.handleAllWebDataURI) {
4621                continue;
4622            }
4623            String packageName = riTargetUser.activityInfo.packageName;
4624            PackageSetting ps = mSettings.mPackages.get(packageName);
4625            if (ps == null) {
4626                continue;
4627            }
4628            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4629            int status = (int)(verificationState >> 32);
4630            if (result == null) {
4631                result = new CrossProfileDomainInfo();
4632                result.resolveInfo =
4633                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4634                result.bestDomainVerificationStatus = status;
4635            } else {
4636                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4637                        result.bestDomainVerificationStatus);
4638            }
4639        }
4640        // Don't consider matches with status NEVER across profiles.
4641        if (result != null && result.bestDomainVerificationStatus
4642                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4643            return null;
4644        }
4645        return result;
4646    }
4647
4648    /**
4649     * Verification statuses are ordered from the worse to the best, except for
4650     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4651     */
4652    private int bestDomainVerificationStatus(int status1, int status2) {
4653        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4654            return status2;
4655        }
4656        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4657            return status1;
4658        }
4659        return (int) MathUtils.max(status1, status2);
4660    }
4661
4662    private boolean isUserEnabled(int userId) {
4663        long callingId = Binder.clearCallingIdentity();
4664        try {
4665            UserInfo userInfo = sUserManager.getUserInfo(userId);
4666            return userInfo != null && userInfo.isEnabled();
4667        } finally {
4668            Binder.restoreCallingIdentity(callingId);
4669        }
4670    }
4671
4672    /**
4673     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4674     *
4675     * @return filtered list
4676     */
4677    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4678        if (userId == UserHandle.USER_OWNER) {
4679            return resolveInfos;
4680        }
4681        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4682            ResolveInfo info = resolveInfos.get(i);
4683            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4684                resolveInfos.remove(i);
4685            }
4686        }
4687        return resolveInfos;
4688    }
4689
4690    private static boolean hasWebURI(Intent intent) {
4691        if (intent.getData() == null) {
4692            return false;
4693        }
4694        final String scheme = intent.getScheme();
4695        if (TextUtils.isEmpty(scheme)) {
4696            return false;
4697        }
4698        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4699    }
4700
4701    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4702            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4703            int userId) {
4704        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4705
4706        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4707            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4708                    candidates.size());
4709        }
4710
4711        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4712        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4713        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4714        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4715        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4716        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4717
4718        synchronized (mPackages) {
4719            final int count = candidates.size();
4720            // First, try to use linked apps. Partition the candidates into four lists:
4721            // one for the final results, one for the "do not use ever", one for "undefined status"
4722            // and finally one for "browser app type".
4723            for (int n=0; n<count; n++) {
4724                ResolveInfo info = candidates.get(n);
4725                String packageName = info.activityInfo.packageName;
4726                PackageSetting ps = mSettings.mPackages.get(packageName);
4727                if (ps != null) {
4728                    // Add to the special match all list (Browser use case)
4729                    if (info.handleAllWebDataURI) {
4730                        matchAllList.add(info);
4731                        continue;
4732                    }
4733                    // Try to get the status from User settings first
4734                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4735                    int status = (int)(packedStatus >> 32);
4736                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4737                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4738                        if (DEBUG_DOMAIN_VERIFICATION) {
4739                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4740                                    + " : linkgen=" + linkGeneration);
4741                        }
4742                        // Use link-enabled generation as preferredOrder, i.e.
4743                        // prefer newly-enabled over earlier-enabled.
4744                        info.preferredOrder = linkGeneration;
4745                        alwaysList.add(info);
4746                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4747                        if (DEBUG_DOMAIN_VERIFICATION) {
4748                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4749                        }
4750                        neverList.add(info);
4751                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4752                        if (DEBUG_DOMAIN_VERIFICATION) {
4753                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4754                        }
4755                        alwaysAskList.add(info);
4756                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4757                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4758                        if (DEBUG_DOMAIN_VERIFICATION) {
4759                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4760                        }
4761                        undefinedList.add(info);
4762                    }
4763                }
4764            }
4765
4766            // We'll want to include browser possibilities in a few cases
4767            boolean includeBrowser = false;
4768
4769            // First try to add the "always" resolution(s) for the current user, if any
4770            if (alwaysList.size() > 0) {
4771                result.addAll(alwaysList);
4772            // if there is an "always" for the parent user, add it.
4773            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4774                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4775                result.add(xpDomainInfo.resolveInfo);
4776            } else {
4777                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4778                result.addAll(undefinedList);
4779                if (xpDomainInfo != null && (
4780                        xpDomainInfo.bestDomainVerificationStatus
4781                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4782                        || xpDomainInfo.bestDomainVerificationStatus
4783                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4784                    result.add(xpDomainInfo.resolveInfo);
4785                }
4786                includeBrowser = true;
4787            }
4788
4789            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4790            // If there were 'always' entries their preferred order has been set, so we also
4791            // back that off to make the alternatives equivalent
4792            if (alwaysAskList.size() > 0) {
4793                for (ResolveInfo i : result) {
4794                    i.preferredOrder = 0;
4795                }
4796                result.addAll(alwaysAskList);
4797                includeBrowser = true;
4798            }
4799
4800            if (includeBrowser) {
4801                // Also add browsers (all of them or only the default one)
4802                if (DEBUG_DOMAIN_VERIFICATION) {
4803                    Slog.v(TAG, "   ...including browsers in candidate set");
4804                }
4805                if ((matchFlags & MATCH_ALL) != 0) {
4806                    result.addAll(matchAllList);
4807                } else {
4808                    // Browser/generic handling case.  If there's a default browser, go straight
4809                    // to that (but only if there is no other higher-priority match).
4810                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4811                    int maxMatchPrio = 0;
4812                    ResolveInfo defaultBrowserMatch = null;
4813                    final int numCandidates = matchAllList.size();
4814                    for (int n = 0; n < numCandidates; n++) {
4815                        ResolveInfo info = matchAllList.get(n);
4816                        // track the highest overall match priority...
4817                        if (info.priority > maxMatchPrio) {
4818                            maxMatchPrio = info.priority;
4819                        }
4820                        // ...and the highest-priority default browser match
4821                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4822                            if (defaultBrowserMatch == null
4823                                    || (defaultBrowserMatch.priority < info.priority)) {
4824                                if (debug) {
4825                                    Slog.v(TAG, "Considering default browser match " + info);
4826                                }
4827                                defaultBrowserMatch = info;
4828                            }
4829                        }
4830                    }
4831                    if (defaultBrowserMatch != null
4832                            && defaultBrowserMatch.priority >= maxMatchPrio
4833                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4834                    {
4835                        if (debug) {
4836                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4837                        }
4838                        result.add(defaultBrowserMatch);
4839                    } else {
4840                        result.addAll(matchAllList);
4841                    }
4842                }
4843
4844                // If there is nothing selected, add all candidates and remove the ones that the user
4845                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4846                if (result.size() == 0) {
4847                    result.addAll(candidates);
4848                    result.removeAll(neverList);
4849                }
4850            }
4851        }
4852        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4853            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4854                    result.size());
4855            for (ResolveInfo info : result) {
4856                Slog.v(TAG, "  + " + info.activityInfo);
4857            }
4858        }
4859        return result;
4860    }
4861
4862    // Returns a packed value as a long:
4863    //
4864    // high 'int'-sized word: link status: undefined/ask/never/always.
4865    // low 'int'-sized word: relative priority among 'always' results.
4866    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4867        long result = ps.getDomainVerificationStatusForUser(userId);
4868        // if none available, get the master status
4869        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4870            if (ps.getIntentFilterVerificationInfo() != null) {
4871                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4872            }
4873        }
4874        return result;
4875    }
4876
4877    private ResolveInfo querySkipCurrentProfileIntents(
4878            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4879            int flags, int sourceUserId) {
4880        if (matchingFilters != null) {
4881            int size = matchingFilters.size();
4882            for (int i = 0; i < size; i ++) {
4883                CrossProfileIntentFilter filter = matchingFilters.get(i);
4884                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4885                    // Checking if there are activities in the target user that can handle the
4886                    // intent.
4887                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4888                            flags, sourceUserId);
4889                    if (resolveInfo != null) {
4890                        return resolveInfo;
4891                    }
4892                }
4893            }
4894        }
4895        return null;
4896    }
4897
4898    // Return matching ResolveInfo if any for skip current profile intent filters.
4899    private ResolveInfo queryCrossProfileIntents(
4900            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4901            int flags, int sourceUserId) {
4902        if (matchingFilters != null) {
4903            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4904            // match the same intent. For performance reasons, it is better not to
4905            // run queryIntent twice for the same userId
4906            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4907            int size = matchingFilters.size();
4908            for (int i = 0; i < size; i++) {
4909                CrossProfileIntentFilter filter = matchingFilters.get(i);
4910                int targetUserId = filter.getTargetUserId();
4911                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4912                        && !alreadyTriedUserIds.get(targetUserId)) {
4913                    // Checking if there are activities in the target user that can handle the
4914                    // intent.
4915                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4916                            flags, sourceUserId);
4917                    if (resolveInfo != null) return resolveInfo;
4918                    alreadyTriedUserIds.put(targetUserId, true);
4919                }
4920            }
4921        }
4922        return null;
4923    }
4924
4925    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4926            String resolvedType, int flags, int sourceUserId) {
4927        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4928                resolvedType, flags, filter.getTargetUserId());
4929        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4930            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4931        }
4932        return null;
4933    }
4934
4935    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4936            int sourceUserId, int targetUserId) {
4937        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4938        String className;
4939        if (targetUserId == UserHandle.USER_OWNER) {
4940            className = FORWARD_INTENT_TO_USER_OWNER;
4941        } else {
4942            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4943        }
4944        ComponentName forwardingActivityComponentName = new ComponentName(
4945                mAndroidApplication.packageName, className);
4946        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4947                sourceUserId);
4948        if (targetUserId == UserHandle.USER_OWNER) {
4949            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4950            forwardingResolveInfo.noResourceId = true;
4951        }
4952        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4953        forwardingResolveInfo.priority = 0;
4954        forwardingResolveInfo.preferredOrder = 0;
4955        forwardingResolveInfo.match = 0;
4956        forwardingResolveInfo.isDefault = true;
4957        forwardingResolveInfo.filter = filter;
4958        forwardingResolveInfo.targetUserId = targetUserId;
4959        return forwardingResolveInfo;
4960    }
4961
4962    @Override
4963    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4964            Intent[] specifics, String[] specificTypes, Intent intent,
4965            String resolvedType, int flags, int userId) {
4966        if (!sUserManager.exists(userId)) return Collections.emptyList();
4967        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4968                false, "query intent activity options");
4969        final String resultsAction = intent.getAction();
4970
4971        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4972                | PackageManager.GET_RESOLVED_FILTER, userId);
4973
4974        if (DEBUG_INTENT_MATCHING) {
4975            Log.v(TAG, "Query " + intent + ": " + results);
4976        }
4977
4978        int specificsPos = 0;
4979        int N;
4980
4981        // todo: note that the algorithm used here is O(N^2).  This
4982        // isn't a problem in our current environment, but if we start running
4983        // into situations where we have more than 5 or 10 matches then this
4984        // should probably be changed to something smarter...
4985
4986        // First we go through and resolve each of the specific items
4987        // that were supplied, taking care of removing any corresponding
4988        // duplicate items in the generic resolve list.
4989        if (specifics != null) {
4990            for (int i=0; i<specifics.length; i++) {
4991                final Intent sintent = specifics[i];
4992                if (sintent == null) {
4993                    continue;
4994                }
4995
4996                if (DEBUG_INTENT_MATCHING) {
4997                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4998                }
4999
5000                String action = sintent.getAction();
5001                if (resultsAction != null && resultsAction.equals(action)) {
5002                    // If this action was explicitly requested, then don't
5003                    // remove things that have it.
5004                    action = null;
5005                }
5006
5007                ResolveInfo ri = null;
5008                ActivityInfo ai = null;
5009
5010                ComponentName comp = sintent.getComponent();
5011                if (comp == null) {
5012                    ri = resolveIntent(
5013                        sintent,
5014                        specificTypes != null ? specificTypes[i] : null,
5015                            flags, userId);
5016                    if (ri == null) {
5017                        continue;
5018                    }
5019                    if (ri == mResolveInfo) {
5020                        // ACK!  Must do something better with this.
5021                    }
5022                    ai = ri.activityInfo;
5023                    comp = new ComponentName(ai.applicationInfo.packageName,
5024                            ai.name);
5025                } else {
5026                    ai = getActivityInfo(comp, flags, userId);
5027                    if (ai == null) {
5028                        continue;
5029                    }
5030                }
5031
5032                // Look for any generic query activities that are duplicates
5033                // of this specific one, and remove them from the results.
5034                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5035                N = results.size();
5036                int j;
5037                for (j=specificsPos; j<N; j++) {
5038                    ResolveInfo sri = results.get(j);
5039                    if ((sri.activityInfo.name.equals(comp.getClassName())
5040                            && sri.activityInfo.applicationInfo.packageName.equals(
5041                                    comp.getPackageName()))
5042                        || (action != null && sri.filter.matchAction(action))) {
5043                        results.remove(j);
5044                        if (DEBUG_INTENT_MATCHING) Log.v(
5045                            TAG, "Removing duplicate item from " + j
5046                            + " due to specific " + specificsPos);
5047                        if (ri == null) {
5048                            ri = sri;
5049                        }
5050                        j--;
5051                        N--;
5052                    }
5053                }
5054
5055                // Add this specific item to its proper place.
5056                if (ri == null) {
5057                    ri = new ResolveInfo();
5058                    ri.activityInfo = ai;
5059                }
5060                results.add(specificsPos, ri);
5061                ri.specificIndex = i;
5062                specificsPos++;
5063            }
5064        }
5065
5066        // Now we go through the remaining generic results and remove any
5067        // duplicate actions that are found here.
5068        N = results.size();
5069        for (int i=specificsPos; i<N-1; i++) {
5070            final ResolveInfo rii = results.get(i);
5071            if (rii.filter == null) {
5072                continue;
5073            }
5074
5075            // Iterate over all of the actions of this result's intent
5076            // filter...  typically this should be just one.
5077            final Iterator<String> it = rii.filter.actionsIterator();
5078            if (it == null) {
5079                continue;
5080            }
5081            while (it.hasNext()) {
5082                final String action = it.next();
5083                if (resultsAction != null && resultsAction.equals(action)) {
5084                    // If this action was explicitly requested, then don't
5085                    // remove things that have it.
5086                    continue;
5087                }
5088                for (int j=i+1; j<N; j++) {
5089                    final ResolveInfo rij = results.get(j);
5090                    if (rij.filter != null && rij.filter.hasAction(action)) {
5091                        results.remove(j);
5092                        if (DEBUG_INTENT_MATCHING) Log.v(
5093                            TAG, "Removing duplicate item from " + j
5094                            + " due to action " + action + " at " + i);
5095                        j--;
5096                        N--;
5097                    }
5098                }
5099            }
5100
5101            // If the caller didn't request filter information, drop it now
5102            // so we don't have to marshall/unmarshall it.
5103            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5104                rii.filter = null;
5105            }
5106        }
5107
5108        // Filter out the caller activity if so requested.
5109        if (caller != null) {
5110            N = results.size();
5111            for (int i=0; i<N; i++) {
5112                ActivityInfo ainfo = results.get(i).activityInfo;
5113                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5114                        && caller.getClassName().equals(ainfo.name)) {
5115                    results.remove(i);
5116                    break;
5117                }
5118            }
5119        }
5120
5121        // If the caller didn't request filter information,
5122        // drop them now so we don't have to
5123        // marshall/unmarshall it.
5124        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5125            N = results.size();
5126            for (int i=0; i<N; i++) {
5127                results.get(i).filter = null;
5128            }
5129        }
5130
5131        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5132        return results;
5133    }
5134
5135    @Override
5136    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5137            int userId) {
5138        if (!sUserManager.exists(userId)) return Collections.emptyList();
5139        ComponentName comp = intent.getComponent();
5140        if (comp == null) {
5141            if (intent.getSelector() != null) {
5142                intent = intent.getSelector();
5143                comp = intent.getComponent();
5144            }
5145        }
5146        if (comp != null) {
5147            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5148            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5149            if (ai != null) {
5150                ResolveInfo ri = new ResolveInfo();
5151                ri.activityInfo = ai;
5152                list.add(ri);
5153            }
5154            return list;
5155        }
5156
5157        // reader
5158        synchronized (mPackages) {
5159            String pkgName = intent.getPackage();
5160            if (pkgName == null) {
5161                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5162            }
5163            final PackageParser.Package pkg = mPackages.get(pkgName);
5164            if (pkg != null) {
5165                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5166                        userId);
5167            }
5168            return null;
5169        }
5170    }
5171
5172    @Override
5173    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5174        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5175        if (!sUserManager.exists(userId)) return null;
5176        if (query != null) {
5177            if (query.size() >= 1) {
5178                // If there is more than one service with the same priority,
5179                // just arbitrarily pick the first one.
5180                return query.get(0);
5181            }
5182        }
5183        return null;
5184    }
5185
5186    @Override
5187    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5188            int userId) {
5189        if (!sUserManager.exists(userId)) return Collections.emptyList();
5190        ComponentName comp = intent.getComponent();
5191        if (comp == null) {
5192            if (intent.getSelector() != null) {
5193                intent = intent.getSelector();
5194                comp = intent.getComponent();
5195            }
5196        }
5197        if (comp != null) {
5198            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5199            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5200            if (si != null) {
5201                final ResolveInfo ri = new ResolveInfo();
5202                ri.serviceInfo = si;
5203                list.add(ri);
5204            }
5205            return list;
5206        }
5207
5208        // reader
5209        synchronized (mPackages) {
5210            String pkgName = intent.getPackage();
5211            if (pkgName == null) {
5212                return mServices.queryIntent(intent, resolvedType, flags, userId);
5213            }
5214            final PackageParser.Package pkg = mPackages.get(pkgName);
5215            if (pkg != null) {
5216                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5217                        userId);
5218            }
5219            return null;
5220        }
5221    }
5222
5223    @Override
5224    public List<ResolveInfo> queryIntentContentProviders(
5225            Intent intent, String resolvedType, int flags, int userId) {
5226        if (!sUserManager.exists(userId)) return Collections.emptyList();
5227        ComponentName comp = intent.getComponent();
5228        if (comp == null) {
5229            if (intent.getSelector() != null) {
5230                intent = intent.getSelector();
5231                comp = intent.getComponent();
5232            }
5233        }
5234        if (comp != null) {
5235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5236            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5237            if (pi != null) {
5238                final ResolveInfo ri = new ResolveInfo();
5239                ri.providerInfo = pi;
5240                list.add(ri);
5241            }
5242            return list;
5243        }
5244
5245        // reader
5246        synchronized (mPackages) {
5247            String pkgName = intent.getPackage();
5248            if (pkgName == null) {
5249                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5250            }
5251            final PackageParser.Package pkg = mPackages.get(pkgName);
5252            if (pkg != null) {
5253                return mProviders.queryIntentForPackage(
5254                        intent, resolvedType, flags, pkg.providers, userId);
5255            }
5256            return null;
5257        }
5258    }
5259
5260    @Override
5261    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5262        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5263
5264        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5265
5266        // writer
5267        synchronized (mPackages) {
5268            ArrayList<PackageInfo> list;
5269            if (listUninstalled) {
5270                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5271                for (PackageSetting ps : mSettings.mPackages.values()) {
5272                    PackageInfo pi;
5273                    if (ps.pkg != null) {
5274                        pi = generatePackageInfo(ps.pkg, flags, userId);
5275                    } else {
5276                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5277                    }
5278                    if (pi != null) {
5279                        list.add(pi);
5280                    }
5281                }
5282            } else {
5283                list = new ArrayList<PackageInfo>(mPackages.size());
5284                for (PackageParser.Package p : mPackages.values()) {
5285                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5286                    if (pi != null) {
5287                        list.add(pi);
5288                    }
5289                }
5290            }
5291
5292            return new ParceledListSlice<PackageInfo>(list);
5293        }
5294    }
5295
5296    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5297            String[] permissions, boolean[] tmp, int flags, int userId) {
5298        int numMatch = 0;
5299        final PermissionsState permissionsState = ps.getPermissionsState();
5300        for (int i=0; i<permissions.length; i++) {
5301            final String permission = permissions[i];
5302            if (permissionsState.hasPermission(permission, userId)) {
5303                tmp[i] = true;
5304                numMatch++;
5305            } else {
5306                tmp[i] = false;
5307            }
5308        }
5309        if (numMatch == 0) {
5310            return;
5311        }
5312        PackageInfo pi;
5313        if (ps.pkg != null) {
5314            pi = generatePackageInfo(ps.pkg, flags, userId);
5315        } else {
5316            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5317        }
5318        // The above might return null in cases of uninstalled apps or install-state
5319        // skew across users/profiles.
5320        if (pi != null) {
5321            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5322                if (numMatch == permissions.length) {
5323                    pi.requestedPermissions = permissions;
5324                } else {
5325                    pi.requestedPermissions = new String[numMatch];
5326                    numMatch = 0;
5327                    for (int i=0; i<permissions.length; i++) {
5328                        if (tmp[i]) {
5329                            pi.requestedPermissions[numMatch] = permissions[i];
5330                            numMatch++;
5331                        }
5332                    }
5333                }
5334            }
5335            list.add(pi);
5336        }
5337    }
5338
5339    @Override
5340    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5341            String[] permissions, int flags, int userId) {
5342        if (!sUserManager.exists(userId)) return null;
5343        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5344
5345        // writer
5346        synchronized (mPackages) {
5347            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5348            boolean[] tmpBools = new boolean[permissions.length];
5349            if (listUninstalled) {
5350                for (PackageSetting ps : mSettings.mPackages.values()) {
5351                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5352                }
5353            } else {
5354                for (PackageParser.Package pkg : mPackages.values()) {
5355                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5356                    if (ps != null) {
5357                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5358                                userId);
5359                    }
5360                }
5361            }
5362
5363            return new ParceledListSlice<PackageInfo>(list);
5364        }
5365    }
5366
5367    @Override
5368    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5369        if (!sUserManager.exists(userId)) return null;
5370        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5371
5372        // writer
5373        synchronized (mPackages) {
5374            ArrayList<ApplicationInfo> list;
5375            if (listUninstalled) {
5376                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5377                for (PackageSetting ps : mSettings.mPackages.values()) {
5378                    ApplicationInfo ai;
5379                    if (ps.pkg != null) {
5380                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5381                                ps.readUserState(userId), userId);
5382                    } else {
5383                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5384                    }
5385                    if (ai != null) {
5386                        list.add(ai);
5387                    }
5388                }
5389            } else {
5390                list = new ArrayList<ApplicationInfo>(mPackages.size());
5391                for (PackageParser.Package p : mPackages.values()) {
5392                    if (p.mExtras != null) {
5393                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5394                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5395                        if (ai != null) {
5396                            list.add(ai);
5397                        }
5398                    }
5399                }
5400            }
5401
5402            return new ParceledListSlice<ApplicationInfo>(list);
5403        }
5404    }
5405
5406    public List<ApplicationInfo> getPersistentApplications(int flags) {
5407        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5408
5409        // reader
5410        synchronized (mPackages) {
5411            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5412            final int userId = UserHandle.getCallingUserId();
5413            while (i.hasNext()) {
5414                final PackageParser.Package p = i.next();
5415                if (p.applicationInfo != null
5416                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5417                        && (!mSafeMode || isSystemApp(p))) {
5418                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5419                    if (ps != null) {
5420                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5421                                ps.readUserState(userId), userId);
5422                        if (ai != null) {
5423                            finalList.add(ai);
5424                        }
5425                    }
5426                }
5427            }
5428        }
5429
5430        return finalList;
5431    }
5432
5433    @Override
5434    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5435        if (!sUserManager.exists(userId)) return null;
5436        // reader
5437        synchronized (mPackages) {
5438            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5439            PackageSetting ps = provider != null
5440                    ? mSettings.mPackages.get(provider.owner.packageName)
5441                    : null;
5442            return ps != null
5443                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5444                    && (!mSafeMode || (provider.info.applicationInfo.flags
5445                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5446                    ? PackageParser.generateProviderInfo(provider, flags,
5447                            ps.readUserState(userId), userId)
5448                    : null;
5449        }
5450    }
5451
5452    /**
5453     * @deprecated
5454     */
5455    @Deprecated
5456    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5457        // reader
5458        synchronized (mPackages) {
5459            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5460                    .entrySet().iterator();
5461            final int userId = UserHandle.getCallingUserId();
5462            while (i.hasNext()) {
5463                Map.Entry<String, PackageParser.Provider> entry = i.next();
5464                PackageParser.Provider p = entry.getValue();
5465                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5466
5467                if (ps != null && p.syncable
5468                        && (!mSafeMode || (p.info.applicationInfo.flags
5469                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5470                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5471                            ps.readUserState(userId), userId);
5472                    if (info != null) {
5473                        outNames.add(entry.getKey());
5474                        outInfo.add(info);
5475                    }
5476                }
5477            }
5478        }
5479    }
5480
5481    @Override
5482    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5483            int uid, int flags) {
5484        ArrayList<ProviderInfo> finalList = null;
5485        // reader
5486        synchronized (mPackages) {
5487            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5488            final int userId = processName != null ?
5489                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5490            while (i.hasNext()) {
5491                final PackageParser.Provider p = i.next();
5492                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5493                if (ps != null && p.info.authority != null
5494                        && (processName == null
5495                                || (p.info.processName.equals(processName)
5496                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5497                        && mSettings.isEnabledLPr(p.info, flags, userId)
5498                        && (!mSafeMode
5499                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5500                    if (finalList == null) {
5501                        finalList = new ArrayList<ProviderInfo>(3);
5502                    }
5503                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5504                            ps.readUserState(userId), userId);
5505                    if (info != null) {
5506                        finalList.add(info);
5507                    }
5508                }
5509            }
5510        }
5511
5512        if (finalList != null) {
5513            Collections.sort(finalList, mProviderInitOrderSorter);
5514            return new ParceledListSlice<ProviderInfo>(finalList);
5515        }
5516
5517        return null;
5518    }
5519
5520    @Override
5521    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5522            int flags) {
5523        // reader
5524        synchronized (mPackages) {
5525            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5526            return PackageParser.generateInstrumentationInfo(i, flags);
5527        }
5528    }
5529
5530    @Override
5531    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5532            int flags) {
5533        ArrayList<InstrumentationInfo> finalList =
5534            new ArrayList<InstrumentationInfo>();
5535
5536        // reader
5537        synchronized (mPackages) {
5538            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5539            while (i.hasNext()) {
5540                final PackageParser.Instrumentation p = i.next();
5541                if (targetPackage == null
5542                        || targetPackage.equals(p.info.targetPackage)) {
5543                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5544                            flags);
5545                    if (ii != null) {
5546                        finalList.add(ii);
5547                    }
5548                }
5549            }
5550        }
5551
5552        return finalList;
5553    }
5554
5555    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5556        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5557        if (overlays == null) {
5558            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5559            return;
5560        }
5561        for (PackageParser.Package opkg : overlays.values()) {
5562            // Not much to do if idmap fails: we already logged the error
5563            // and we certainly don't want to abort installation of pkg simply
5564            // because an overlay didn't fit properly. For these reasons,
5565            // ignore the return value of createIdmapForPackagePairLI.
5566            createIdmapForPackagePairLI(pkg, opkg);
5567        }
5568    }
5569
5570    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5571            PackageParser.Package opkg) {
5572        if (!opkg.mTrustedOverlay) {
5573            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5574                    opkg.baseCodePath + ": overlay not trusted");
5575            return false;
5576        }
5577        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5578        if (overlaySet == null) {
5579            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5580                    opkg.baseCodePath + " but target package has no known overlays");
5581            return false;
5582        }
5583        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5584        // TODO: generate idmap for split APKs
5585        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5586            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5587                    + opkg.baseCodePath);
5588            return false;
5589        }
5590        PackageParser.Package[] overlayArray =
5591            overlaySet.values().toArray(new PackageParser.Package[0]);
5592        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5593            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5594                return p1.mOverlayPriority - p2.mOverlayPriority;
5595            }
5596        };
5597        Arrays.sort(overlayArray, cmp);
5598
5599        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5600        int i = 0;
5601        for (PackageParser.Package p : overlayArray) {
5602            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5603        }
5604        return true;
5605    }
5606
5607    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5608        final File[] files = dir.listFiles();
5609        if (ArrayUtils.isEmpty(files)) {
5610            Log.d(TAG, "No files in app dir " + dir);
5611            return;
5612        }
5613
5614        if (DEBUG_PACKAGE_SCANNING) {
5615            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5616                    + " flags=0x" + Integer.toHexString(parseFlags));
5617        }
5618
5619        for (File file : files) {
5620            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5621                    && !PackageInstallerService.isStageName(file.getName());
5622            if (!isPackage) {
5623                // Ignore entries which are not packages
5624                continue;
5625            }
5626            try {
5627                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5628                        scanFlags, currentTime, null);
5629            } catch (PackageManagerException e) {
5630                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5631
5632                // Delete invalid userdata apps
5633                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5634                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5635                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5636                    if (file.isDirectory()) {
5637                        mInstaller.rmPackageDir(file.getAbsolutePath());
5638                    } else {
5639                        file.delete();
5640                    }
5641                }
5642            }
5643        }
5644    }
5645
5646    private static File getSettingsProblemFile() {
5647        File dataDir = Environment.getDataDirectory();
5648        File systemDir = new File(dataDir, "system");
5649        File fname = new File(systemDir, "uiderrors.txt");
5650        return fname;
5651    }
5652
5653    static void reportSettingsProblem(int priority, String msg) {
5654        logCriticalInfo(priority, msg);
5655    }
5656
5657    static void logCriticalInfo(int priority, String msg) {
5658        Slog.println(priority, TAG, msg);
5659        EventLogTags.writePmCriticalInfo(msg);
5660        try {
5661            File fname = getSettingsProblemFile();
5662            FileOutputStream out = new FileOutputStream(fname, true);
5663            PrintWriter pw = new FastPrintWriter(out);
5664            SimpleDateFormat formatter = new SimpleDateFormat();
5665            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5666            pw.println(dateString + ": " + msg);
5667            pw.close();
5668            FileUtils.setPermissions(
5669                    fname.toString(),
5670                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5671                    -1, -1);
5672        } catch (java.io.IOException e) {
5673        }
5674    }
5675
5676    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5677            PackageParser.Package pkg, File srcFile, int parseFlags)
5678            throws PackageManagerException {
5679        if (ps != null
5680                && ps.codePath.equals(srcFile)
5681                && ps.timeStamp == srcFile.lastModified()
5682                && !isCompatSignatureUpdateNeeded(pkg)
5683                && !isRecoverSignatureUpdateNeeded(pkg)) {
5684            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5685            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5686            ArraySet<PublicKey> signingKs;
5687            synchronized (mPackages) {
5688                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5689            }
5690            if (ps.signatures.mSignatures != null
5691                    && ps.signatures.mSignatures.length != 0
5692                    && signingKs != null) {
5693                // Optimization: reuse the existing cached certificates
5694                // if the package appears to be unchanged.
5695                pkg.mSignatures = ps.signatures.mSignatures;
5696                pkg.mSigningKeys = signingKs;
5697                return;
5698            }
5699
5700            Slog.w(TAG, "PackageSetting for " + ps.name
5701                    + " is missing signatures.  Collecting certs again to recover them.");
5702        } else {
5703            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5704        }
5705
5706        try {
5707            pp.collectCertificates(pkg, parseFlags);
5708            pp.collectManifestDigest(pkg);
5709        } catch (PackageParserException e) {
5710            throw PackageManagerException.from(e);
5711        }
5712    }
5713
5714    /*
5715     *  Scan a package and return the newly parsed package.
5716     *  Returns null in case of errors and the error code is stored in mLastScanError
5717     */
5718    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5719            long currentTime, UserHandle user) throws PackageManagerException {
5720        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5721        parseFlags |= mDefParseFlags;
5722        PackageParser pp = new PackageParser();
5723        pp.setSeparateProcesses(mSeparateProcesses);
5724        pp.setOnlyCoreApps(mOnlyCore);
5725        pp.setDisplayMetrics(mMetrics);
5726
5727        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5728            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5729        }
5730
5731        final PackageParser.Package pkg;
5732        try {
5733            pkg = pp.parsePackage(scanFile, parseFlags);
5734        } catch (PackageParserException e) {
5735            throw PackageManagerException.from(e);
5736        }
5737
5738        PackageSetting ps = null;
5739        PackageSetting updatedPkg;
5740        // reader
5741        synchronized (mPackages) {
5742            // Look to see if we already know about this package.
5743            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5744            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5745                // This package has been renamed to its original name.  Let's
5746                // use that.
5747                ps = mSettings.peekPackageLPr(oldName);
5748            }
5749            // If there was no original package, see one for the real package name.
5750            if (ps == null) {
5751                ps = mSettings.peekPackageLPr(pkg.packageName);
5752            }
5753            // Check to see if this package could be hiding/updating a system
5754            // package.  Must look for it either under the original or real
5755            // package name depending on our state.
5756            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5757            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5758        }
5759        boolean updatedPkgBetter = false;
5760        // First check if this is a system package that may involve an update
5761        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5762            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5763            // it needs to drop FLAG_PRIVILEGED.
5764            if (locationIsPrivileged(scanFile)) {
5765                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5766            } else {
5767                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5768            }
5769
5770            if (ps != null && !ps.codePath.equals(scanFile)) {
5771                // The path has changed from what was last scanned...  check the
5772                // version of the new path against what we have stored to determine
5773                // what to do.
5774                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5775                if (pkg.mVersionCode <= ps.versionCode) {
5776                    // The system package has been updated and the code path does not match
5777                    // Ignore entry. Skip it.
5778                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5779                            + " ignored: updated version " + ps.versionCode
5780                            + " better than this " + pkg.mVersionCode);
5781                    if (!updatedPkg.codePath.equals(scanFile)) {
5782                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5783                                + ps.name + " changing from " + updatedPkg.codePathString
5784                                + " to " + scanFile);
5785                        updatedPkg.codePath = scanFile;
5786                        updatedPkg.codePathString = scanFile.toString();
5787                        updatedPkg.resourcePath = scanFile;
5788                        updatedPkg.resourcePathString = scanFile.toString();
5789                    }
5790                    updatedPkg.pkg = pkg;
5791                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5792                            "Package " + ps.name + " at " + scanFile
5793                                    + " ignored: updated version " + ps.versionCode
5794                                    + " better than this " + pkg.mVersionCode);
5795                } else {
5796                    // The current app on the system partition is better than
5797                    // what we have updated to on the data partition; switch
5798                    // back to the system partition version.
5799                    // At this point, its safely assumed that package installation for
5800                    // apps in system partition will go through. If not there won't be a working
5801                    // version of the app
5802                    // writer
5803                    synchronized (mPackages) {
5804                        // Just remove the loaded entries from package lists.
5805                        mPackages.remove(ps.name);
5806                    }
5807
5808                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5809                            + " reverting from " + ps.codePathString
5810                            + ": new version " + pkg.mVersionCode
5811                            + " better than installed " + ps.versionCode);
5812
5813                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5814                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5815                    synchronized (mInstallLock) {
5816                        args.cleanUpResourcesLI();
5817                    }
5818                    synchronized (mPackages) {
5819                        mSettings.enableSystemPackageLPw(ps.name);
5820                    }
5821                    updatedPkgBetter = true;
5822                }
5823            }
5824        }
5825
5826        if (updatedPkg != null) {
5827            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5828            // initially
5829            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5830
5831            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5832            // flag set initially
5833            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5834                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5835            }
5836        }
5837
5838        // Verify certificates against what was last scanned
5839        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5840
5841        /*
5842         * A new system app appeared, but we already had a non-system one of the
5843         * same name installed earlier.
5844         */
5845        boolean shouldHideSystemApp = false;
5846        if (updatedPkg == null && ps != null
5847                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5848            /*
5849             * Check to make sure the signatures match first. If they don't,
5850             * wipe the installed application and its data.
5851             */
5852            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5853                    != PackageManager.SIGNATURE_MATCH) {
5854                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5855                        + " signatures don't match existing userdata copy; removing");
5856                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5857                ps = null;
5858            } else {
5859                /*
5860                 * If the newly-added system app is an older version than the
5861                 * already installed version, hide it. It will be scanned later
5862                 * and re-added like an update.
5863                 */
5864                if (pkg.mVersionCode <= ps.versionCode) {
5865                    shouldHideSystemApp = true;
5866                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5867                            + " but new version " + pkg.mVersionCode + " better than installed "
5868                            + ps.versionCode + "; hiding system");
5869                } else {
5870                    /*
5871                     * The newly found system app is a newer version that the
5872                     * one previously installed. Simply remove the
5873                     * already-installed application and replace it with our own
5874                     * while keeping the application data.
5875                     */
5876                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5877                            + " reverting from " + ps.codePathString + ": new version "
5878                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5879                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5880                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5881                    synchronized (mInstallLock) {
5882                        args.cleanUpResourcesLI();
5883                    }
5884                }
5885            }
5886        }
5887
5888        // The apk is forward locked (not public) if its code and resources
5889        // are kept in different files. (except for app in either system or
5890        // vendor path).
5891        // TODO grab this value from PackageSettings
5892        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5893            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5894                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5895            }
5896        }
5897
5898        // TODO: extend to support forward-locked splits
5899        String resourcePath = null;
5900        String baseResourcePath = null;
5901        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5902            if (ps != null && ps.resourcePathString != null) {
5903                resourcePath = ps.resourcePathString;
5904                baseResourcePath = ps.resourcePathString;
5905            } else {
5906                // Should not happen at all. Just log an error.
5907                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5908            }
5909        } else {
5910            resourcePath = pkg.codePath;
5911            baseResourcePath = pkg.baseCodePath;
5912        }
5913
5914        // Set application objects path explicitly.
5915        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5916        pkg.applicationInfo.setCodePath(pkg.codePath);
5917        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5918        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5919        pkg.applicationInfo.setResourcePath(resourcePath);
5920        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5921        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5922
5923        // Note that we invoke the following method only if we are about to unpack an application
5924        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5925                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5926
5927        /*
5928         * If the system app should be overridden by a previously installed
5929         * data, hide the system app now and let the /data/app scan pick it up
5930         * again.
5931         */
5932        if (shouldHideSystemApp) {
5933            synchronized (mPackages) {
5934                mSettings.disableSystemPackageLPw(pkg.packageName);
5935            }
5936        }
5937
5938        return scannedPkg;
5939    }
5940
5941    private static String fixProcessName(String defProcessName,
5942            String processName, int uid) {
5943        if (processName == null) {
5944            return defProcessName;
5945        }
5946        return processName;
5947    }
5948
5949    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5950            throws PackageManagerException {
5951        if (pkgSetting.signatures.mSignatures != null) {
5952            // Already existing package. Make sure signatures match
5953            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5954                    == PackageManager.SIGNATURE_MATCH;
5955            if (!match) {
5956                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5957                        == PackageManager.SIGNATURE_MATCH;
5958            }
5959            if (!match) {
5960                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5961                        == PackageManager.SIGNATURE_MATCH;
5962            }
5963            if (!match) {
5964                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5965                        + pkg.packageName + " signatures do not match the "
5966                        + "previously installed version; ignoring!");
5967            }
5968        }
5969
5970        // Check for shared user signatures
5971        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5972            // Already existing package. Make sure signatures match
5973            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5974                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5975            if (!match) {
5976                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5977                        == PackageManager.SIGNATURE_MATCH;
5978            }
5979            if (!match) {
5980                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5981                        == PackageManager.SIGNATURE_MATCH;
5982            }
5983            if (!match) {
5984                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5985                        "Package " + pkg.packageName
5986                        + " has no signatures that match those in shared user "
5987                        + pkgSetting.sharedUser.name + "; ignoring!");
5988            }
5989        }
5990    }
5991
5992    /**
5993     * Enforces that only the system UID or root's UID can call a method exposed
5994     * via Binder.
5995     *
5996     * @param message used as message if SecurityException is thrown
5997     * @throws SecurityException if the caller is not system or root
5998     */
5999    private static final void enforceSystemOrRoot(String message) {
6000        final int uid = Binder.getCallingUid();
6001        if (uid != Process.SYSTEM_UID && uid != 0) {
6002            throw new SecurityException(message);
6003        }
6004    }
6005
6006    @Override
6007    public void performBootDexOpt() {
6008        enforceSystemOrRoot("Only the system can request dexopt be performed");
6009
6010        // Before everything else, see whether we need to fstrim.
6011        try {
6012            IMountService ms = PackageHelper.getMountService();
6013            if (ms != null) {
6014                final boolean isUpgrade = isUpgrade();
6015                boolean doTrim = isUpgrade;
6016                if (doTrim) {
6017                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6018                } else {
6019                    final long interval = android.provider.Settings.Global.getLong(
6020                            mContext.getContentResolver(),
6021                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6022                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6023                    if (interval > 0) {
6024                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6025                        if (timeSinceLast > interval) {
6026                            doTrim = true;
6027                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6028                                    + "; running immediately");
6029                        }
6030                    }
6031                }
6032                if (doTrim) {
6033                    if (!isFirstBoot()) {
6034                        try {
6035                            ActivityManagerNative.getDefault().showBootMessage(
6036                                    mContext.getResources().getString(
6037                                            R.string.android_upgrading_fstrim), true);
6038                        } catch (RemoteException e) {
6039                        }
6040                    }
6041                    ms.runMaintenance();
6042                }
6043            } else {
6044                Slog.e(TAG, "Mount service unavailable!");
6045            }
6046        } catch (RemoteException e) {
6047            // Can't happen; MountService is local
6048        }
6049
6050        final ArraySet<PackageParser.Package> pkgs;
6051        synchronized (mPackages) {
6052            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6053        }
6054
6055        if (pkgs != null) {
6056            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6057            // in case the device runs out of space.
6058            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6059            // Give priority to core apps.
6060            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6061                PackageParser.Package pkg = it.next();
6062                if (pkg.coreApp) {
6063                    if (DEBUG_DEXOPT) {
6064                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6065                    }
6066                    sortedPkgs.add(pkg);
6067                    it.remove();
6068                }
6069            }
6070            // Give priority to system apps that listen for pre boot complete.
6071            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6072            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6073            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6074                PackageParser.Package pkg = it.next();
6075                if (pkgNames.contains(pkg.packageName)) {
6076                    if (DEBUG_DEXOPT) {
6077                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6078                    }
6079                    sortedPkgs.add(pkg);
6080                    it.remove();
6081                }
6082            }
6083            // Filter out packages that aren't recently used.
6084            filterRecentlyUsedApps(pkgs);
6085            // Add all remaining apps.
6086            for (PackageParser.Package pkg : pkgs) {
6087                if (DEBUG_DEXOPT) {
6088                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6089                }
6090                sortedPkgs.add(pkg);
6091            }
6092
6093            // If we want to be lazy, filter everything that wasn't recently used.
6094            if (mLazyDexOpt) {
6095                filterRecentlyUsedApps(sortedPkgs);
6096            }
6097
6098            int i = 0;
6099            int total = sortedPkgs.size();
6100            File dataDir = Environment.getDataDirectory();
6101            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6102            if (lowThreshold == 0) {
6103                throw new IllegalStateException("Invalid low memory threshold");
6104            }
6105            for (PackageParser.Package pkg : sortedPkgs) {
6106                long usableSpace = dataDir.getUsableSpace();
6107                if (usableSpace < lowThreshold) {
6108                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6109                    break;
6110                }
6111                performBootDexOpt(pkg, ++i, total);
6112            }
6113        }
6114    }
6115
6116    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6117        // Filter out packages that aren't recently used.
6118        //
6119        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6120        // should do a full dexopt.
6121        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6122            int total = pkgs.size();
6123            int skipped = 0;
6124            long now = System.currentTimeMillis();
6125            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6126                PackageParser.Package pkg = i.next();
6127                long then = pkg.mLastPackageUsageTimeInMills;
6128                if (then + mDexOptLRUThresholdInMills < now) {
6129                    if (DEBUG_DEXOPT) {
6130                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6131                              ((then == 0) ? "never" : new Date(then)));
6132                    }
6133                    i.remove();
6134                    skipped++;
6135                }
6136            }
6137            if (DEBUG_DEXOPT) {
6138                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6139            }
6140        }
6141    }
6142
6143    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6144        List<ResolveInfo> ris = null;
6145        try {
6146            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6147                    intent, null, 0, UserHandle.USER_OWNER);
6148        } catch (RemoteException e) {
6149        }
6150        ArraySet<String> pkgNames = new ArraySet<String>();
6151        if (ris != null) {
6152            for (ResolveInfo ri : ris) {
6153                pkgNames.add(ri.activityInfo.packageName);
6154            }
6155        }
6156        return pkgNames;
6157    }
6158
6159    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6160        if (DEBUG_DEXOPT) {
6161            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6162        }
6163        if (!isFirstBoot()) {
6164            try {
6165                ActivityManagerNative.getDefault().showBootMessage(
6166                        mContext.getResources().getString(R.string.android_upgrading_apk,
6167                                curr, total), true);
6168            } catch (RemoteException e) {
6169            }
6170        }
6171        PackageParser.Package p = pkg;
6172        synchronized (mInstallLock) {
6173            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6174                    false /* force dex */, false /* defer */, true /* include dependencies */,
6175                    false /* boot complete */, false /*useJit*/);
6176        }
6177    }
6178
6179    @Override
6180    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6181        return performDexOpt(packageName, instructionSet, false);
6182    }
6183
6184    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6185        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6186        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6187        if (!dexopt && !updateUsage) {
6188            // We aren't going to dexopt or update usage, so bail early.
6189            return false;
6190        }
6191        PackageParser.Package p;
6192        final String targetInstructionSet;
6193        synchronized (mPackages) {
6194            p = mPackages.get(packageName);
6195            if (p == null) {
6196                return false;
6197            }
6198            if (updateUsage) {
6199                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6200            }
6201            mPackageUsage.write(false);
6202            if (!dexopt) {
6203                // We aren't going to dexopt, so bail early.
6204                return false;
6205            }
6206
6207            targetInstructionSet = instructionSet != null ? instructionSet :
6208                    getPrimaryInstructionSet(p.applicationInfo);
6209            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6210                return false;
6211            }
6212        }
6213        long callingId = Binder.clearCallingIdentity();
6214        try {
6215            synchronized (mInstallLock) {
6216                final String[] instructionSets = new String[] { targetInstructionSet };
6217                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6218                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6219                        true /* boot complete */, false /*useJit*/);
6220                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6221            }
6222        } finally {
6223            Binder.restoreCallingIdentity(callingId);
6224        }
6225    }
6226
6227    public ArraySet<String> getPackagesThatNeedDexOpt() {
6228        ArraySet<String> pkgs = null;
6229        synchronized (mPackages) {
6230            for (PackageParser.Package p : mPackages.values()) {
6231                if (DEBUG_DEXOPT) {
6232                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6233                }
6234                if (!p.mDexOptPerformed.isEmpty()) {
6235                    continue;
6236                }
6237                if (pkgs == null) {
6238                    pkgs = new ArraySet<String>();
6239                }
6240                pkgs.add(p.packageName);
6241            }
6242        }
6243        return pkgs;
6244    }
6245
6246    public void shutdown() {
6247        mPackageUsage.write(true);
6248    }
6249
6250    @Override
6251    public void forceDexOpt(String packageName) {
6252        enforceSystemOrRoot("forceDexOpt");
6253
6254        PackageParser.Package pkg;
6255        synchronized (mPackages) {
6256            pkg = mPackages.get(packageName);
6257            if (pkg == null) {
6258                throw new IllegalArgumentException("Missing package: " + packageName);
6259            }
6260        }
6261
6262        synchronized (mInstallLock) {
6263            final String[] instructionSets = new String[] {
6264                    getPrimaryInstructionSet(pkg.applicationInfo) };
6265            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6266                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6267                    true /* boot complete */, false /*useJit*/);
6268            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6269                throw new IllegalStateException("Failed to dexopt: " + res);
6270            }
6271        }
6272    }
6273
6274    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6275        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6276            Slog.w(TAG, "Unable to update from " + oldPkg.name
6277                    + " to " + newPkg.packageName
6278                    + ": old package not in system partition");
6279            return false;
6280        } else if (mPackages.get(oldPkg.name) != null) {
6281            Slog.w(TAG, "Unable to update from " + oldPkg.name
6282                    + " to " + newPkg.packageName
6283                    + ": old package still exists");
6284            return false;
6285        }
6286        return true;
6287    }
6288
6289    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6290        int[] users = sUserManager.getUserIds();
6291        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6292        if (res < 0) {
6293            return res;
6294        }
6295        for (int user : users) {
6296            if (user != 0) {
6297                res = mInstaller.createUserData(volumeUuid, packageName,
6298                        UserHandle.getUid(user, uid), user, seinfo);
6299                if (res < 0) {
6300                    return res;
6301                }
6302            }
6303        }
6304        return res;
6305    }
6306
6307    private int removeDataDirsLI(String volumeUuid, String packageName) {
6308        int[] users = sUserManager.getUserIds();
6309        int res = 0;
6310        for (int user : users) {
6311            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6312            if (resInner < 0) {
6313                res = resInner;
6314            }
6315        }
6316
6317        return res;
6318    }
6319
6320    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6321        int[] users = sUserManager.getUserIds();
6322        int res = 0;
6323        for (int user : users) {
6324            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6325            if (resInner < 0) {
6326                res = resInner;
6327            }
6328        }
6329        return res;
6330    }
6331
6332    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6333            PackageParser.Package changingLib) {
6334        if (file.path != null) {
6335            usesLibraryFiles.add(file.path);
6336            return;
6337        }
6338        PackageParser.Package p = mPackages.get(file.apk);
6339        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6340            // If we are doing this while in the middle of updating a library apk,
6341            // then we need to make sure to use that new apk for determining the
6342            // dependencies here.  (We haven't yet finished committing the new apk
6343            // to the package manager state.)
6344            if (p == null || p.packageName.equals(changingLib.packageName)) {
6345                p = changingLib;
6346            }
6347        }
6348        if (p != null) {
6349            usesLibraryFiles.addAll(p.getAllCodePaths());
6350        }
6351    }
6352
6353    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6354            PackageParser.Package changingLib) throws PackageManagerException {
6355        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6356            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6357            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6358            for (int i=0; i<N; i++) {
6359                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6360                if (file == null) {
6361                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6362                            "Package " + pkg.packageName + " requires unavailable shared library "
6363                            + pkg.usesLibraries.get(i) + "; failing!");
6364                }
6365                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6366            }
6367            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6368            for (int i=0; i<N; i++) {
6369                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6370                if (file == null) {
6371                    Slog.w(TAG, "Package " + pkg.packageName
6372                            + " desires unavailable shared library "
6373                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6374                } else {
6375                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6376                }
6377            }
6378            N = usesLibraryFiles.size();
6379            if (N > 0) {
6380                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6381            } else {
6382                pkg.usesLibraryFiles = null;
6383            }
6384        }
6385    }
6386
6387    private static boolean hasString(List<String> list, List<String> which) {
6388        if (list == null) {
6389            return false;
6390        }
6391        for (int i=list.size()-1; i>=0; i--) {
6392            for (int j=which.size()-1; j>=0; j--) {
6393                if (which.get(j).equals(list.get(i))) {
6394                    return true;
6395                }
6396            }
6397        }
6398        return false;
6399    }
6400
6401    private void updateAllSharedLibrariesLPw() {
6402        for (PackageParser.Package pkg : mPackages.values()) {
6403            try {
6404                updateSharedLibrariesLPw(pkg, null);
6405            } catch (PackageManagerException e) {
6406                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6407            }
6408        }
6409    }
6410
6411    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6412            PackageParser.Package changingPkg) {
6413        ArrayList<PackageParser.Package> res = null;
6414        for (PackageParser.Package pkg : mPackages.values()) {
6415            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6416                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6417                if (res == null) {
6418                    res = new ArrayList<PackageParser.Package>();
6419                }
6420                res.add(pkg);
6421                try {
6422                    updateSharedLibrariesLPw(pkg, changingPkg);
6423                } catch (PackageManagerException e) {
6424                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6425                }
6426            }
6427        }
6428        return res;
6429    }
6430
6431    /**
6432     * Derive the value of the {@code cpuAbiOverride} based on the provided
6433     * value and an optional stored value from the package settings.
6434     */
6435    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6436        String cpuAbiOverride = null;
6437
6438        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6439            cpuAbiOverride = null;
6440        } else if (abiOverride != null) {
6441            cpuAbiOverride = abiOverride;
6442        } else if (settings != null) {
6443            cpuAbiOverride = settings.cpuAbiOverrideString;
6444        }
6445
6446        return cpuAbiOverride;
6447    }
6448
6449    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6450            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6451        boolean success = false;
6452        try {
6453            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6454                    currentTime, user);
6455            success = true;
6456            return res;
6457        } finally {
6458            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6459                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6460            }
6461        }
6462    }
6463
6464    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6465            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6466        final File scanFile = new File(pkg.codePath);
6467        if (pkg.applicationInfo.getCodePath() == null ||
6468                pkg.applicationInfo.getResourcePath() == null) {
6469            // Bail out. The resource and code paths haven't been set.
6470            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6471                    "Code and resource paths haven't been set correctly");
6472        }
6473
6474        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6475            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6476        } else {
6477            // Only allow system apps to be flagged as core apps.
6478            pkg.coreApp = false;
6479        }
6480
6481        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6482            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6483        }
6484
6485        if (mCustomResolverComponentName != null &&
6486                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6487            setUpCustomResolverActivity(pkg);
6488        }
6489
6490        if (pkg.packageName.equals("android")) {
6491            synchronized (mPackages) {
6492                if (mAndroidApplication != null) {
6493                    Slog.w(TAG, "*************************************************");
6494                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6495                    Slog.w(TAG, " file=" + scanFile);
6496                    Slog.w(TAG, "*************************************************");
6497                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6498                            "Core android package being redefined.  Skipping.");
6499                }
6500
6501                // Set up information for our fall-back user intent resolution activity.
6502                mPlatformPackage = pkg;
6503                pkg.mVersionCode = mSdkVersion;
6504                mAndroidApplication = pkg.applicationInfo;
6505
6506                if (!mResolverReplaced) {
6507                    mResolveActivity.applicationInfo = mAndroidApplication;
6508                    mResolveActivity.name = ResolverActivity.class.getName();
6509                    mResolveActivity.packageName = mAndroidApplication.packageName;
6510                    mResolveActivity.processName = "system:ui";
6511                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6512                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6513                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6514                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6515                    mResolveActivity.exported = true;
6516                    mResolveActivity.enabled = true;
6517                    mResolveInfo.activityInfo = mResolveActivity;
6518                    mResolveInfo.priority = 0;
6519                    mResolveInfo.preferredOrder = 0;
6520                    mResolveInfo.match = 0;
6521                    mResolveComponentName = new ComponentName(
6522                            mAndroidApplication.packageName, mResolveActivity.name);
6523                }
6524            }
6525        }
6526
6527        if (DEBUG_PACKAGE_SCANNING) {
6528            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6529                Log.d(TAG, "Scanning package " + pkg.packageName);
6530        }
6531
6532        if (mPackages.containsKey(pkg.packageName)
6533                || mSharedLibraries.containsKey(pkg.packageName)) {
6534            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6535                    "Application package " + pkg.packageName
6536                    + " already installed.  Skipping duplicate.");
6537        }
6538
6539        // If we're only installing presumed-existing packages, require that the
6540        // scanned APK is both already known and at the path previously established
6541        // for it.  Previously unknown packages we pick up normally, but if we have an
6542        // a priori expectation about this package's install presence, enforce it.
6543        // With a singular exception for new system packages. When an OTA contains
6544        // a new system package, we allow the codepath to change from a system location
6545        // to the user-installed location. If we don't allow this change, any newer,
6546        // user-installed version of the application will be ignored.
6547        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6548            if (mExpectingBetter.containsKey(pkg.packageName)) {
6549                logCriticalInfo(Log.WARN,
6550                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6551            } else {
6552                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6553                if (known != null) {
6554                    if (DEBUG_PACKAGE_SCANNING) {
6555                        Log.d(TAG, "Examining " + pkg.codePath
6556                                + " and requiring known paths " + known.codePathString
6557                                + " & " + known.resourcePathString);
6558                    }
6559                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6560                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6561                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6562                                "Application package " + pkg.packageName
6563                                + " found at " + pkg.applicationInfo.getCodePath()
6564                                + " but expected at " + known.codePathString + "; ignoring.");
6565                    }
6566                }
6567            }
6568        }
6569
6570        // Initialize package source and resource directories
6571        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6572        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6573
6574        SharedUserSetting suid = null;
6575        PackageSetting pkgSetting = null;
6576
6577        if (!isSystemApp(pkg)) {
6578            // Only system apps can use these features.
6579            pkg.mOriginalPackages = null;
6580            pkg.mRealPackage = null;
6581            pkg.mAdoptPermissions = null;
6582        }
6583
6584        // writer
6585        synchronized (mPackages) {
6586            if (pkg.mSharedUserId != null) {
6587                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6588                if (suid == null) {
6589                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6590                            "Creating application package " + pkg.packageName
6591                            + " for shared user failed");
6592                }
6593                if (DEBUG_PACKAGE_SCANNING) {
6594                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6595                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6596                                + "): packages=" + suid.packages);
6597                }
6598            }
6599
6600            // Check if we are renaming from an original package name.
6601            PackageSetting origPackage = null;
6602            String realName = null;
6603            if (pkg.mOriginalPackages != null) {
6604                // This package may need to be renamed to a previously
6605                // installed name.  Let's check on that...
6606                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6607                if (pkg.mOriginalPackages.contains(renamed)) {
6608                    // This package had originally been installed as the
6609                    // original name, and we have already taken care of
6610                    // transitioning to the new one.  Just update the new
6611                    // one to continue using the old name.
6612                    realName = pkg.mRealPackage;
6613                    if (!pkg.packageName.equals(renamed)) {
6614                        // Callers into this function may have already taken
6615                        // care of renaming the package; only do it here if
6616                        // it is not already done.
6617                        pkg.setPackageName(renamed);
6618                    }
6619
6620                } else {
6621                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6622                        if ((origPackage = mSettings.peekPackageLPr(
6623                                pkg.mOriginalPackages.get(i))) != null) {
6624                            // We do have the package already installed under its
6625                            // original name...  should we use it?
6626                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6627                                // New package is not compatible with original.
6628                                origPackage = null;
6629                                continue;
6630                            } else if (origPackage.sharedUser != null) {
6631                                // Make sure uid is compatible between packages.
6632                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6633                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6634                                            + " to " + pkg.packageName + ": old uid "
6635                                            + origPackage.sharedUser.name
6636                                            + " differs from " + pkg.mSharedUserId);
6637                                    origPackage = null;
6638                                    continue;
6639                                }
6640                            } else {
6641                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6642                                        + pkg.packageName + " to old name " + origPackage.name);
6643                            }
6644                            break;
6645                        }
6646                    }
6647                }
6648            }
6649
6650            if (mTransferedPackages.contains(pkg.packageName)) {
6651                Slog.w(TAG, "Package " + pkg.packageName
6652                        + " was transferred to another, but its .apk remains");
6653            }
6654
6655            // Just create the setting, don't add it yet. For already existing packages
6656            // the PkgSetting exists already and doesn't have to be created.
6657            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6658                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6659                    pkg.applicationInfo.primaryCpuAbi,
6660                    pkg.applicationInfo.secondaryCpuAbi,
6661                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6662                    user, false);
6663            if (pkgSetting == null) {
6664                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6665                        "Creating application package " + pkg.packageName + " failed");
6666            }
6667
6668            if (pkgSetting.origPackage != null) {
6669                // If we are first transitioning from an original package,
6670                // fix up the new package's name now.  We need to do this after
6671                // looking up the package under its new name, so getPackageLP
6672                // can take care of fiddling things correctly.
6673                pkg.setPackageName(origPackage.name);
6674
6675                // File a report about this.
6676                String msg = "New package " + pkgSetting.realName
6677                        + " renamed to replace old package " + pkgSetting.name;
6678                reportSettingsProblem(Log.WARN, msg);
6679
6680                // Make a note of it.
6681                mTransferedPackages.add(origPackage.name);
6682
6683                // No longer need to retain this.
6684                pkgSetting.origPackage = null;
6685            }
6686
6687            if (realName != null) {
6688                // Make a note of it.
6689                mTransferedPackages.add(pkg.packageName);
6690            }
6691
6692            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6693                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6694            }
6695
6696            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6697                // Check all shared libraries and map to their actual file path.
6698                // We only do this here for apps not on a system dir, because those
6699                // are the only ones that can fail an install due to this.  We
6700                // will take care of the system apps by updating all of their
6701                // library paths after the scan is done.
6702                updateSharedLibrariesLPw(pkg, null);
6703            }
6704
6705            if (mFoundPolicyFile) {
6706                SELinuxMMAC.assignSeinfoValue(pkg);
6707            }
6708
6709            pkg.applicationInfo.uid = pkgSetting.appId;
6710            pkg.mExtras = pkgSetting;
6711            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6712                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6713                    // We just determined the app is signed correctly, so bring
6714                    // over the latest parsed certs.
6715                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6716                } else {
6717                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6718                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6719                                "Package " + pkg.packageName + " upgrade keys do not match the "
6720                                + "previously installed version");
6721                    } else {
6722                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6723                        String msg = "System package " + pkg.packageName
6724                            + " signature changed; retaining data.";
6725                        reportSettingsProblem(Log.WARN, msg);
6726                    }
6727                }
6728            } else {
6729                try {
6730                    verifySignaturesLP(pkgSetting, pkg);
6731                    // We just determined the app is signed correctly, so bring
6732                    // over the latest parsed certs.
6733                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6734                } catch (PackageManagerException e) {
6735                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6736                        throw e;
6737                    }
6738                    // The signature has changed, but this package is in the system
6739                    // image...  let's recover!
6740                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6741                    // However...  if this package is part of a shared user, but it
6742                    // doesn't match the signature of the shared user, let's fail.
6743                    // What this means is that you can't change the signatures
6744                    // associated with an overall shared user, which doesn't seem all
6745                    // that unreasonable.
6746                    if (pkgSetting.sharedUser != null) {
6747                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6748                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6749                            throw new PackageManagerException(
6750                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6751                                            "Signature mismatch for shared user : "
6752                                            + pkgSetting.sharedUser);
6753                        }
6754                    }
6755                    // File a report about this.
6756                    String msg = "System package " + pkg.packageName
6757                        + " signature changed; retaining data.";
6758                    reportSettingsProblem(Log.WARN, msg);
6759                }
6760            }
6761            // Verify that this new package doesn't have any content providers
6762            // that conflict with existing packages.  Only do this if the
6763            // package isn't already installed, since we don't want to break
6764            // things that are installed.
6765            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6766                final int N = pkg.providers.size();
6767                int i;
6768                for (i=0; i<N; i++) {
6769                    PackageParser.Provider p = pkg.providers.get(i);
6770                    if (p.info.authority != null) {
6771                        String names[] = p.info.authority.split(";");
6772                        for (int j = 0; j < names.length; j++) {
6773                            if (mProvidersByAuthority.containsKey(names[j])) {
6774                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6775                                final String otherPackageName =
6776                                        ((other != null && other.getComponentName() != null) ?
6777                                                other.getComponentName().getPackageName() : "?");
6778                                throw new PackageManagerException(
6779                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6780                                                "Can't install because provider name " + names[j]
6781                                                + " (in package " + pkg.applicationInfo.packageName
6782                                                + ") is already used by " + otherPackageName);
6783                            }
6784                        }
6785                    }
6786                }
6787            }
6788
6789            if (pkg.mAdoptPermissions != null) {
6790                // This package wants to adopt ownership of permissions from
6791                // another package.
6792                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6793                    final String origName = pkg.mAdoptPermissions.get(i);
6794                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6795                    if (orig != null) {
6796                        if (verifyPackageUpdateLPr(orig, pkg)) {
6797                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6798                                    + pkg.packageName);
6799                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6800                        }
6801                    }
6802                }
6803            }
6804        }
6805
6806        final String pkgName = pkg.packageName;
6807
6808        final long scanFileTime = scanFile.lastModified();
6809        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6810        pkg.applicationInfo.processName = fixProcessName(
6811                pkg.applicationInfo.packageName,
6812                pkg.applicationInfo.processName,
6813                pkg.applicationInfo.uid);
6814
6815        File dataPath;
6816        if (mPlatformPackage == pkg) {
6817            // The system package is special.
6818            dataPath = new File(Environment.getDataDirectory(), "system");
6819
6820            pkg.applicationInfo.dataDir = dataPath.getPath();
6821
6822        } else {
6823            // This is a normal package, need to make its data directory.
6824            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6825                    UserHandle.USER_OWNER, pkg.packageName);
6826
6827            boolean uidError = false;
6828            if (dataPath.exists()) {
6829                int currentUid = 0;
6830                try {
6831                    StructStat stat = Os.stat(dataPath.getPath());
6832                    currentUid = stat.st_uid;
6833                } catch (ErrnoException e) {
6834                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6835                }
6836
6837                // If we have mismatched owners for the data path, we have a problem.
6838                if (currentUid != pkg.applicationInfo.uid) {
6839                    boolean recovered = false;
6840                    if (currentUid == 0) {
6841                        // The directory somehow became owned by root.  Wow.
6842                        // This is probably because the system was stopped while
6843                        // installd was in the middle of messing with its libs
6844                        // directory.  Ask installd to fix that.
6845                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6846                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6847                        if (ret >= 0) {
6848                            recovered = true;
6849                            String msg = "Package " + pkg.packageName
6850                                    + " unexpectedly changed to uid 0; recovered to " +
6851                                    + pkg.applicationInfo.uid;
6852                            reportSettingsProblem(Log.WARN, msg);
6853                        }
6854                    }
6855                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6856                            || (scanFlags&SCAN_BOOTING) != 0)) {
6857                        // If this is a system app, we can at least delete its
6858                        // current data so the application will still work.
6859                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6860                        if (ret >= 0) {
6861                            // TODO: Kill the processes first
6862                            // Old data gone!
6863                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6864                                    ? "System package " : "Third party package ";
6865                            String msg = prefix + pkg.packageName
6866                                    + " has changed from uid: "
6867                                    + currentUid + " to "
6868                                    + pkg.applicationInfo.uid + "; old data erased";
6869                            reportSettingsProblem(Log.WARN, msg);
6870                            recovered = true;
6871
6872                            // And now re-install the app.
6873                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6874                                    pkg.applicationInfo.seinfo);
6875                            if (ret == -1) {
6876                                // Ack should not happen!
6877                                msg = prefix + pkg.packageName
6878                                        + " could not have data directory re-created after delete.";
6879                                reportSettingsProblem(Log.WARN, msg);
6880                                throw new PackageManagerException(
6881                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6882                            }
6883                        }
6884                        if (!recovered) {
6885                            mHasSystemUidErrors = true;
6886                        }
6887                    } else if (!recovered) {
6888                        // If we allow this install to proceed, we will be broken.
6889                        // Abort, abort!
6890                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6891                                "scanPackageLI");
6892                    }
6893                    if (!recovered) {
6894                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6895                            + pkg.applicationInfo.uid + "/fs_"
6896                            + currentUid;
6897                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6898                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6899                        String msg = "Package " + pkg.packageName
6900                                + " has mismatched uid: "
6901                                + currentUid + " on disk, "
6902                                + pkg.applicationInfo.uid + " in settings";
6903                        // writer
6904                        synchronized (mPackages) {
6905                            mSettings.mReadMessages.append(msg);
6906                            mSettings.mReadMessages.append('\n');
6907                            uidError = true;
6908                            if (!pkgSetting.uidError) {
6909                                reportSettingsProblem(Log.ERROR, msg);
6910                            }
6911                        }
6912                    }
6913                }
6914                pkg.applicationInfo.dataDir = dataPath.getPath();
6915                if (mShouldRestoreconData) {
6916                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6917                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6918                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6919                }
6920            } else {
6921                if (DEBUG_PACKAGE_SCANNING) {
6922                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6923                        Log.v(TAG, "Want this data dir: " + dataPath);
6924                }
6925                //invoke installer to do the actual installation
6926                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6927                        pkg.applicationInfo.seinfo);
6928                if (ret < 0) {
6929                    // Error from installer
6930                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6931                            "Unable to create data dirs [errorCode=" + ret + "]");
6932                }
6933
6934                if (dataPath.exists()) {
6935                    pkg.applicationInfo.dataDir = dataPath.getPath();
6936                } else {
6937                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6938                    pkg.applicationInfo.dataDir = null;
6939                }
6940            }
6941
6942            pkgSetting.uidError = uidError;
6943        }
6944
6945        final String path = scanFile.getPath();
6946        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6947
6948        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6949            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6950
6951            // Some system apps still use directory structure for native libraries
6952            // in which case we might end up not detecting abi solely based on apk
6953            // structure. Try to detect abi based on directory structure.
6954            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6955                    pkg.applicationInfo.primaryCpuAbi == null) {
6956                setBundledAppAbisAndRoots(pkg, pkgSetting);
6957                setNativeLibraryPaths(pkg);
6958            }
6959
6960        } else {
6961            if ((scanFlags & SCAN_MOVE) != 0) {
6962                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6963                // but we already have this packages package info in the PackageSetting. We just
6964                // use that and derive the native library path based on the new codepath.
6965                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6966                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6967            }
6968
6969            // Set native library paths again. For moves, the path will be updated based on the
6970            // ABIs we've determined above. For non-moves, the path will be updated based on the
6971            // ABIs we determined during compilation, but the path will depend on the final
6972            // package path (after the rename away from the stage path).
6973            setNativeLibraryPaths(pkg);
6974        }
6975
6976        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6977        final int[] userIds = sUserManager.getUserIds();
6978        synchronized (mInstallLock) {
6979            // Make sure all user data directories are ready to roll; we're okay
6980            // if they already exist
6981            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6982                for (int userId : userIds) {
6983                    if (userId != 0) {
6984                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6985                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6986                                pkg.applicationInfo.seinfo);
6987                    }
6988                }
6989            }
6990
6991            // Create a native library symlink only if we have native libraries
6992            // and if the native libraries are 32 bit libraries. We do not provide
6993            // this symlink for 64 bit libraries.
6994            if (pkg.applicationInfo.primaryCpuAbi != null &&
6995                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6996                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6997                for (int userId : userIds) {
6998                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6999                            nativeLibPath, userId) < 0) {
7000                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7001                                "Failed linking native library dir (user=" + userId + ")");
7002                    }
7003                }
7004            }
7005        }
7006
7007        // This is a special case for the "system" package, where the ABI is
7008        // dictated by the zygote configuration (and init.rc). We should keep track
7009        // of this ABI so that we can deal with "normal" applications that run under
7010        // the same UID correctly.
7011        if (mPlatformPackage == pkg) {
7012            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7013                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7014        }
7015
7016        // If there's a mismatch between the abi-override in the package setting
7017        // and the abiOverride specified for the install. Warn about this because we
7018        // would've already compiled the app without taking the package setting into
7019        // account.
7020        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7021            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7022                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7023                        " for package: " + pkg.packageName);
7024            }
7025        }
7026
7027        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7028        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7029        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7030
7031        // Copy the derived override back to the parsed package, so that we can
7032        // update the package settings accordingly.
7033        pkg.cpuAbiOverride = cpuAbiOverride;
7034
7035        if (DEBUG_ABI_SELECTION) {
7036            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7037                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7038                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7039        }
7040
7041        // Push the derived path down into PackageSettings so we know what to
7042        // clean up at uninstall time.
7043        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7044
7045        if (DEBUG_ABI_SELECTION) {
7046            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7047                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7048                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7049        }
7050
7051        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7052            // We don't do this here during boot because we can do it all
7053            // at once after scanning all existing packages.
7054            //
7055            // We also do this *before* we perform dexopt on this package, so that
7056            // we can avoid redundant dexopts, and also to make sure we've got the
7057            // code and package path correct.
7058            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7059                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7060        }
7061
7062        if ((scanFlags & SCAN_NO_DEX) == 0) {
7063            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7064                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7065                    (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7066            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7067                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7068            }
7069        }
7070        if (mFactoryTest && pkg.requestedPermissions.contains(
7071                android.Manifest.permission.FACTORY_TEST)) {
7072            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7073        }
7074
7075        ArrayList<PackageParser.Package> clientLibPkgs = null;
7076
7077        // writer
7078        synchronized (mPackages) {
7079            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7080                // Only system apps can add new shared libraries.
7081                if (pkg.libraryNames != null) {
7082                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7083                        String name = pkg.libraryNames.get(i);
7084                        boolean allowed = false;
7085                        if (pkg.isUpdatedSystemApp()) {
7086                            // New library entries can only be added through the
7087                            // system image.  This is important to get rid of a lot
7088                            // of nasty edge cases: for example if we allowed a non-
7089                            // system update of the app to add a library, then uninstalling
7090                            // the update would make the library go away, and assumptions
7091                            // we made such as through app install filtering would now
7092                            // have allowed apps on the device which aren't compatible
7093                            // with it.  Better to just have the restriction here, be
7094                            // conservative, and create many fewer cases that can negatively
7095                            // impact the user experience.
7096                            final PackageSetting sysPs = mSettings
7097                                    .getDisabledSystemPkgLPr(pkg.packageName);
7098                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7099                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7100                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7101                                        allowed = true;
7102                                        allowed = true;
7103                                        break;
7104                                    }
7105                                }
7106                            }
7107                        } else {
7108                            allowed = true;
7109                        }
7110                        if (allowed) {
7111                            if (!mSharedLibraries.containsKey(name)) {
7112                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7113                            } else if (!name.equals(pkg.packageName)) {
7114                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7115                                        + name + " already exists; skipping");
7116                            }
7117                        } else {
7118                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7119                                    + name + " that is not declared on system image; skipping");
7120                        }
7121                    }
7122                    if ((scanFlags&SCAN_BOOTING) == 0) {
7123                        // If we are not booting, we need to update any applications
7124                        // that are clients of our shared library.  If we are booting,
7125                        // this will all be done once the scan is complete.
7126                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7127                    }
7128                }
7129            }
7130        }
7131
7132        // We also need to dexopt any apps that are dependent on this library.  Note that
7133        // if these fail, we should abort the install since installing the library will
7134        // result in some apps being broken.
7135        if (clientLibPkgs != null) {
7136            if ((scanFlags & SCAN_NO_DEX) == 0) {
7137                for (int i = 0; i < clientLibPkgs.size(); i++) {
7138                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7139                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7140                            null /* instruction sets */, forceDex,
7141                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7142                            (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7143                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7144                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7145                                "scanPackageLI failed to dexopt clientLibPkgs");
7146                    }
7147                }
7148            }
7149        }
7150
7151        // Request the ActivityManager to kill the process(only for existing packages)
7152        // so that we do not end up in a confused state while the user is still using the older
7153        // version of the application while the new one gets installed.
7154        if ((scanFlags & SCAN_REPLACING) != 0) {
7155            killApplication(pkg.applicationInfo.packageName,
7156                        pkg.applicationInfo.uid, "replace pkg");
7157        }
7158
7159        // Also need to kill any apps that are dependent on the library.
7160        if (clientLibPkgs != null) {
7161            for (int i=0; i<clientLibPkgs.size(); i++) {
7162                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7163                killApplication(clientPkg.applicationInfo.packageName,
7164                        clientPkg.applicationInfo.uid, "update lib");
7165            }
7166        }
7167
7168        // Make sure we're not adding any bogus keyset info
7169        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7170        ksms.assertScannedPackageValid(pkg);
7171
7172        // writer
7173        synchronized (mPackages) {
7174            // We don't expect installation to fail beyond this point
7175
7176            // Add the new setting to mSettings
7177            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7178            // Add the new setting to mPackages
7179            mPackages.put(pkg.applicationInfo.packageName, pkg);
7180            // Make sure we don't accidentally delete its data.
7181            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7182            while (iter.hasNext()) {
7183                PackageCleanItem item = iter.next();
7184                if (pkgName.equals(item.packageName)) {
7185                    iter.remove();
7186                }
7187            }
7188
7189            // Take care of first install / last update times.
7190            if (currentTime != 0) {
7191                if (pkgSetting.firstInstallTime == 0) {
7192                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7193                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7194                    pkgSetting.lastUpdateTime = currentTime;
7195                }
7196            } else if (pkgSetting.firstInstallTime == 0) {
7197                // We need *something*.  Take time time stamp of the file.
7198                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7199            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7200                if (scanFileTime != pkgSetting.timeStamp) {
7201                    // A package on the system image has changed; consider this
7202                    // to be an update.
7203                    pkgSetting.lastUpdateTime = scanFileTime;
7204                }
7205            }
7206
7207            // Add the package's KeySets to the global KeySetManagerService
7208            ksms.addScannedPackageLPw(pkg);
7209
7210            int N = pkg.providers.size();
7211            StringBuilder r = null;
7212            int i;
7213            for (i=0; i<N; i++) {
7214                PackageParser.Provider p = pkg.providers.get(i);
7215                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7216                        p.info.processName, pkg.applicationInfo.uid);
7217                mProviders.addProvider(p);
7218                p.syncable = p.info.isSyncable;
7219                if (p.info.authority != null) {
7220                    String names[] = p.info.authority.split(";");
7221                    p.info.authority = null;
7222                    for (int j = 0; j < names.length; j++) {
7223                        if (j == 1 && p.syncable) {
7224                            // We only want the first authority for a provider to possibly be
7225                            // syncable, so if we already added this provider using a different
7226                            // authority clear the syncable flag. We copy the provider before
7227                            // changing it because the mProviders object contains a reference
7228                            // to a provider that we don't want to change.
7229                            // Only do this for the second authority since the resulting provider
7230                            // object can be the same for all future authorities for this provider.
7231                            p = new PackageParser.Provider(p);
7232                            p.syncable = false;
7233                        }
7234                        if (!mProvidersByAuthority.containsKey(names[j])) {
7235                            mProvidersByAuthority.put(names[j], p);
7236                            if (p.info.authority == null) {
7237                                p.info.authority = names[j];
7238                            } else {
7239                                p.info.authority = p.info.authority + ";" + names[j];
7240                            }
7241                            if (DEBUG_PACKAGE_SCANNING) {
7242                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7243                                    Log.d(TAG, "Registered content provider: " + names[j]
7244                                            + ", className = " + p.info.name + ", isSyncable = "
7245                                            + p.info.isSyncable);
7246                            }
7247                        } else {
7248                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7249                            Slog.w(TAG, "Skipping provider name " + names[j] +
7250                                    " (in package " + pkg.applicationInfo.packageName +
7251                                    "): name already used by "
7252                                    + ((other != null && other.getComponentName() != null)
7253                                            ? other.getComponentName().getPackageName() : "?"));
7254                        }
7255                    }
7256                }
7257                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7258                    if (r == null) {
7259                        r = new StringBuilder(256);
7260                    } else {
7261                        r.append(' ');
7262                    }
7263                    r.append(p.info.name);
7264                }
7265            }
7266            if (r != null) {
7267                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7268            }
7269
7270            N = pkg.services.size();
7271            r = null;
7272            for (i=0; i<N; i++) {
7273                PackageParser.Service s = pkg.services.get(i);
7274                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7275                        s.info.processName, pkg.applicationInfo.uid);
7276                mServices.addService(s);
7277                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7278                    if (r == null) {
7279                        r = new StringBuilder(256);
7280                    } else {
7281                        r.append(' ');
7282                    }
7283                    r.append(s.info.name);
7284                }
7285            }
7286            if (r != null) {
7287                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7288            }
7289
7290            N = pkg.receivers.size();
7291            r = null;
7292            for (i=0; i<N; i++) {
7293                PackageParser.Activity a = pkg.receivers.get(i);
7294                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7295                        a.info.processName, pkg.applicationInfo.uid);
7296                mReceivers.addActivity(a, "receiver");
7297                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7298                    if (r == null) {
7299                        r = new StringBuilder(256);
7300                    } else {
7301                        r.append(' ');
7302                    }
7303                    r.append(a.info.name);
7304                }
7305            }
7306            if (r != null) {
7307                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7308            }
7309
7310            N = pkg.activities.size();
7311            r = null;
7312            for (i=0; i<N; i++) {
7313                PackageParser.Activity a = pkg.activities.get(i);
7314                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7315                        a.info.processName, pkg.applicationInfo.uid);
7316                mActivities.addActivity(a, "activity");
7317                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7318                    if (r == null) {
7319                        r = new StringBuilder(256);
7320                    } else {
7321                        r.append(' ');
7322                    }
7323                    r.append(a.info.name);
7324                }
7325            }
7326            if (r != null) {
7327                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7328            }
7329
7330            N = pkg.permissionGroups.size();
7331            r = null;
7332            for (i=0; i<N; i++) {
7333                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7334                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7335                if (cur == null) {
7336                    mPermissionGroups.put(pg.info.name, pg);
7337                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7338                        if (r == null) {
7339                            r = new StringBuilder(256);
7340                        } else {
7341                            r.append(' ');
7342                        }
7343                        r.append(pg.info.name);
7344                    }
7345                } else {
7346                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7347                            + pg.info.packageName + " ignored: original from "
7348                            + cur.info.packageName);
7349                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7350                        if (r == null) {
7351                            r = new StringBuilder(256);
7352                        } else {
7353                            r.append(' ');
7354                        }
7355                        r.append("DUP:");
7356                        r.append(pg.info.name);
7357                    }
7358                }
7359            }
7360            if (r != null) {
7361                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7362            }
7363
7364            N = pkg.permissions.size();
7365            r = null;
7366            for (i=0; i<N; i++) {
7367                PackageParser.Permission p = pkg.permissions.get(i);
7368
7369                // Assume by default that we did not install this permission into the system.
7370                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7371
7372                // Now that permission groups have a special meaning, we ignore permission
7373                // groups for legacy apps to prevent unexpected behavior. In particular,
7374                // permissions for one app being granted to someone just becuase they happen
7375                // to be in a group defined by another app (before this had no implications).
7376                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7377                    p.group = mPermissionGroups.get(p.info.group);
7378                    // Warn for a permission in an unknown group.
7379                    if (p.info.group != null && p.group == null) {
7380                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7381                                + p.info.packageName + " in an unknown group " + p.info.group);
7382                    }
7383                }
7384
7385                ArrayMap<String, BasePermission> permissionMap =
7386                        p.tree ? mSettings.mPermissionTrees
7387                                : mSettings.mPermissions;
7388                BasePermission bp = permissionMap.get(p.info.name);
7389
7390                // Allow system apps to redefine non-system permissions
7391                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7392                    final boolean currentOwnerIsSystem = (bp.perm != null
7393                            && isSystemApp(bp.perm.owner));
7394                    if (isSystemApp(p.owner)) {
7395                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7396                            // It's a built-in permission and no owner, take ownership now
7397                            bp.packageSetting = pkgSetting;
7398                            bp.perm = p;
7399                            bp.uid = pkg.applicationInfo.uid;
7400                            bp.sourcePackage = p.info.packageName;
7401                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7402                        } else if (!currentOwnerIsSystem) {
7403                            String msg = "New decl " + p.owner + " of permission  "
7404                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7405                            reportSettingsProblem(Log.WARN, msg);
7406                            bp = null;
7407                        }
7408                    }
7409                }
7410
7411                if (bp == null) {
7412                    bp = new BasePermission(p.info.name, p.info.packageName,
7413                            BasePermission.TYPE_NORMAL);
7414                    permissionMap.put(p.info.name, bp);
7415                }
7416
7417                if (bp.perm == null) {
7418                    if (bp.sourcePackage == null
7419                            || bp.sourcePackage.equals(p.info.packageName)) {
7420                        BasePermission tree = findPermissionTreeLP(p.info.name);
7421                        if (tree == null
7422                                || tree.sourcePackage.equals(p.info.packageName)) {
7423                            bp.packageSetting = pkgSetting;
7424                            bp.perm = p;
7425                            bp.uid = pkg.applicationInfo.uid;
7426                            bp.sourcePackage = p.info.packageName;
7427                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7428                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7429                                if (r == null) {
7430                                    r = new StringBuilder(256);
7431                                } else {
7432                                    r.append(' ');
7433                                }
7434                                r.append(p.info.name);
7435                            }
7436                        } else {
7437                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7438                                    + p.info.packageName + " ignored: base tree "
7439                                    + tree.name + " is from package "
7440                                    + tree.sourcePackage);
7441                        }
7442                    } else {
7443                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7444                                + p.info.packageName + " ignored: original from "
7445                                + bp.sourcePackage);
7446                    }
7447                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7448                    if (r == null) {
7449                        r = new StringBuilder(256);
7450                    } else {
7451                        r.append(' ');
7452                    }
7453                    r.append("DUP:");
7454                    r.append(p.info.name);
7455                }
7456                if (bp.perm == p) {
7457                    bp.protectionLevel = p.info.protectionLevel;
7458                }
7459            }
7460
7461            if (r != null) {
7462                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7463            }
7464
7465            N = pkg.instrumentation.size();
7466            r = null;
7467            for (i=0; i<N; i++) {
7468                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7469                a.info.packageName = pkg.applicationInfo.packageName;
7470                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7471                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7472                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7473                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7474                a.info.dataDir = pkg.applicationInfo.dataDir;
7475
7476                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7477                // need other information about the application, like the ABI and what not ?
7478                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7479                mInstrumentation.put(a.getComponentName(), a);
7480                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7481                    if (r == null) {
7482                        r = new StringBuilder(256);
7483                    } else {
7484                        r.append(' ');
7485                    }
7486                    r.append(a.info.name);
7487                }
7488            }
7489            if (r != null) {
7490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7491            }
7492
7493            if (pkg.protectedBroadcasts != null) {
7494                N = pkg.protectedBroadcasts.size();
7495                for (i=0; i<N; i++) {
7496                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7497                }
7498            }
7499
7500            pkgSetting.setTimeStamp(scanFileTime);
7501
7502            // Create idmap files for pairs of (packages, overlay packages).
7503            // Note: "android", ie framework-res.apk, is handled by native layers.
7504            if (pkg.mOverlayTarget != null) {
7505                // This is an overlay package.
7506                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7507                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7508                        mOverlays.put(pkg.mOverlayTarget,
7509                                new ArrayMap<String, PackageParser.Package>());
7510                    }
7511                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7512                    map.put(pkg.packageName, pkg);
7513                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7514                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7515                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7516                                "scanPackageLI failed to createIdmap");
7517                    }
7518                }
7519            } else if (mOverlays.containsKey(pkg.packageName) &&
7520                    !pkg.packageName.equals("android")) {
7521                // This is a regular package, with one or more known overlay packages.
7522                createIdmapsForPackageLI(pkg);
7523            }
7524        }
7525
7526        return pkg;
7527    }
7528
7529    /**
7530     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7531     * is derived purely on the basis of the contents of {@code scanFile} and
7532     * {@code cpuAbiOverride}.
7533     *
7534     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7535     */
7536    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7537                                 String cpuAbiOverride, boolean extractLibs)
7538            throws PackageManagerException {
7539        // TODO: We can probably be smarter about this stuff. For installed apps,
7540        // we can calculate this information at install time once and for all. For
7541        // system apps, we can probably assume that this information doesn't change
7542        // after the first boot scan. As things stand, we do lots of unnecessary work.
7543
7544        // Give ourselves some initial paths; we'll come back for another
7545        // pass once we've determined ABI below.
7546        setNativeLibraryPaths(pkg);
7547
7548        // We would never need to extract libs for forward-locked and external packages,
7549        // since the container service will do it for us. We shouldn't attempt to
7550        // extract libs from system app when it was not updated.
7551        if (pkg.isForwardLocked() || isExternal(pkg) ||
7552            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7553            extractLibs = false;
7554        }
7555
7556        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7557        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7558
7559        NativeLibraryHelper.Handle handle = null;
7560        try {
7561            handle = NativeLibraryHelper.Handle.create(scanFile);
7562            // TODO(multiArch): This can be null for apps that didn't go through the
7563            // usual installation process. We can calculate it again, like we
7564            // do during install time.
7565            //
7566            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7567            // unnecessary.
7568            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7569
7570            // Null out the abis so that they can be recalculated.
7571            pkg.applicationInfo.primaryCpuAbi = null;
7572            pkg.applicationInfo.secondaryCpuAbi = null;
7573            if (isMultiArch(pkg.applicationInfo)) {
7574                // Warn if we've set an abiOverride for multi-lib packages..
7575                // By definition, we need to copy both 32 and 64 bit libraries for
7576                // such packages.
7577                if (pkg.cpuAbiOverride != null
7578                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7579                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7580                }
7581
7582                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7583                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7584                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7585                    if (extractLibs) {
7586                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7587                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7588                                useIsaSpecificSubdirs);
7589                    } else {
7590                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7591                    }
7592                }
7593
7594                maybeThrowExceptionForMultiArchCopy(
7595                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7596
7597                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7598                    if (extractLibs) {
7599                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7600                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7601                                useIsaSpecificSubdirs);
7602                    } else {
7603                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7604                    }
7605                }
7606
7607                maybeThrowExceptionForMultiArchCopy(
7608                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7609
7610                if (abi64 >= 0) {
7611                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7612                }
7613
7614                if (abi32 >= 0) {
7615                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7616                    if (abi64 >= 0) {
7617                        pkg.applicationInfo.secondaryCpuAbi = abi;
7618                    } else {
7619                        pkg.applicationInfo.primaryCpuAbi = abi;
7620                    }
7621                }
7622            } else {
7623                String[] abiList = (cpuAbiOverride != null) ?
7624                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7625
7626                // Enable gross and lame hacks for apps that are built with old
7627                // SDK tools. We must scan their APKs for renderscript bitcode and
7628                // not launch them if it's present. Don't bother checking on devices
7629                // that don't have 64 bit support.
7630                boolean needsRenderScriptOverride = false;
7631                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7632                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7633                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7634                    needsRenderScriptOverride = true;
7635                }
7636
7637                final int copyRet;
7638                if (extractLibs) {
7639                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7640                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7641                } else {
7642                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7643                }
7644
7645                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7646                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7647                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7648                }
7649
7650                if (copyRet >= 0) {
7651                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7652                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7653                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7654                } else if (needsRenderScriptOverride) {
7655                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7656                }
7657            }
7658        } catch (IOException ioe) {
7659            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7660        } finally {
7661            IoUtils.closeQuietly(handle);
7662        }
7663
7664        // Now that we've calculated the ABIs and determined if it's an internal app,
7665        // we will go ahead and populate the nativeLibraryPath.
7666        setNativeLibraryPaths(pkg);
7667    }
7668
7669    /**
7670     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7671     * i.e, so that all packages can be run inside a single process if required.
7672     *
7673     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7674     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7675     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7676     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7677     * updating a package that belongs to a shared user.
7678     *
7679     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7680     * adds unnecessary complexity.
7681     */
7682    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7683            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7684            boolean bootComplete) {
7685        String requiredInstructionSet = null;
7686        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7687            requiredInstructionSet = VMRuntime.getInstructionSet(
7688                     scannedPackage.applicationInfo.primaryCpuAbi);
7689        }
7690
7691        PackageSetting requirer = null;
7692        for (PackageSetting ps : packagesForUser) {
7693            // If packagesForUser contains scannedPackage, we skip it. This will happen
7694            // when scannedPackage is an update of an existing package. Without this check,
7695            // we will never be able to change the ABI of any package belonging to a shared
7696            // user, even if it's compatible with other packages.
7697            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7698                if (ps.primaryCpuAbiString == null) {
7699                    continue;
7700                }
7701
7702                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7703                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7704                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7705                    // this but there's not much we can do.
7706                    String errorMessage = "Instruction set mismatch, "
7707                            + ((requirer == null) ? "[caller]" : requirer)
7708                            + " requires " + requiredInstructionSet + " whereas " + ps
7709                            + " requires " + instructionSet;
7710                    Slog.w(TAG, errorMessage);
7711                }
7712
7713                if (requiredInstructionSet == null) {
7714                    requiredInstructionSet = instructionSet;
7715                    requirer = ps;
7716                }
7717            }
7718        }
7719
7720        if (requiredInstructionSet != null) {
7721            String adjustedAbi;
7722            if (requirer != null) {
7723                // requirer != null implies that either scannedPackage was null or that scannedPackage
7724                // did not require an ABI, in which case we have to adjust scannedPackage to match
7725                // the ABI of the set (which is the same as requirer's ABI)
7726                adjustedAbi = requirer.primaryCpuAbiString;
7727                if (scannedPackage != null) {
7728                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7729                }
7730            } else {
7731                // requirer == null implies that we're updating all ABIs in the set to
7732                // match scannedPackage.
7733                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7734            }
7735
7736            for (PackageSetting ps : packagesForUser) {
7737                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7738                    if (ps.primaryCpuAbiString != null) {
7739                        continue;
7740                    }
7741
7742                    ps.primaryCpuAbiString = adjustedAbi;
7743                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7744                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7745                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7746
7747                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7748                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7749                                bootComplete, false /*useJit*/);
7750                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7751                            ps.primaryCpuAbiString = null;
7752                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7753                            return;
7754                        } else {
7755                            mInstaller.rmdex(ps.codePathString,
7756                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7757                        }
7758                    }
7759                }
7760            }
7761        }
7762    }
7763
7764    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7765        synchronized (mPackages) {
7766            mResolverReplaced = true;
7767            // Set up information for custom user intent resolution activity.
7768            mResolveActivity.applicationInfo = pkg.applicationInfo;
7769            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7770            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7771            mResolveActivity.processName = pkg.applicationInfo.packageName;
7772            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7773            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7774                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7775            mResolveActivity.theme = 0;
7776            mResolveActivity.exported = true;
7777            mResolveActivity.enabled = true;
7778            mResolveInfo.activityInfo = mResolveActivity;
7779            mResolveInfo.priority = 0;
7780            mResolveInfo.preferredOrder = 0;
7781            mResolveInfo.match = 0;
7782            mResolveComponentName = mCustomResolverComponentName;
7783            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7784                    mResolveComponentName);
7785        }
7786    }
7787
7788    private static String calculateBundledApkRoot(final String codePathString) {
7789        final File codePath = new File(codePathString);
7790        final File codeRoot;
7791        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7792            codeRoot = Environment.getRootDirectory();
7793        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7794            codeRoot = Environment.getOemDirectory();
7795        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7796            codeRoot = Environment.getVendorDirectory();
7797        } else {
7798            // Unrecognized code path; take its top real segment as the apk root:
7799            // e.g. /something/app/blah.apk => /something
7800            try {
7801                File f = codePath.getCanonicalFile();
7802                File parent = f.getParentFile();    // non-null because codePath is a file
7803                File tmp;
7804                while ((tmp = parent.getParentFile()) != null) {
7805                    f = parent;
7806                    parent = tmp;
7807                }
7808                codeRoot = f;
7809                Slog.w(TAG, "Unrecognized code path "
7810                        + codePath + " - using " + codeRoot);
7811            } catch (IOException e) {
7812                // Can't canonicalize the code path -- shenanigans?
7813                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7814                return Environment.getRootDirectory().getPath();
7815            }
7816        }
7817        return codeRoot.getPath();
7818    }
7819
7820    /**
7821     * Derive and set the location of native libraries for the given package,
7822     * which varies depending on where and how the package was installed.
7823     */
7824    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7825        final ApplicationInfo info = pkg.applicationInfo;
7826        final String codePath = pkg.codePath;
7827        final File codeFile = new File(codePath);
7828        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7829        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7830
7831        info.nativeLibraryRootDir = null;
7832        info.nativeLibraryRootRequiresIsa = false;
7833        info.nativeLibraryDir = null;
7834        info.secondaryNativeLibraryDir = null;
7835
7836        if (isApkFile(codeFile)) {
7837            // Monolithic install
7838            if (bundledApp) {
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(info.sourceDir);
7842                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7843                        getPrimaryInstructionSet(info));
7844
7845                // This is a bundled system app so choose the path based on the ABI.
7846                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7847                // is just the default path.
7848                final String apkName = deriveCodePathName(codePath);
7849                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7850                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7851                        apkName).getAbsolutePath();
7852
7853                if (info.secondaryCpuAbi != null) {
7854                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7855                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7856                            secondaryLibDir, apkName).getAbsolutePath();
7857                }
7858            } else if (asecApp) {
7859                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7860                        .getAbsolutePath();
7861            } else {
7862                final String apkName = deriveCodePathName(codePath);
7863                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7864                        .getAbsolutePath();
7865            }
7866
7867            info.nativeLibraryRootRequiresIsa = false;
7868            info.nativeLibraryDir = info.nativeLibraryRootDir;
7869        } else {
7870            // Cluster install
7871            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7872            info.nativeLibraryRootRequiresIsa = true;
7873
7874            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7875                    getPrimaryInstructionSet(info)).getAbsolutePath();
7876
7877            if (info.secondaryCpuAbi != null) {
7878                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7879                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7880            }
7881        }
7882    }
7883
7884    /**
7885     * Calculate the abis and roots for a bundled app. These can uniquely
7886     * be determined from the contents of the system partition, i.e whether
7887     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7888     * of this information, and instead assume that the system was built
7889     * sensibly.
7890     */
7891    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7892                                           PackageSetting pkgSetting) {
7893        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7894
7895        // If "/system/lib64/apkname" exists, assume that is the per-package
7896        // native library directory to use; otherwise use "/system/lib/apkname".
7897        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7898        setBundledAppAbi(pkg, apkRoot, apkName);
7899        // pkgSetting might be null during rescan following uninstall of updates
7900        // to a bundled app, so accommodate that possibility.  The settings in
7901        // that case will be established later from the parsed package.
7902        //
7903        // If the settings aren't null, sync them up with what we've just derived.
7904        // note that apkRoot isn't stored in the package settings.
7905        if (pkgSetting != null) {
7906            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7907            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7908        }
7909    }
7910
7911    /**
7912     * Deduces the ABI of a bundled app and sets the relevant fields on the
7913     * parsed pkg object.
7914     *
7915     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7916     *        under which system libraries are installed.
7917     * @param apkName the name of the installed package.
7918     */
7919    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7920        final File codeFile = new File(pkg.codePath);
7921
7922        final boolean has64BitLibs;
7923        final boolean has32BitLibs;
7924        if (isApkFile(codeFile)) {
7925            // Monolithic install
7926            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7927            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7928        } else {
7929            // Cluster install
7930            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7931            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7932                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7933                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7934                has64BitLibs = (new File(rootDir, isa)).exists();
7935            } else {
7936                has64BitLibs = false;
7937            }
7938            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7939                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7940                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7941                has32BitLibs = (new File(rootDir, isa)).exists();
7942            } else {
7943                has32BitLibs = false;
7944            }
7945        }
7946
7947        if (has64BitLibs && !has32BitLibs) {
7948            // The package has 64 bit libs, but not 32 bit libs. Its primary
7949            // ABI should be 64 bit. We can safely assume here that the bundled
7950            // native libraries correspond to the most preferred ABI in the list.
7951
7952            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7953            pkg.applicationInfo.secondaryCpuAbi = null;
7954        } else if (has32BitLibs && !has64BitLibs) {
7955            // The package has 32 bit libs but not 64 bit libs. Its primary
7956            // ABI should be 32 bit.
7957
7958            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7959            pkg.applicationInfo.secondaryCpuAbi = null;
7960        } else if (has32BitLibs && has64BitLibs) {
7961            // The application has both 64 and 32 bit bundled libraries. We check
7962            // here that the app declares multiArch support, and warn if it doesn't.
7963            //
7964            // We will be lenient here and record both ABIs. The primary will be the
7965            // ABI that's higher on the list, i.e, a device that's configured to prefer
7966            // 64 bit apps will see a 64 bit primary ABI,
7967
7968            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7969                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7970            }
7971
7972            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7973                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7974                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7975            } else {
7976                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7977                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7978            }
7979        } else {
7980            pkg.applicationInfo.primaryCpuAbi = null;
7981            pkg.applicationInfo.secondaryCpuAbi = null;
7982        }
7983    }
7984
7985    private void killApplication(String pkgName, int appId, String reason) {
7986        // Request the ActivityManager to kill the process(only for existing packages)
7987        // so that we do not end up in a confused state while the user is still using the older
7988        // version of the application while the new one gets installed.
7989        IActivityManager am = ActivityManagerNative.getDefault();
7990        if (am != null) {
7991            try {
7992                am.killApplicationWithAppId(pkgName, appId, reason);
7993            } catch (RemoteException e) {
7994            }
7995        }
7996    }
7997
7998    void removePackageLI(PackageSetting ps, boolean chatty) {
7999        if (DEBUG_INSTALL) {
8000            if (chatty)
8001                Log.d(TAG, "Removing package " + ps.name);
8002        }
8003
8004        // writer
8005        synchronized (mPackages) {
8006            mPackages.remove(ps.name);
8007            final PackageParser.Package pkg = ps.pkg;
8008            if (pkg != null) {
8009                cleanPackageDataStructuresLILPw(pkg, chatty);
8010            }
8011        }
8012    }
8013
8014    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8015        if (DEBUG_INSTALL) {
8016            if (chatty)
8017                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8018        }
8019
8020        // writer
8021        synchronized (mPackages) {
8022            mPackages.remove(pkg.applicationInfo.packageName);
8023            cleanPackageDataStructuresLILPw(pkg, chatty);
8024        }
8025    }
8026
8027    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8028        int N = pkg.providers.size();
8029        StringBuilder r = null;
8030        int i;
8031        for (i=0; i<N; i++) {
8032            PackageParser.Provider p = pkg.providers.get(i);
8033            mProviders.removeProvider(p);
8034            if (p.info.authority == null) {
8035
8036                /* There was another ContentProvider with this authority when
8037                 * this app was installed so this authority is null,
8038                 * Ignore it as we don't have to unregister the provider.
8039                 */
8040                continue;
8041            }
8042            String names[] = p.info.authority.split(";");
8043            for (int j = 0; j < names.length; j++) {
8044                if (mProvidersByAuthority.get(names[j]) == p) {
8045                    mProvidersByAuthority.remove(names[j]);
8046                    if (DEBUG_REMOVE) {
8047                        if (chatty)
8048                            Log.d(TAG, "Unregistered content provider: " + names[j]
8049                                    + ", className = " + p.info.name + ", isSyncable = "
8050                                    + p.info.isSyncable);
8051                    }
8052                }
8053            }
8054            if (DEBUG_REMOVE && chatty) {
8055                if (r == null) {
8056                    r = new StringBuilder(256);
8057                } else {
8058                    r.append(' ');
8059                }
8060                r.append(p.info.name);
8061            }
8062        }
8063        if (r != null) {
8064            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8065        }
8066
8067        N = pkg.services.size();
8068        r = null;
8069        for (i=0; i<N; i++) {
8070            PackageParser.Service s = pkg.services.get(i);
8071            mServices.removeService(s);
8072            if (chatty) {
8073                if (r == null) {
8074                    r = new StringBuilder(256);
8075                } else {
8076                    r.append(' ');
8077                }
8078                r.append(s.info.name);
8079            }
8080        }
8081        if (r != null) {
8082            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8083        }
8084
8085        N = pkg.receivers.size();
8086        r = null;
8087        for (i=0; i<N; i++) {
8088            PackageParser.Activity a = pkg.receivers.get(i);
8089            mReceivers.removeActivity(a, "receiver");
8090            if (DEBUG_REMOVE && chatty) {
8091                if (r == null) {
8092                    r = new StringBuilder(256);
8093                } else {
8094                    r.append(' ');
8095                }
8096                r.append(a.info.name);
8097            }
8098        }
8099        if (r != null) {
8100            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8101        }
8102
8103        N = pkg.activities.size();
8104        r = null;
8105        for (i=0; i<N; i++) {
8106            PackageParser.Activity a = pkg.activities.get(i);
8107            mActivities.removeActivity(a, "activity");
8108            if (DEBUG_REMOVE && chatty) {
8109                if (r == null) {
8110                    r = new StringBuilder(256);
8111                } else {
8112                    r.append(' ');
8113                }
8114                r.append(a.info.name);
8115            }
8116        }
8117        if (r != null) {
8118            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8119        }
8120
8121        N = pkg.permissions.size();
8122        r = null;
8123        for (i=0; i<N; i++) {
8124            PackageParser.Permission p = pkg.permissions.get(i);
8125            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8126            if (bp == null) {
8127                bp = mSettings.mPermissionTrees.get(p.info.name);
8128            }
8129            if (bp != null && bp.perm == p) {
8130                bp.perm = null;
8131                if (DEBUG_REMOVE && chatty) {
8132                    if (r == null) {
8133                        r = new StringBuilder(256);
8134                    } else {
8135                        r.append(' ');
8136                    }
8137                    r.append(p.info.name);
8138                }
8139            }
8140            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8141                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8142                if (appOpPkgs != null) {
8143                    appOpPkgs.remove(pkg.packageName);
8144                }
8145            }
8146        }
8147        if (r != null) {
8148            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8149        }
8150
8151        N = pkg.requestedPermissions.size();
8152        r = null;
8153        for (i=0; i<N; i++) {
8154            String perm = pkg.requestedPermissions.get(i);
8155            BasePermission bp = mSettings.mPermissions.get(perm);
8156            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8157                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8158                if (appOpPkgs != null) {
8159                    appOpPkgs.remove(pkg.packageName);
8160                    if (appOpPkgs.isEmpty()) {
8161                        mAppOpPermissionPackages.remove(perm);
8162                    }
8163                }
8164            }
8165        }
8166        if (r != null) {
8167            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8168        }
8169
8170        N = pkg.instrumentation.size();
8171        r = null;
8172        for (i=0; i<N; i++) {
8173            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8174            mInstrumentation.remove(a.getComponentName());
8175            if (DEBUG_REMOVE && chatty) {
8176                if (r == null) {
8177                    r = new StringBuilder(256);
8178                } else {
8179                    r.append(' ');
8180                }
8181                r.append(a.info.name);
8182            }
8183        }
8184        if (r != null) {
8185            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8186        }
8187
8188        r = null;
8189        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8190            // Only system apps can hold shared libraries.
8191            if (pkg.libraryNames != null) {
8192                for (i=0; i<pkg.libraryNames.size(); i++) {
8193                    String name = pkg.libraryNames.get(i);
8194                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8195                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8196                        mSharedLibraries.remove(name);
8197                        if (DEBUG_REMOVE && chatty) {
8198                            if (r == null) {
8199                                r = new StringBuilder(256);
8200                            } else {
8201                                r.append(' ');
8202                            }
8203                            r.append(name);
8204                        }
8205                    }
8206                }
8207            }
8208        }
8209        if (r != null) {
8210            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8211        }
8212    }
8213
8214    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8215        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8216            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8217                return true;
8218            }
8219        }
8220        return false;
8221    }
8222
8223    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8224    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8225    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8226
8227    private void updatePermissionsLPw(String changingPkg,
8228            PackageParser.Package pkgInfo, int flags) {
8229        // Make sure there are no dangling permission trees.
8230        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8231        while (it.hasNext()) {
8232            final BasePermission bp = it.next();
8233            if (bp.packageSetting == null) {
8234                // We may not yet have parsed the package, so just see if
8235                // we still know about its settings.
8236                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8237            }
8238            if (bp.packageSetting == null) {
8239                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8240                        + " from package " + bp.sourcePackage);
8241                it.remove();
8242            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8243                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8244                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8245                            + " from package " + bp.sourcePackage);
8246                    flags |= UPDATE_PERMISSIONS_ALL;
8247                    it.remove();
8248                }
8249            }
8250        }
8251
8252        // Make sure all dynamic permissions have been assigned to a package,
8253        // and make sure there are no dangling permissions.
8254        it = mSettings.mPermissions.values().iterator();
8255        while (it.hasNext()) {
8256            final BasePermission bp = it.next();
8257            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8258                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8259                        + bp.name + " pkg=" + bp.sourcePackage
8260                        + " info=" + bp.pendingInfo);
8261                if (bp.packageSetting == null && bp.pendingInfo != null) {
8262                    final BasePermission tree = findPermissionTreeLP(bp.name);
8263                    if (tree != null && tree.perm != null) {
8264                        bp.packageSetting = tree.packageSetting;
8265                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8266                                new PermissionInfo(bp.pendingInfo));
8267                        bp.perm.info.packageName = tree.perm.info.packageName;
8268                        bp.perm.info.name = bp.name;
8269                        bp.uid = tree.uid;
8270                    }
8271                }
8272            }
8273            if (bp.packageSetting == null) {
8274                // We may not yet have parsed the package, so just see if
8275                // we still know about its settings.
8276                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8277            }
8278            if (bp.packageSetting == null) {
8279                Slog.w(TAG, "Removing dangling permission: " + bp.name
8280                        + " from package " + bp.sourcePackage);
8281                it.remove();
8282            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8283                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8284                    Slog.i(TAG, "Removing old permission: " + bp.name
8285                            + " from package " + bp.sourcePackage);
8286                    flags |= UPDATE_PERMISSIONS_ALL;
8287                    it.remove();
8288                }
8289            }
8290        }
8291
8292        // Now update the permissions for all packages, in particular
8293        // replace the granted permissions of the system packages.
8294        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8295            for (PackageParser.Package pkg : mPackages.values()) {
8296                if (pkg != pkgInfo) {
8297                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8298                            changingPkg);
8299                }
8300            }
8301        }
8302
8303        if (pkgInfo != null) {
8304            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8305        }
8306    }
8307
8308    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8309            String packageOfInterest) {
8310        // IMPORTANT: There are two types of permissions: install and runtime.
8311        // Install time permissions are granted when the app is installed to
8312        // all device users and users added in the future. Runtime permissions
8313        // are granted at runtime explicitly to specific users. Normal and signature
8314        // protected permissions are install time permissions. Dangerous permissions
8315        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8316        // otherwise they are runtime permissions. This function does not manage
8317        // runtime permissions except for the case an app targeting Lollipop MR1
8318        // being upgraded to target a newer SDK, in which case dangerous permissions
8319        // are transformed from install time to runtime ones.
8320
8321        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8322        if (ps == null) {
8323            return;
8324        }
8325
8326        PermissionsState permissionsState = ps.getPermissionsState();
8327        PermissionsState origPermissions = permissionsState;
8328
8329        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8330
8331        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8332
8333        boolean changedInstallPermission = false;
8334
8335        if (replace) {
8336            ps.installPermissionsFixed = false;
8337            if (!ps.isSharedUser()) {
8338                origPermissions = new PermissionsState(permissionsState);
8339                permissionsState.reset();
8340            }
8341        }
8342
8343        permissionsState.setGlobalGids(mGlobalGids);
8344
8345        final int N = pkg.requestedPermissions.size();
8346        for (int i=0; i<N; i++) {
8347            final String name = pkg.requestedPermissions.get(i);
8348            final BasePermission bp = mSettings.mPermissions.get(name);
8349
8350            if (DEBUG_INSTALL) {
8351                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8352            }
8353
8354            if (bp == null || bp.packageSetting == null) {
8355                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8356                    Slog.w(TAG, "Unknown permission " + name
8357                            + " in package " + pkg.packageName);
8358                }
8359                continue;
8360            }
8361
8362            final String perm = bp.name;
8363            boolean allowedSig = false;
8364            int grant = GRANT_DENIED;
8365
8366            // Keep track of app op permissions.
8367            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8368                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8369                if (pkgs == null) {
8370                    pkgs = new ArraySet<>();
8371                    mAppOpPermissionPackages.put(bp.name, pkgs);
8372                }
8373                pkgs.add(pkg.packageName);
8374            }
8375
8376            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8377            switch (level) {
8378                case PermissionInfo.PROTECTION_NORMAL: {
8379                    // For all apps normal permissions are install time ones.
8380                    grant = GRANT_INSTALL;
8381                } break;
8382
8383                case PermissionInfo.PROTECTION_DANGEROUS: {
8384                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8385                        // For legacy apps dangerous permissions are install time ones.
8386                        grant = GRANT_INSTALL_LEGACY;
8387                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8388                        // For legacy apps that became modern, install becomes runtime.
8389                        grant = GRANT_UPGRADE;
8390                    } else if (mPromoteSystemApps
8391                            && isSystemApp(ps)
8392                            && mExistingSystemPackages.contains(ps.name)) {
8393                        // For legacy system apps, install becomes runtime.
8394                        // We cannot check hasInstallPermission() for system apps since those
8395                        // permissions were granted implicitly and not persisted pre-M.
8396                        grant = GRANT_UPGRADE;
8397                    } else {
8398                        // For modern apps keep runtime permissions unchanged.
8399                        grant = GRANT_RUNTIME;
8400                    }
8401                } break;
8402
8403                case PermissionInfo.PROTECTION_SIGNATURE: {
8404                    // For all apps signature permissions are install time ones.
8405                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8406                    if (allowedSig) {
8407                        grant = GRANT_INSTALL;
8408                    }
8409                } break;
8410            }
8411
8412            if (DEBUG_INSTALL) {
8413                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8414            }
8415
8416            if (grant != GRANT_DENIED) {
8417                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8418                    // If this is an existing, non-system package, then
8419                    // we can't add any new permissions to it.
8420                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8421                        // Except...  if this is a permission that was added
8422                        // to the platform (note: need to only do this when
8423                        // updating the platform).
8424                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8425                            grant = GRANT_DENIED;
8426                        }
8427                    }
8428                }
8429
8430                switch (grant) {
8431                    case GRANT_INSTALL: {
8432                        // Revoke this as runtime permission to handle the case of
8433                        // a runtime permission being downgraded to an install one.
8434                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8435                            if (origPermissions.getRuntimePermissionState(
8436                                    bp.name, userId) != null) {
8437                                // Revoke the runtime permission and clear the flags.
8438                                origPermissions.revokeRuntimePermission(bp, userId);
8439                                origPermissions.updatePermissionFlags(bp, userId,
8440                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8441                                // If we revoked a permission permission, we have to write.
8442                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8443                                        changedRuntimePermissionUserIds, userId);
8444                            }
8445                        }
8446                        // Grant an install permission.
8447                        if (permissionsState.grantInstallPermission(bp) !=
8448                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8449                            changedInstallPermission = true;
8450                        }
8451                    } break;
8452
8453                    case GRANT_INSTALL_LEGACY: {
8454                        // Grant an install permission.
8455                        if (permissionsState.grantInstallPermission(bp) !=
8456                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8457                            changedInstallPermission = true;
8458                        }
8459                    } break;
8460
8461                    case GRANT_RUNTIME: {
8462                        // Grant previously granted runtime permissions.
8463                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8464                            PermissionState permissionState = origPermissions
8465                                    .getRuntimePermissionState(bp.name, userId);
8466                            final int flags = permissionState != null
8467                                    ? permissionState.getFlags() : 0;
8468                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8469                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8470                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8471                                    // If we cannot put the permission as it was, we have to write.
8472                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8473                                            changedRuntimePermissionUserIds, userId);
8474                                }
8475                            }
8476                            // Propagate the permission flags.
8477                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8478                        }
8479                    } break;
8480
8481                    case GRANT_UPGRADE: {
8482                        // Grant runtime permissions for a previously held install permission.
8483                        PermissionState permissionState = origPermissions
8484                                .getInstallPermissionState(bp.name);
8485                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8486
8487                        if (origPermissions.revokeInstallPermission(bp)
8488                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8489                            // We will be transferring the permission flags, so clear them.
8490                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8491                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8492                            changedInstallPermission = true;
8493                        }
8494
8495                        // If the permission is not to be promoted to runtime we ignore it and
8496                        // also its other flags as they are not applicable to install permissions.
8497                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8498                            for (int userId : currentUserIds) {
8499                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8500                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8501                                    // Transfer the permission flags.
8502                                    permissionsState.updatePermissionFlags(bp, userId,
8503                                            flags, flags);
8504                                    // If we granted the permission, we have to write.
8505                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8506                                            changedRuntimePermissionUserIds, userId);
8507                                }
8508                            }
8509                        }
8510                    } break;
8511
8512                    default: {
8513                        if (packageOfInterest == null
8514                                || packageOfInterest.equals(pkg.packageName)) {
8515                            Slog.w(TAG, "Not granting permission " + perm
8516                                    + " to package " + pkg.packageName
8517                                    + " because it was previously installed without");
8518                        }
8519                    } break;
8520                }
8521            } else {
8522                if (permissionsState.revokeInstallPermission(bp) !=
8523                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8524                    // Also drop the permission flags.
8525                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8526                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8527                    changedInstallPermission = true;
8528                    Slog.i(TAG, "Un-granting permission " + perm
8529                            + " from package " + pkg.packageName
8530                            + " (protectionLevel=" + bp.protectionLevel
8531                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8532                            + ")");
8533                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8534                    // Don't print warning for app op permissions, since it is fine for them
8535                    // not to be granted, there is a UI for the user to decide.
8536                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8537                        Slog.w(TAG, "Not granting permission " + perm
8538                                + " to package " + pkg.packageName
8539                                + " (protectionLevel=" + bp.protectionLevel
8540                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8541                                + ")");
8542                    }
8543                }
8544            }
8545        }
8546
8547        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8548                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8549            // This is the first that we have heard about this package, so the
8550            // permissions we have now selected are fixed until explicitly
8551            // changed.
8552            ps.installPermissionsFixed = true;
8553        }
8554
8555        // Persist the runtime permissions state for users with changes.
8556        for (int userId : changedRuntimePermissionUserIds) {
8557            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8558        }
8559    }
8560
8561    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8562        boolean allowed = false;
8563        final int NP = PackageParser.NEW_PERMISSIONS.length;
8564        for (int ip=0; ip<NP; ip++) {
8565            final PackageParser.NewPermissionInfo npi
8566                    = PackageParser.NEW_PERMISSIONS[ip];
8567            if (npi.name.equals(perm)
8568                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8569                allowed = true;
8570                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8571                        + pkg.packageName);
8572                break;
8573            }
8574        }
8575        return allowed;
8576    }
8577
8578    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8579            BasePermission bp, PermissionsState origPermissions) {
8580        boolean allowed;
8581        allowed = (compareSignatures(
8582                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8583                        == PackageManager.SIGNATURE_MATCH)
8584                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8585                        == PackageManager.SIGNATURE_MATCH);
8586        if (!allowed && (bp.protectionLevel
8587                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8588            if (isSystemApp(pkg)) {
8589                // For updated system applications, a system permission
8590                // is granted only if it had been defined by the original application.
8591                if (pkg.isUpdatedSystemApp()) {
8592                    final PackageSetting sysPs = mSettings
8593                            .getDisabledSystemPkgLPr(pkg.packageName);
8594                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8595                        // If the original was granted this permission, we take
8596                        // that grant decision as read and propagate it to the
8597                        // update.
8598                        if (sysPs.isPrivileged()) {
8599                            allowed = true;
8600                        }
8601                    } else {
8602                        // The system apk may have been updated with an older
8603                        // version of the one on the data partition, but which
8604                        // granted a new system permission that it didn't have
8605                        // before.  In this case we do want to allow the app to
8606                        // now get the new permission if the ancestral apk is
8607                        // privileged to get it.
8608                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8609                            for (int j=0;
8610                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8611                                if (perm.equals(
8612                                        sysPs.pkg.requestedPermissions.get(j))) {
8613                                    allowed = true;
8614                                    break;
8615                                }
8616                            }
8617                        }
8618                    }
8619                } else {
8620                    allowed = isPrivilegedApp(pkg);
8621                }
8622            }
8623        }
8624        if (!allowed) {
8625            if (!allowed && (bp.protectionLevel
8626                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8627                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8628                // If this was a previously normal/dangerous permission that got moved
8629                // to a system permission as part of the runtime permission redesign, then
8630                // we still want to blindly grant it to old apps.
8631                allowed = true;
8632            }
8633            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8634                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8635                // If this permission is to be granted to the system installer and
8636                // this app is an installer, then it gets the permission.
8637                allowed = true;
8638            }
8639            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8640                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8641                // If this permission is to be granted to the system verifier and
8642                // this app is a verifier, then it gets the permission.
8643                allowed = true;
8644            }
8645            if (!allowed && (bp.protectionLevel
8646                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8647                    && isSystemApp(pkg)) {
8648                // Any pre-installed system app is allowed to get this permission.
8649                allowed = true;
8650            }
8651            if (!allowed && (bp.protectionLevel
8652                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8653                // For development permissions, a development permission
8654                // is granted only if it was already granted.
8655                allowed = origPermissions.hasInstallPermission(perm);
8656            }
8657        }
8658        return allowed;
8659    }
8660
8661    final class ActivityIntentResolver
8662            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8663        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8664                boolean defaultOnly, int userId) {
8665            if (!sUserManager.exists(userId)) return null;
8666            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8667            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8668        }
8669
8670        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8671                int userId) {
8672            if (!sUserManager.exists(userId)) return null;
8673            mFlags = flags;
8674            return super.queryIntent(intent, resolvedType,
8675                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8676        }
8677
8678        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8679                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8680            if (!sUserManager.exists(userId)) return null;
8681            if (packageActivities == null) {
8682                return null;
8683            }
8684            mFlags = flags;
8685            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8686            final int N = packageActivities.size();
8687            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8688                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8689
8690            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8691            for (int i = 0; i < N; ++i) {
8692                intentFilters = packageActivities.get(i).intents;
8693                if (intentFilters != null && intentFilters.size() > 0) {
8694                    PackageParser.ActivityIntentInfo[] array =
8695                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8696                    intentFilters.toArray(array);
8697                    listCut.add(array);
8698                }
8699            }
8700            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8701        }
8702
8703        public final void addActivity(PackageParser.Activity a, String type) {
8704            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8705            mActivities.put(a.getComponentName(), a);
8706            if (DEBUG_SHOW_INFO)
8707                Log.v(
8708                TAG, "  " + type + " " +
8709                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8710            if (DEBUG_SHOW_INFO)
8711                Log.v(TAG, "    Class=" + a.info.name);
8712            final int NI = a.intents.size();
8713            for (int j=0; j<NI; j++) {
8714                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8715                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8716                    intent.setPriority(0);
8717                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8718                            + a.className + " with priority > 0, forcing to 0");
8719                }
8720                if (DEBUG_SHOW_INFO) {
8721                    Log.v(TAG, "    IntentFilter:");
8722                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8723                }
8724                if (!intent.debugCheck()) {
8725                    Log.w(TAG, "==> For Activity " + a.info.name);
8726                }
8727                addFilter(intent);
8728            }
8729        }
8730
8731        public final void removeActivity(PackageParser.Activity a, String type) {
8732            mActivities.remove(a.getComponentName());
8733            if (DEBUG_SHOW_INFO) {
8734                Log.v(TAG, "  " + type + " "
8735                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8736                                : a.info.name) + ":");
8737                Log.v(TAG, "    Class=" + a.info.name);
8738            }
8739            final int NI = a.intents.size();
8740            for (int j=0; j<NI; j++) {
8741                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8742                if (DEBUG_SHOW_INFO) {
8743                    Log.v(TAG, "    IntentFilter:");
8744                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8745                }
8746                removeFilter(intent);
8747            }
8748        }
8749
8750        @Override
8751        protected boolean allowFilterResult(
8752                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8753            ActivityInfo filterAi = filter.activity.info;
8754            for (int i=dest.size()-1; i>=0; i--) {
8755                ActivityInfo destAi = dest.get(i).activityInfo;
8756                if (destAi.name == filterAi.name
8757                        && destAi.packageName == filterAi.packageName) {
8758                    return false;
8759                }
8760            }
8761            return true;
8762        }
8763
8764        @Override
8765        protected ActivityIntentInfo[] newArray(int size) {
8766            return new ActivityIntentInfo[size];
8767        }
8768
8769        @Override
8770        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8771            if (!sUserManager.exists(userId)) return true;
8772            PackageParser.Package p = filter.activity.owner;
8773            if (p != null) {
8774                PackageSetting ps = (PackageSetting)p.mExtras;
8775                if (ps != null) {
8776                    // System apps are never considered stopped for purposes of
8777                    // filtering, because there may be no way for the user to
8778                    // actually re-launch them.
8779                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8780                            && ps.getStopped(userId);
8781                }
8782            }
8783            return false;
8784        }
8785
8786        @Override
8787        protected boolean isPackageForFilter(String packageName,
8788                PackageParser.ActivityIntentInfo info) {
8789            return packageName.equals(info.activity.owner.packageName);
8790        }
8791
8792        @Override
8793        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8794                int match, int userId) {
8795            if (!sUserManager.exists(userId)) return null;
8796            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8797                return null;
8798            }
8799            final PackageParser.Activity activity = info.activity;
8800            if (mSafeMode && (activity.info.applicationInfo.flags
8801                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8802                return null;
8803            }
8804            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8805            if (ps == null) {
8806                return null;
8807            }
8808            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8809                    ps.readUserState(userId), userId);
8810            if (ai == null) {
8811                return null;
8812            }
8813            final ResolveInfo res = new ResolveInfo();
8814            res.activityInfo = ai;
8815            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8816                res.filter = info;
8817            }
8818            if (info != null) {
8819                res.handleAllWebDataURI = info.handleAllWebDataURI();
8820            }
8821            res.priority = info.getPriority();
8822            res.preferredOrder = activity.owner.mPreferredOrder;
8823            //System.out.println("Result: " + res.activityInfo.className +
8824            //                   " = " + res.priority);
8825            res.match = match;
8826            res.isDefault = info.hasDefault;
8827            res.labelRes = info.labelRes;
8828            res.nonLocalizedLabel = info.nonLocalizedLabel;
8829            if (userNeedsBadging(userId)) {
8830                res.noResourceId = true;
8831            } else {
8832                res.icon = info.icon;
8833            }
8834            res.iconResourceId = info.icon;
8835            res.system = res.activityInfo.applicationInfo.isSystemApp();
8836            return res;
8837        }
8838
8839        @Override
8840        protected void sortResults(List<ResolveInfo> results) {
8841            Collections.sort(results, mResolvePrioritySorter);
8842        }
8843
8844        @Override
8845        protected void dumpFilter(PrintWriter out, String prefix,
8846                PackageParser.ActivityIntentInfo filter) {
8847            out.print(prefix); out.print(
8848                    Integer.toHexString(System.identityHashCode(filter.activity)));
8849                    out.print(' ');
8850                    filter.activity.printComponentShortName(out);
8851                    out.print(" filter ");
8852                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8853        }
8854
8855        @Override
8856        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8857            return filter.activity;
8858        }
8859
8860        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8861            PackageParser.Activity activity = (PackageParser.Activity)label;
8862            out.print(prefix); out.print(
8863                    Integer.toHexString(System.identityHashCode(activity)));
8864                    out.print(' ');
8865                    activity.printComponentShortName(out);
8866            if (count > 1) {
8867                out.print(" ("); out.print(count); out.print(" filters)");
8868            }
8869            out.println();
8870        }
8871
8872//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8873//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8874//            final List<ResolveInfo> retList = Lists.newArrayList();
8875//            while (i.hasNext()) {
8876//                final ResolveInfo resolveInfo = i.next();
8877//                if (isEnabledLP(resolveInfo.activityInfo)) {
8878//                    retList.add(resolveInfo);
8879//                }
8880//            }
8881//            return retList;
8882//        }
8883
8884        // Keys are String (activity class name), values are Activity.
8885        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8886                = new ArrayMap<ComponentName, PackageParser.Activity>();
8887        private int mFlags;
8888    }
8889
8890    private final class ServiceIntentResolver
8891            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8892        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8893                boolean defaultOnly, int userId) {
8894            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8895            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8896        }
8897
8898        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8899                int userId) {
8900            if (!sUserManager.exists(userId)) return null;
8901            mFlags = flags;
8902            return super.queryIntent(intent, resolvedType,
8903                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8904        }
8905
8906        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8907                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8908            if (!sUserManager.exists(userId)) return null;
8909            if (packageServices == null) {
8910                return null;
8911            }
8912            mFlags = flags;
8913            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8914            final int N = packageServices.size();
8915            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8916                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8917
8918            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8919            for (int i = 0; i < N; ++i) {
8920                intentFilters = packageServices.get(i).intents;
8921                if (intentFilters != null && intentFilters.size() > 0) {
8922                    PackageParser.ServiceIntentInfo[] array =
8923                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8924                    intentFilters.toArray(array);
8925                    listCut.add(array);
8926                }
8927            }
8928            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8929        }
8930
8931        public final void addService(PackageParser.Service s) {
8932            mServices.put(s.getComponentName(), s);
8933            if (DEBUG_SHOW_INFO) {
8934                Log.v(TAG, "  "
8935                        + (s.info.nonLocalizedLabel != null
8936                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8937                Log.v(TAG, "    Class=" + s.info.name);
8938            }
8939            final int NI = s.intents.size();
8940            int j;
8941            for (j=0; j<NI; j++) {
8942                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8943                if (DEBUG_SHOW_INFO) {
8944                    Log.v(TAG, "    IntentFilter:");
8945                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8946                }
8947                if (!intent.debugCheck()) {
8948                    Log.w(TAG, "==> For Service " + s.info.name);
8949                }
8950                addFilter(intent);
8951            }
8952        }
8953
8954        public final void removeService(PackageParser.Service s) {
8955            mServices.remove(s.getComponentName());
8956            if (DEBUG_SHOW_INFO) {
8957                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8958                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8959                Log.v(TAG, "    Class=" + s.info.name);
8960            }
8961            final int NI = s.intents.size();
8962            int j;
8963            for (j=0; j<NI; j++) {
8964                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8965                if (DEBUG_SHOW_INFO) {
8966                    Log.v(TAG, "    IntentFilter:");
8967                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8968                }
8969                removeFilter(intent);
8970            }
8971        }
8972
8973        @Override
8974        protected boolean allowFilterResult(
8975                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8976            ServiceInfo filterSi = filter.service.info;
8977            for (int i=dest.size()-1; i>=0; i--) {
8978                ServiceInfo destAi = dest.get(i).serviceInfo;
8979                if (destAi.name == filterSi.name
8980                        && destAi.packageName == filterSi.packageName) {
8981                    return false;
8982                }
8983            }
8984            return true;
8985        }
8986
8987        @Override
8988        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8989            return new PackageParser.ServiceIntentInfo[size];
8990        }
8991
8992        @Override
8993        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8994            if (!sUserManager.exists(userId)) return true;
8995            PackageParser.Package p = filter.service.owner;
8996            if (p != null) {
8997                PackageSetting ps = (PackageSetting)p.mExtras;
8998                if (ps != null) {
8999                    // System apps are never considered stopped for purposes of
9000                    // filtering, because there may be no way for the user to
9001                    // actually re-launch them.
9002                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9003                            && ps.getStopped(userId);
9004                }
9005            }
9006            return false;
9007        }
9008
9009        @Override
9010        protected boolean isPackageForFilter(String packageName,
9011                PackageParser.ServiceIntentInfo info) {
9012            return packageName.equals(info.service.owner.packageName);
9013        }
9014
9015        @Override
9016        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9017                int match, int userId) {
9018            if (!sUserManager.exists(userId)) return null;
9019            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9020            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9021                return null;
9022            }
9023            final PackageParser.Service service = info.service;
9024            if (mSafeMode && (service.info.applicationInfo.flags
9025                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9026                return null;
9027            }
9028            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9029            if (ps == null) {
9030                return null;
9031            }
9032            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9033                    ps.readUserState(userId), userId);
9034            if (si == null) {
9035                return null;
9036            }
9037            final ResolveInfo res = new ResolveInfo();
9038            res.serviceInfo = si;
9039            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9040                res.filter = filter;
9041            }
9042            res.priority = info.getPriority();
9043            res.preferredOrder = service.owner.mPreferredOrder;
9044            res.match = match;
9045            res.isDefault = info.hasDefault;
9046            res.labelRes = info.labelRes;
9047            res.nonLocalizedLabel = info.nonLocalizedLabel;
9048            res.icon = info.icon;
9049            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9050            return res;
9051        }
9052
9053        @Override
9054        protected void sortResults(List<ResolveInfo> results) {
9055            Collections.sort(results, mResolvePrioritySorter);
9056        }
9057
9058        @Override
9059        protected void dumpFilter(PrintWriter out, String prefix,
9060                PackageParser.ServiceIntentInfo filter) {
9061            out.print(prefix); out.print(
9062                    Integer.toHexString(System.identityHashCode(filter.service)));
9063                    out.print(' ');
9064                    filter.service.printComponentShortName(out);
9065                    out.print(" filter ");
9066                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9067        }
9068
9069        @Override
9070        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9071            return filter.service;
9072        }
9073
9074        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9075            PackageParser.Service service = (PackageParser.Service)label;
9076            out.print(prefix); out.print(
9077                    Integer.toHexString(System.identityHashCode(service)));
9078                    out.print(' ');
9079                    service.printComponentShortName(out);
9080            if (count > 1) {
9081                out.print(" ("); out.print(count); out.print(" filters)");
9082            }
9083            out.println();
9084        }
9085
9086//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9087//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9088//            final List<ResolveInfo> retList = Lists.newArrayList();
9089//            while (i.hasNext()) {
9090//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9091//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9092//                    retList.add(resolveInfo);
9093//                }
9094//            }
9095//            return retList;
9096//        }
9097
9098        // Keys are String (activity class name), values are Activity.
9099        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9100                = new ArrayMap<ComponentName, PackageParser.Service>();
9101        private int mFlags;
9102    };
9103
9104    private final class ProviderIntentResolver
9105            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9106        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9107                boolean defaultOnly, int userId) {
9108            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9109            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9110        }
9111
9112        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9113                int userId) {
9114            if (!sUserManager.exists(userId))
9115                return null;
9116            mFlags = flags;
9117            return super.queryIntent(intent, resolvedType,
9118                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9119        }
9120
9121        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9122                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9123            if (!sUserManager.exists(userId))
9124                return null;
9125            if (packageProviders == null) {
9126                return null;
9127            }
9128            mFlags = flags;
9129            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9130            final int N = packageProviders.size();
9131            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9132                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9133
9134            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9135            for (int i = 0; i < N; ++i) {
9136                intentFilters = packageProviders.get(i).intents;
9137                if (intentFilters != null && intentFilters.size() > 0) {
9138                    PackageParser.ProviderIntentInfo[] array =
9139                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9140                    intentFilters.toArray(array);
9141                    listCut.add(array);
9142                }
9143            }
9144            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9145        }
9146
9147        public final void addProvider(PackageParser.Provider p) {
9148            if (mProviders.containsKey(p.getComponentName())) {
9149                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9150                return;
9151            }
9152
9153            mProviders.put(p.getComponentName(), p);
9154            if (DEBUG_SHOW_INFO) {
9155                Log.v(TAG, "  "
9156                        + (p.info.nonLocalizedLabel != null
9157                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9158                Log.v(TAG, "    Class=" + p.info.name);
9159            }
9160            final int NI = p.intents.size();
9161            int j;
9162            for (j = 0; j < NI; j++) {
9163                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9164                if (DEBUG_SHOW_INFO) {
9165                    Log.v(TAG, "    IntentFilter:");
9166                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9167                }
9168                if (!intent.debugCheck()) {
9169                    Log.w(TAG, "==> For Provider " + p.info.name);
9170                }
9171                addFilter(intent);
9172            }
9173        }
9174
9175        public final void removeProvider(PackageParser.Provider p) {
9176            mProviders.remove(p.getComponentName());
9177            if (DEBUG_SHOW_INFO) {
9178                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9179                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9180                Log.v(TAG, "    Class=" + p.info.name);
9181            }
9182            final int NI = p.intents.size();
9183            int j;
9184            for (j = 0; j < NI; j++) {
9185                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9186                if (DEBUG_SHOW_INFO) {
9187                    Log.v(TAG, "    IntentFilter:");
9188                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9189                }
9190                removeFilter(intent);
9191            }
9192        }
9193
9194        @Override
9195        protected boolean allowFilterResult(
9196                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9197            ProviderInfo filterPi = filter.provider.info;
9198            for (int i = dest.size() - 1; i >= 0; i--) {
9199                ProviderInfo destPi = dest.get(i).providerInfo;
9200                if (destPi.name == filterPi.name
9201                        && destPi.packageName == filterPi.packageName) {
9202                    return false;
9203                }
9204            }
9205            return true;
9206        }
9207
9208        @Override
9209        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9210            return new PackageParser.ProviderIntentInfo[size];
9211        }
9212
9213        @Override
9214        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9215            if (!sUserManager.exists(userId))
9216                return true;
9217            PackageParser.Package p = filter.provider.owner;
9218            if (p != null) {
9219                PackageSetting ps = (PackageSetting) p.mExtras;
9220                if (ps != null) {
9221                    // System apps are never considered stopped for purposes of
9222                    // filtering, because there may be no way for the user to
9223                    // actually re-launch them.
9224                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9225                            && ps.getStopped(userId);
9226                }
9227            }
9228            return false;
9229        }
9230
9231        @Override
9232        protected boolean isPackageForFilter(String packageName,
9233                PackageParser.ProviderIntentInfo info) {
9234            return packageName.equals(info.provider.owner.packageName);
9235        }
9236
9237        @Override
9238        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9239                int match, int userId) {
9240            if (!sUserManager.exists(userId))
9241                return null;
9242            final PackageParser.ProviderIntentInfo info = filter;
9243            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9244                return null;
9245            }
9246            final PackageParser.Provider provider = info.provider;
9247            if (mSafeMode && (provider.info.applicationInfo.flags
9248                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9249                return null;
9250            }
9251            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9252            if (ps == null) {
9253                return null;
9254            }
9255            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9256                    ps.readUserState(userId), userId);
9257            if (pi == null) {
9258                return null;
9259            }
9260            final ResolveInfo res = new ResolveInfo();
9261            res.providerInfo = pi;
9262            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9263                res.filter = filter;
9264            }
9265            res.priority = info.getPriority();
9266            res.preferredOrder = provider.owner.mPreferredOrder;
9267            res.match = match;
9268            res.isDefault = info.hasDefault;
9269            res.labelRes = info.labelRes;
9270            res.nonLocalizedLabel = info.nonLocalizedLabel;
9271            res.icon = info.icon;
9272            res.system = res.providerInfo.applicationInfo.isSystemApp();
9273            return res;
9274        }
9275
9276        @Override
9277        protected void sortResults(List<ResolveInfo> results) {
9278            Collections.sort(results, mResolvePrioritySorter);
9279        }
9280
9281        @Override
9282        protected void dumpFilter(PrintWriter out, String prefix,
9283                PackageParser.ProviderIntentInfo filter) {
9284            out.print(prefix);
9285            out.print(
9286                    Integer.toHexString(System.identityHashCode(filter.provider)));
9287            out.print(' ');
9288            filter.provider.printComponentShortName(out);
9289            out.print(" filter ");
9290            out.println(Integer.toHexString(System.identityHashCode(filter)));
9291        }
9292
9293        @Override
9294        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9295            return filter.provider;
9296        }
9297
9298        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9299            PackageParser.Provider provider = (PackageParser.Provider)label;
9300            out.print(prefix); out.print(
9301                    Integer.toHexString(System.identityHashCode(provider)));
9302                    out.print(' ');
9303                    provider.printComponentShortName(out);
9304            if (count > 1) {
9305                out.print(" ("); out.print(count); out.print(" filters)");
9306            }
9307            out.println();
9308        }
9309
9310        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9311                = new ArrayMap<ComponentName, PackageParser.Provider>();
9312        private int mFlags;
9313    };
9314
9315    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9316            new Comparator<ResolveInfo>() {
9317        public int compare(ResolveInfo r1, ResolveInfo r2) {
9318            int v1 = r1.priority;
9319            int v2 = r2.priority;
9320            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9321            if (v1 != v2) {
9322                return (v1 > v2) ? -1 : 1;
9323            }
9324            v1 = r1.preferredOrder;
9325            v2 = r2.preferredOrder;
9326            if (v1 != v2) {
9327                return (v1 > v2) ? -1 : 1;
9328            }
9329            if (r1.isDefault != r2.isDefault) {
9330                return r1.isDefault ? -1 : 1;
9331            }
9332            v1 = r1.match;
9333            v2 = r2.match;
9334            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9335            if (v1 != v2) {
9336                return (v1 > v2) ? -1 : 1;
9337            }
9338            if (r1.system != r2.system) {
9339                return r1.system ? -1 : 1;
9340            }
9341            return 0;
9342        }
9343    };
9344
9345    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9346            new Comparator<ProviderInfo>() {
9347        public int compare(ProviderInfo p1, ProviderInfo p2) {
9348            final int v1 = p1.initOrder;
9349            final int v2 = p2.initOrder;
9350            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9351        }
9352    };
9353
9354    final void sendPackageBroadcast(final String action, final String pkg,
9355            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9356            final int[] userIds) {
9357        mHandler.post(new Runnable() {
9358            @Override
9359            public void run() {
9360                try {
9361                    final IActivityManager am = ActivityManagerNative.getDefault();
9362                    if (am == null) return;
9363                    final int[] resolvedUserIds;
9364                    if (userIds == null) {
9365                        resolvedUserIds = am.getRunningUserIds();
9366                    } else {
9367                        resolvedUserIds = userIds;
9368                    }
9369                    for (int id : resolvedUserIds) {
9370                        final Intent intent = new Intent(action,
9371                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9372                        if (extras != null) {
9373                            intent.putExtras(extras);
9374                        }
9375                        if (targetPkg != null) {
9376                            intent.setPackage(targetPkg);
9377                        }
9378                        // Modify the UID when posting to other users
9379                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9380                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9381                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9382                            intent.putExtra(Intent.EXTRA_UID, uid);
9383                        }
9384                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9385                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9386                        if (DEBUG_BROADCASTS) {
9387                            RuntimeException here = new RuntimeException("here");
9388                            here.fillInStackTrace();
9389                            Slog.d(TAG, "Sending to user " + id + ": "
9390                                    + intent.toShortString(false, true, false, false)
9391                                    + " " + intent.getExtras(), here);
9392                        }
9393                        am.broadcastIntent(null, intent, null, finishedReceiver,
9394                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9395                                null, finishedReceiver != null, false, id);
9396                    }
9397                } catch (RemoteException ex) {
9398                }
9399            }
9400        });
9401    }
9402
9403    /**
9404     * Check if the external storage media is available. This is true if there
9405     * is a mounted external storage medium or if the external storage is
9406     * emulated.
9407     */
9408    private boolean isExternalMediaAvailable() {
9409        return mMediaMounted || Environment.isExternalStorageEmulated();
9410    }
9411
9412    @Override
9413    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9414        // writer
9415        synchronized (mPackages) {
9416            if (!isExternalMediaAvailable()) {
9417                // If the external storage is no longer mounted at this point,
9418                // the caller may not have been able to delete all of this
9419                // packages files and can not delete any more.  Bail.
9420                return null;
9421            }
9422            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9423            if (lastPackage != null) {
9424                pkgs.remove(lastPackage);
9425            }
9426            if (pkgs.size() > 0) {
9427                return pkgs.get(0);
9428            }
9429        }
9430        return null;
9431    }
9432
9433    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9434        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9435                userId, andCode ? 1 : 0, packageName);
9436        if (mSystemReady) {
9437            msg.sendToTarget();
9438        } else {
9439            if (mPostSystemReadyMessages == null) {
9440                mPostSystemReadyMessages = new ArrayList<>();
9441            }
9442            mPostSystemReadyMessages.add(msg);
9443        }
9444    }
9445
9446    void startCleaningPackages() {
9447        // reader
9448        synchronized (mPackages) {
9449            if (!isExternalMediaAvailable()) {
9450                return;
9451            }
9452            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9453                return;
9454            }
9455        }
9456        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9457        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9458        IActivityManager am = ActivityManagerNative.getDefault();
9459        if (am != null) {
9460            try {
9461                am.startService(null, intent, null, mContext.getOpPackageName(),
9462                        UserHandle.USER_OWNER);
9463            } catch (RemoteException e) {
9464            }
9465        }
9466    }
9467
9468    @Override
9469    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9470            int installFlags, String installerPackageName, VerificationParams verificationParams,
9471            String packageAbiOverride) {
9472        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9473                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9474    }
9475
9476    @Override
9477    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9478            int installFlags, String installerPackageName, VerificationParams verificationParams,
9479            String packageAbiOverride, int userId) {
9480        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9481
9482        final int callingUid = Binder.getCallingUid();
9483        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9484
9485        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9486            try {
9487                if (observer != null) {
9488                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9489                }
9490            } catch (RemoteException re) {
9491            }
9492            return;
9493        }
9494
9495        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9496            installFlags |= PackageManager.INSTALL_FROM_ADB;
9497
9498        } else {
9499            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9500            // about installerPackageName.
9501
9502            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9503            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9504        }
9505
9506        UserHandle user;
9507        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9508            user = UserHandle.ALL;
9509        } else {
9510            user = new UserHandle(userId);
9511        }
9512
9513        // Only system components can circumvent runtime permissions when installing.
9514        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9515                && mContext.checkCallingOrSelfPermission(Manifest.permission
9516                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9517            throw new SecurityException("You need the "
9518                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9519                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9520        }
9521
9522        verificationParams.setInstallerUid(callingUid);
9523
9524        final File originFile = new File(originPath);
9525        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9526
9527        final Message msg = mHandler.obtainMessage(INIT_COPY);
9528        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9529                null, verificationParams, user, packageAbiOverride, null);
9530        mHandler.sendMessage(msg);
9531    }
9532
9533    void installStage(String packageName, File stagedDir, String stagedCid,
9534            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9535            String installerPackageName, int installerUid, UserHandle user) {
9536        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9537                params.referrerUri, installerUid, null);
9538        verifParams.setInstallerUid(installerUid);
9539
9540        final OriginInfo origin;
9541        if (stagedDir != null) {
9542            origin = OriginInfo.fromStagedFile(stagedDir);
9543        } else {
9544            origin = OriginInfo.fromStagedContainer(stagedCid);
9545        }
9546
9547        final Message msg = mHandler.obtainMessage(INIT_COPY);
9548        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9549                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9550                params.grantedRuntimePermissions);
9551        mHandler.sendMessage(msg);
9552    }
9553
9554    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9555        Bundle extras = new Bundle(1);
9556        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9557
9558        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9559                packageName, extras, null, null, new int[] {userId});
9560        try {
9561            IActivityManager am = ActivityManagerNative.getDefault();
9562            final boolean isSystem =
9563                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9564            if (isSystem && am.isUserRunning(userId, false)) {
9565                // The just-installed/enabled app is bundled on the system, so presumed
9566                // to be able to run automatically without needing an explicit launch.
9567                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9568                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9569                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9570                        .setPackage(packageName);
9571                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9572                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9573            }
9574        } catch (RemoteException e) {
9575            // shouldn't happen
9576            Slog.w(TAG, "Unable to bootstrap installed package", e);
9577        }
9578    }
9579
9580    @Override
9581    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9582            int userId) {
9583        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9584        PackageSetting pkgSetting;
9585        final int uid = Binder.getCallingUid();
9586        enforceCrossUserPermission(uid, userId, true, true,
9587                "setApplicationHiddenSetting for user " + userId);
9588
9589        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9590            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9591            return false;
9592        }
9593
9594        long callingId = Binder.clearCallingIdentity();
9595        try {
9596            boolean sendAdded = false;
9597            boolean sendRemoved = false;
9598            // writer
9599            synchronized (mPackages) {
9600                pkgSetting = mSettings.mPackages.get(packageName);
9601                if (pkgSetting == null) {
9602                    return false;
9603                }
9604                if (pkgSetting.getHidden(userId) != hidden) {
9605                    pkgSetting.setHidden(hidden, userId);
9606                    mSettings.writePackageRestrictionsLPr(userId);
9607                    if (hidden) {
9608                        sendRemoved = true;
9609                    } else {
9610                        sendAdded = true;
9611                    }
9612                }
9613            }
9614            if (sendAdded) {
9615                sendPackageAddedForUser(packageName, pkgSetting, userId);
9616                return true;
9617            }
9618            if (sendRemoved) {
9619                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9620                        "hiding pkg");
9621                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9622                return true;
9623            }
9624        } finally {
9625            Binder.restoreCallingIdentity(callingId);
9626        }
9627        return false;
9628    }
9629
9630    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9631            int userId) {
9632        final PackageRemovedInfo info = new PackageRemovedInfo();
9633        info.removedPackage = packageName;
9634        info.removedUsers = new int[] {userId};
9635        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9636        info.sendBroadcast(false, false, false);
9637    }
9638
9639    /**
9640     * Returns true if application is not found or there was an error. Otherwise it returns
9641     * the hidden state of the package for the given user.
9642     */
9643    @Override
9644    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9645        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9646        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9647                false, "getApplicationHidden for user " + userId);
9648        PackageSetting pkgSetting;
9649        long callingId = Binder.clearCallingIdentity();
9650        try {
9651            // writer
9652            synchronized (mPackages) {
9653                pkgSetting = mSettings.mPackages.get(packageName);
9654                if (pkgSetting == null) {
9655                    return true;
9656                }
9657                return pkgSetting.getHidden(userId);
9658            }
9659        } finally {
9660            Binder.restoreCallingIdentity(callingId);
9661        }
9662    }
9663
9664    /**
9665     * @hide
9666     */
9667    @Override
9668    public int installExistingPackageAsUser(String packageName, int userId) {
9669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9670                null);
9671        PackageSetting pkgSetting;
9672        final int uid = Binder.getCallingUid();
9673        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9674                + userId);
9675        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9676            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9677        }
9678
9679        long callingId = Binder.clearCallingIdentity();
9680        try {
9681            boolean sendAdded = false;
9682
9683            // writer
9684            synchronized (mPackages) {
9685                pkgSetting = mSettings.mPackages.get(packageName);
9686                if (pkgSetting == null) {
9687                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9688                }
9689                if (!pkgSetting.getInstalled(userId)) {
9690                    pkgSetting.setInstalled(true, userId);
9691                    pkgSetting.setHidden(false, userId);
9692                    mSettings.writePackageRestrictionsLPr(userId);
9693                    sendAdded = true;
9694                }
9695            }
9696
9697            if (sendAdded) {
9698                sendPackageAddedForUser(packageName, pkgSetting, userId);
9699            }
9700        } finally {
9701            Binder.restoreCallingIdentity(callingId);
9702        }
9703
9704        return PackageManager.INSTALL_SUCCEEDED;
9705    }
9706
9707    boolean isUserRestricted(int userId, String restrictionKey) {
9708        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9709        if (restrictions.getBoolean(restrictionKey, false)) {
9710            Log.w(TAG, "User is restricted: " + restrictionKey);
9711            return true;
9712        }
9713        return false;
9714    }
9715
9716    @Override
9717    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9718        mContext.enforceCallingOrSelfPermission(
9719                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9720                "Only package verification agents can verify applications");
9721
9722        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9723        final PackageVerificationResponse response = new PackageVerificationResponse(
9724                verificationCode, Binder.getCallingUid());
9725        msg.arg1 = id;
9726        msg.obj = response;
9727        mHandler.sendMessage(msg);
9728    }
9729
9730    @Override
9731    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9732            long millisecondsToDelay) {
9733        mContext.enforceCallingOrSelfPermission(
9734                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9735                "Only package verification agents can extend verification timeouts");
9736
9737        final PackageVerificationState state = mPendingVerification.get(id);
9738        final PackageVerificationResponse response = new PackageVerificationResponse(
9739                verificationCodeAtTimeout, Binder.getCallingUid());
9740
9741        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9742            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9743        }
9744        if (millisecondsToDelay < 0) {
9745            millisecondsToDelay = 0;
9746        }
9747        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9748                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9749            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9750        }
9751
9752        if ((state != null) && !state.timeoutExtended()) {
9753            state.extendTimeout();
9754
9755            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9756            msg.arg1 = id;
9757            msg.obj = response;
9758            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9759        }
9760    }
9761
9762    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9763            int verificationCode, UserHandle user) {
9764        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9765        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9766        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9767        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9768        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9769
9770        mContext.sendBroadcastAsUser(intent, user,
9771                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9772    }
9773
9774    private ComponentName matchComponentForVerifier(String packageName,
9775            List<ResolveInfo> receivers) {
9776        ActivityInfo targetReceiver = null;
9777
9778        final int NR = receivers.size();
9779        for (int i = 0; i < NR; i++) {
9780            final ResolveInfo info = receivers.get(i);
9781            if (info.activityInfo == null) {
9782                continue;
9783            }
9784
9785            if (packageName.equals(info.activityInfo.packageName)) {
9786                targetReceiver = info.activityInfo;
9787                break;
9788            }
9789        }
9790
9791        if (targetReceiver == null) {
9792            return null;
9793        }
9794
9795        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9796    }
9797
9798    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9799            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9800        if (pkgInfo.verifiers.length == 0) {
9801            return null;
9802        }
9803
9804        final int N = pkgInfo.verifiers.length;
9805        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9806        for (int i = 0; i < N; i++) {
9807            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9808
9809            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9810                    receivers);
9811            if (comp == null) {
9812                continue;
9813            }
9814
9815            final int verifierUid = getUidForVerifier(verifierInfo);
9816            if (verifierUid == -1) {
9817                continue;
9818            }
9819
9820            if (DEBUG_VERIFY) {
9821                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9822                        + " with the correct signature");
9823            }
9824            sufficientVerifiers.add(comp);
9825            verificationState.addSufficientVerifier(verifierUid);
9826        }
9827
9828        return sufficientVerifiers;
9829    }
9830
9831    private int getUidForVerifier(VerifierInfo verifierInfo) {
9832        synchronized (mPackages) {
9833            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9834            if (pkg == null) {
9835                return -1;
9836            } else if (pkg.mSignatures.length != 1) {
9837                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9838                        + " has more than one signature; ignoring");
9839                return -1;
9840            }
9841
9842            /*
9843             * If the public key of the package's signature does not match
9844             * our expected public key, then this is a different package and
9845             * we should skip.
9846             */
9847
9848            final byte[] expectedPublicKey;
9849            try {
9850                final Signature verifierSig = pkg.mSignatures[0];
9851                final PublicKey publicKey = verifierSig.getPublicKey();
9852                expectedPublicKey = publicKey.getEncoded();
9853            } catch (CertificateException e) {
9854                return -1;
9855            }
9856
9857            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9858
9859            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9860                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9861                        + " does not have the expected public key; ignoring");
9862                return -1;
9863            }
9864
9865            return pkg.applicationInfo.uid;
9866        }
9867    }
9868
9869    @Override
9870    public void finishPackageInstall(int token) {
9871        enforceSystemOrRoot("Only the system is allowed to finish installs");
9872
9873        if (DEBUG_INSTALL) {
9874            Slog.v(TAG, "BM finishing package install for " + token);
9875        }
9876
9877        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9878        mHandler.sendMessage(msg);
9879    }
9880
9881    /**
9882     * Get the verification agent timeout.
9883     *
9884     * @return verification timeout in milliseconds
9885     */
9886    private long getVerificationTimeout() {
9887        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9888                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9889                DEFAULT_VERIFICATION_TIMEOUT);
9890    }
9891
9892    /**
9893     * Get the default verification agent response code.
9894     *
9895     * @return default verification response code
9896     */
9897    private int getDefaultVerificationResponse() {
9898        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9899                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9900                DEFAULT_VERIFICATION_RESPONSE);
9901    }
9902
9903    /**
9904     * Check whether or not package verification has been enabled.
9905     *
9906     * @return true if verification should be performed
9907     */
9908    private boolean isVerificationEnabled(int userId, int installFlags) {
9909        if (!DEFAULT_VERIFY_ENABLE) {
9910            return false;
9911        }
9912
9913        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9914
9915        // Check if installing from ADB
9916        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9917            // Do not run verification in a test harness environment
9918            if (ActivityManager.isRunningInTestHarness()) {
9919                return false;
9920            }
9921            if (ensureVerifyAppsEnabled) {
9922                return true;
9923            }
9924            // Check if the developer does not want package verification for ADB installs
9925            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9926                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9927                return false;
9928            }
9929        }
9930
9931        if (ensureVerifyAppsEnabled) {
9932            return true;
9933        }
9934
9935        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9936                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9937    }
9938
9939    @Override
9940    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9941            throws RemoteException {
9942        mContext.enforceCallingOrSelfPermission(
9943                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9944                "Only intentfilter verification agents can verify applications");
9945
9946        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9947        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9948                Binder.getCallingUid(), verificationCode, failedDomains);
9949        msg.arg1 = id;
9950        msg.obj = response;
9951        mHandler.sendMessage(msg);
9952    }
9953
9954    @Override
9955    public int getIntentVerificationStatus(String packageName, int userId) {
9956        synchronized (mPackages) {
9957            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9958        }
9959    }
9960
9961    @Override
9962    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9963        mContext.enforceCallingOrSelfPermission(
9964                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9965
9966        boolean result = false;
9967        synchronized (mPackages) {
9968            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9969        }
9970        if (result) {
9971            scheduleWritePackageRestrictionsLocked(userId);
9972        }
9973        return result;
9974    }
9975
9976    @Override
9977    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9978        synchronized (mPackages) {
9979            return mSettings.getIntentFilterVerificationsLPr(packageName);
9980        }
9981    }
9982
9983    @Override
9984    public List<IntentFilter> getAllIntentFilters(String packageName) {
9985        if (TextUtils.isEmpty(packageName)) {
9986            return Collections.<IntentFilter>emptyList();
9987        }
9988        synchronized (mPackages) {
9989            PackageParser.Package pkg = mPackages.get(packageName);
9990            if (pkg == null || pkg.activities == null) {
9991                return Collections.<IntentFilter>emptyList();
9992            }
9993            final int count = pkg.activities.size();
9994            ArrayList<IntentFilter> result = new ArrayList<>();
9995            for (int n=0; n<count; n++) {
9996                PackageParser.Activity activity = pkg.activities.get(n);
9997                if (activity.intents != null || activity.intents.size() > 0) {
9998                    result.addAll(activity.intents);
9999                }
10000            }
10001            return result;
10002        }
10003    }
10004
10005    @Override
10006    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10007        mContext.enforceCallingOrSelfPermission(
10008                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10009
10010        synchronized (mPackages) {
10011            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10012            if (packageName != null) {
10013                result |= updateIntentVerificationStatus(packageName,
10014                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10015                        userId);
10016                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10017                        packageName, userId);
10018            }
10019            return result;
10020        }
10021    }
10022
10023    @Override
10024    public String getDefaultBrowserPackageName(int userId) {
10025        synchronized (mPackages) {
10026            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10027        }
10028    }
10029
10030    /**
10031     * Get the "allow unknown sources" setting.
10032     *
10033     * @return the current "allow unknown sources" setting
10034     */
10035    private int getUnknownSourcesSettings() {
10036        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10037                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10038                -1);
10039    }
10040
10041    @Override
10042    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10043        final int uid = Binder.getCallingUid();
10044        // writer
10045        synchronized (mPackages) {
10046            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10047            if (targetPackageSetting == null) {
10048                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10049            }
10050
10051            PackageSetting installerPackageSetting;
10052            if (installerPackageName != null) {
10053                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10054                if (installerPackageSetting == null) {
10055                    throw new IllegalArgumentException("Unknown installer package: "
10056                            + installerPackageName);
10057                }
10058            } else {
10059                installerPackageSetting = null;
10060            }
10061
10062            Signature[] callerSignature;
10063            Object obj = mSettings.getUserIdLPr(uid);
10064            if (obj != null) {
10065                if (obj instanceof SharedUserSetting) {
10066                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10067                } else if (obj instanceof PackageSetting) {
10068                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10069                } else {
10070                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10071                }
10072            } else {
10073                throw new SecurityException("Unknown calling uid " + uid);
10074            }
10075
10076            // Verify: can't set installerPackageName to a package that is
10077            // not signed with the same cert as the caller.
10078            if (installerPackageSetting != null) {
10079                if (compareSignatures(callerSignature,
10080                        installerPackageSetting.signatures.mSignatures)
10081                        != PackageManager.SIGNATURE_MATCH) {
10082                    throw new SecurityException(
10083                            "Caller does not have same cert as new installer package "
10084                            + installerPackageName);
10085                }
10086            }
10087
10088            // Verify: if target already has an installer package, it must
10089            // be signed with the same cert as the caller.
10090            if (targetPackageSetting.installerPackageName != null) {
10091                PackageSetting setting = mSettings.mPackages.get(
10092                        targetPackageSetting.installerPackageName);
10093                // If the currently set package isn't valid, then it's always
10094                // okay to change it.
10095                if (setting != null) {
10096                    if (compareSignatures(callerSignature,
10097                            setting.signatures.mSignatures)
10098                            != PackageManager.SIGNATURE_MATCH) {
10099                        throw new SecurityException(
10100                                "Caller does not have same cert as old installer package "
10101                                + targetPackageSetting.installerPackageName);
10102                    }
10103                }
10104            }
10105
10106            // Okay!
10107            targetPackageSetting.installerPackageName = installerPackageName;
10108            scheduleWriteSettingsLocked();
10109        }
10110    }
10111
10112    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10113        // Queue up an async operation since the package installation may take a little while.
10114        mHandler.post(new Runnable() {
10115            public void run() {
10116                mHandler.removeCallbacks(this);
10117                 // Result object to be returned
10118                PackageInstalledInfo res = new PackageInstalledInfo();
10119                res.returnCode = currentStatus;
10120                res.uid = -1;
10121                res.pkg = null;
10122                res.removedInfo = new PackageRemovedInfo();
10123                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10124                    args.doPreInstall(res.returnCode);
10125                    synchronized (mInstallLock) {
10126                        installPackageLI(args, res);
10127                    }
10128                    args.doPostInstall(res.returnCode, res.uid);
10129                }
10130
10131                // A restore should be performed at this point if (a) the install
10132                // succeeded, (b) the operation is not an update, and (c) the new
10133                // package has not opted out of backup participation.
10134                final boolean update = res.removedInfo.removedPackage != null;
10135                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10136                boolean doRestore = !update
10137                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10138
10139                // Set up the post-install work request bookkeeping.  This will be used
10140                // and cleaned up by the post-install event handling regardless of whether
10141                // there's a restore pass performed.  Token values are >= 1.
10142                int token;
10143                if (mNextInstallToken < 0) mNextInstallToken = 1;
10144                token = mNextInstallToken++;
10145
10146                PostInstallData data = new PostInstallData(args, res);
10147                mRunningInstalls.put(token, data);
10148                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10149
10150                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10151                    // Pass responsibility to the Backup Manager.  It will perform a
10152                    // restore if appropriate, then pass responsibility back to the
10153                    // Package Manager to run the post-install observer callbacks
10154                    // and broadcasts.
10155                    IBackupManager bm = IBackupManager.Stub.asInterface(
10156                            ServiceManager.getService(Context.BACKUP_SERVICE));
10157                    if (bm != null) {
10158                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10159                                + " to BM for possible restore");
10160                        try {
10161                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10162                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10163                            } else {
10164                                doRestore = false;
10165                            }
10166                        } catch (RemoteException e) {
10167                            // can't happen; the backup manager is local
10168                        } catch (Exception e) {
10169                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10170                            doRestore = false;
10171                        }
10172                    } else {
10173                        Slog.e(TAG, "Backup Manager not found!");
10174                        doRestore = false;
10175                    }
10176                }
10177
10178                if (!doRestore) {
10179                    // No restore possible, or the Backup Manager was mysteriously not
10180                    // available -- just fire the post-install work request directly.
10181                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10182                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10183                    mHandler.sendMessage(msg);
10184                }
10185            }
10186        });
10187    }
10188
10189    private abstract class HandlerParams {
10190        private static final int MAX_RETRIES = 4;
10191
10192        /**
10193         * Number of times startCopy() has been attempted and had a non-fatal
10194         * error.
10195         */
10196        private int mRetries = 0;
10197
10198        /** User handle for the user requesting the information or installation. */
10199        private final UserHandle mUser;
10200
10201        HandlerParams(UserHandle user) {
10202            mUser = user;
10203        }
10204
10205        UserHandle getUser() {
10206            return mUser;
10207        }
10208
10209        final boolean startCopy() {
10210            boolean res;
10211            try {
10212                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10213
10214                if (++mRetries > MAX_RETRIES) {
10215                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10216                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10217                    handleServiceError();
10218                    return false;
10219                } else {
10220                    handleStartCopy();
10221                    res = true;
10222                }
10223            } catch (RemoteException e) {
10224                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10225                mHandler.sendEmptyMessage(MCS_RECONNECT);
10226                res = false;
10227            }
10228            handleReturnCode();
10229            return res;
10230        }
10231
10232        final void serviceError() {
10233            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10234            handleServiceError();
10235            handleReturnCode();
10236        }
10237
10238        abstract void handleStartCopy() throws RemoteException;
10239        abstract void handleServiceError();
10240        abstract void handleReturnCode();
10241    }
10242
10243    class MeasureParams extends HandlerParams {
10244        private final PackageStats mStats;
10245        private boolean mSuccess;
10246
10247        private final IPackageStatsObserver mObserver;
10248
10249        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10250            super(new UserHandle(stats.userHandle));
10251            mObserver = observer;
10252            mStats = stats;
10253        }
10254
10255        @Override
10256        public String toString() {
10257            return "MeasureParams{"
10258                + Integer.toHexString(System.identityHashCode(this))
10259                + " " + mStats.packageName + "}";
10260        }
10261
10262        @Override
10263        void handleStartCopy() throws RemoteException {
10264            synchronized (mInstallLock) {
10265                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10266            }
10267
10268            if (mSuccess) {
10269                final boolean mounted;
10270                if (Environment.isExternalStorageEmulated()) {
10271                    mounted = true;
10272                } else {
10273                    final String status = Environment.getExternalStorageState();
10274                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10275                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10276                }
10277
10278                if (mounted) {
10279                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10280
10281                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10282                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10283
10284                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10285                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10286
10287                    // Always subtract cache size, since it's a subdirectory
10288                    mStats.externalDataSize -= mStats.externalCacheSize;
10289
10290                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10291                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10292
10293                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10294                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10295                }
10296            }
10297        }
10298
10299        @Override
10300        void handleReturnCode() {
10301            if (mObserver != null) {
10302                try {
10303                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10304                } catch (RemoteException e) {
10305                    Slog.i(TAG, "Observer no longer exists.");
10306                }
10307            }
10308        }
10309
10310        @Override
10311        void handleServiceError() {
10312            Slog.e(TAG, "Could not measure application " + mStats.packageName
10313                            + " external storage");
10314        }
10315    }
10316
10317    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10318            throws RemoteException {
10319        long result = 0;
10320        for (File path : paths) {
10321            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10322        }
10323        return result;
10324    }
10325
10326    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10327        for (File path : paths) {
10328            try {
10329                mcs.clearDirectory(path.getAbsolutePath());
10330            } catch (RemoteException e) {
10331            }
10332        }
10333    }
10334
10335    static class OriginInfo {
10336        /**
10337         * Location where install is coming from, before it has been
10338         * copied/renamed into place. This could be a single monolithic APK
10339         * file, or a cluster directory. This location may be untrusted.
10340         */
10341        final File file;
10342        final String cid;
10343
10344        /**
10345         * Flag indicating that {@link #file} or {@link #cid} has already been
10346         * staged, meaning downstream users don't need to defensively copy the
10347         * contents.
10348         */
10349        final boolean staged;
10350
10351        /**
10352         * Flag indicating that {@link #file} or {@link #cid} is an already
10353         * installed app that is being moved.
10354         */
10355        final boolean existing;
10356
10357        final String resolvedPath;
10358        final File resolvedFile;
10359
10360        static OriginInfo fromNothing() {
10361            return new OriginInfo(null, null, false, false);
10362        }
10363
10364        static OriginInfo fromUntrustedFile(File file) {
10365            return new OriginInfo(file, null, false, false);
10366        }
10367
10368        static OriginInfo fromExistingFile(File file) {
10369            return new OriginInfo(file, null, false, true);
10370        }
10371
10372        static OriginInfo fromStagedFile(File file) {
10373            return new OriginInfo(file, null, true, false);
10374        }
10375
10376        static OriginInfo fromStagedContainer(String cid) {
10377            return new OriginInfo(null, cid, true, false);
10378        }
10379
10380        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10381            this.file = file;
10382            this.cid = cid;
10383            this.staged = staged;
10384            this.existing = existing;
10385
10386            if (cid != null) {
10387                resolvedPath = PackageHelper.getSdDir(cid);
10388                resolvedFile = new File(resolvedPath);
10389            } else if (file != null) {
10390                resolvedPath = file.getAbsolutePath();
10391                resolvedFile = file;
10392            } else {
10393                resolvedPath = null;
10394                resolvedFile = null;
10395            }
10396        }
10397    }
10398
10399    class MoveInfo {
10400        final int moveId;
10401        final String fromUuid;
10402        final String toUuid;
10403        final String packageName;
10404        final String dataAppName;
10405        final int appId;
10406        final String seinfo;
10407
10408        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10409                String dataAppName, int appId, String seinfo) {
10410            this.moveId = moveId;
10411            this.fromUuid = fromUuid;
10412            this.toUuid = toUuid;
10413            this.packageName = packageName;
10414            this.dataAppName = dataAppName;
10415            this.appId = appId;
10416            this.seinfo = seinfo;
10417        }
10418    }
10419
10420    class InstallParams extends HandlerParams {
10421        final OriginInfo origin;
10422        final MoveInfo move;
10423        final IPackageInstallObserver2 observer;
10424        int installFlags;
10425        final String installerPackageName;
10426        final String volumeUuid;
10427        final VerificationParams verificationParams;
10428        private InstallArgs mArgs;
10429        private int mRet;
10430        final String packageAbiOverride;
10431        final String[] grantedRuntimePermissions;
10432
10433
10434        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10435                int installFlags, String installerPackageName, String volumeUuid,
10436                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10437                String[] grantedPermissions) {
10438            super(user);
10439            this.origin = origin;
10440            this.move = move;
10441            this.observer = observer;
10442            this.installFlags = installFlags;
10443            this.installerPackageName = installerPackageName;
10444            this.volumeUuid = volumeUuid;
10445            this.verificationParams = verificationParams;
10446            this.packageAbiOverride = packageAbiOverride;
10447            this.grantedRuntimePermissions = grantedPermissions;
10448        }
10449
10450        @Override
10451        public String toString() {
10452            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10453                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10454        }
10455
10456        public ManifestDigest getManifestDigest() {
10457            if (verificationParams == null) {
10458                return null;
10459            }
10460            return verificationParams.getManifestDigest();
10461        }
10462
10463        private int installLocationPolicy(PackageInfoLite pkgLite) {
10464            String packageName = pkgLite.packageName;
10465            int installLocation = pkgLite.installLocation;
10466            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10467            // reader
10468            synchronized (mPackages) {
10469                PackageParser.Package pkg = mPackages.get(packageName);
10470                if (pkg != null) {
10471                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10472                        // Check for downgrading.
10473                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10474                            try {
10475                                checkDowngrade(pkg, pkgLite);
10476                            } catch (PackageManagerException e) {
10477                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10478                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10479                            }
10480                        }
10481                        // Check for updated system application.
10482                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10483                            if (onSd) {
10484                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10485                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10486                            }
10487                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10488                        } else {
10489                            if (onSd) {
10490                                // Install flag overrides everything.
10491                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10492                            }
10493                            // If current upgrade specifies particular preference
10494                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10495                                // Application explicitly specified internal.
10496                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10497                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10498                                // App explictly prefers external. Let policy decide
10499                            } else {
10500                                // Prefer previous location
10501                                if (isExternal(pkg)) {
10502                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10503                                }
10504                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10505                            }
10506                        }
10507                    } else {
10508                        // Invalid install. Return error code
10509                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10510                    }
10511                }
10512            }
10513            // All the special cases have been taken care of.
10514            // Return result based on recommended install location.
10515            if (onSd) {
10516                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10517            }
10518            return pkgLite.recommendedInstallLocation;
10519        }
10520
10521        /*
10522         * Invoke remote method to get package information and install
10523         * location values. Override install location based on default
10524         * policy if needed and then create install arguments based
10525         * on the install location.
10526         */
10527        public void handleStartCopy() throws RemoteException {
10528            int ret = PackageManager.INSTALL_SUCCEEDED;
10529
10530            // If we're already staged, we've firmly committed to an install location
10531            if (origin.staged) {
10532                if (origin.file != null) {
10533                    installFlags |= PackageManager.INSTALL_INTERNAL;
10534                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10535                } else if (origin.cid != null) {
10536                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10537                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10538                } else {
10539                    throw new IllegalStateException("Invalid stage location");
10540                }
10541            }
10542
10543            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10544            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10545
10546            PackageInfoLite pkgLite = null;
10547
10548            if (onInt && onSd) {
10549                // Check if both bits are set.
10550                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10551                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10552            } else {
10553                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10554                        packageAbiOverride);
10555
10556                /*
10557                 * If we have too little free space, try to free cache
10558                 * before giving up.
10559                 */
10560                if (!origin.staged && pkgLite.recommendedInstallLocation
10561                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10562                    // TODO: focus freeing disk space on the target device
10563                    final StorageManager storage = StorageManager.from(mContext);
10564                    final long lowThreshold = storage.getStorageLowBytes(
10565                            Environment.getDataDirectory());
10566
10567                    final long sizeBytes = mContainerService.calculateInstalledSize(
10568                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10569
10570                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10571                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10572                                installFlags, packageAbiOverride);
10573                    }
10574
10575                    /*
10576                     * The cache free must have deleted the file we
10577                     * downloaded to install.
10578                     *
10579                     * TODO: fix the "freeCache" call to not delete
10580                     *       the file we care about.
10581                     */
10582                    if (pkgLite.recommendedInstallLocation
10583                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10584                        pkgLite.recommendedInstallLocation
10585                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10586                    }
10587                }
10588            }
10589
10590            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10591                int loc = pkgLite.recommendedInstallLocation;
10592                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10593                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10594                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10595                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10596                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10597                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10598                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10599                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10600                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10601                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10602                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10603                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10604                } else {
10605                    // Override with defaults if needed.
10606                    loc = installLocationPolicy(pkgLite);
10607                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10608                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10609                    } else if (!onSd && !onInt) {
10610                        // Override install location with flags
10611                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10612                            // Set the flag to install on external media.
10613                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10614                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10615                        } else {
10616                            // Make sure the flag for installing on external
10617                            // media is unset
10618                            installFlags |= PackageManager.INSTALL_INTERNAL;
10619                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10620                        }
10621                    }
10622                }
10623            }
10624
10625            final InstallArgs args = createInstallArgs(this);
10626            mArgs = args;
10627
10628            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10629                 /*
10630                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10631                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10632                 */
10633                int userIdentifier = getUser().getIdentifier();
10634                if (userIdentifier == UserHandle.USER_ALL
10635                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10636                    userIdentifier = UserHandle.USER_OWNER;
10637                }
10638
10639                /*
10640                 * Determine if we have any installed package verifiers. If we
10641                 * do, then we'll defer to them to verify the packages.
10642                 */
10643                final int requiredUid = mRequiredVerifierPackage == null ? -1
10644                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10645                if (!origin.existing && requiredUid != -1
10646                        && isVerificationEnabled(userIdentifier, installFlags)) {
10647                    final Intent verification = new Intent(
10648                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10649                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10650                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10651                            PACKAGE_MIME_TYPE);
10652                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10653
10654                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10655                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10656                            0 /* TODO: Which userId? */);
10657
10658                    if (DEBUG_VERIFY) {
10659                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10660                                + verification.toString() + " with " + pkgLite.verifiers.length
10661                                + " optional verifiers");
10662                    }
10663
10664                    final int verificationId = mPendingVerificationToken++;
10665
10666                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10667
10668                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10669                            installerPackageName);
10670
10671                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10672                            installFlags);
10673
10674                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10675                            pkgLite.packageName);
10676
10677                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10678                            pkgLite.versionCode);
10679
10680                    if (verificationParams != null) {
10681                        if (verificationParams.getVerificationURI() != null) {
10682                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10683                                 verificationParams.getVerificationURI());
10684                        }
10685                        if (verificationParams.getOriginatingURI() != null) {
10686                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10687                                  verificationParams.getOriginatingURI());
10688                        }
10689                        if (verificationParams.getReferrer() != null) {
10690                            verification.putExtra(Intent.EXTRA_REFERRER,
10691                                  verificationParams.getReferrer());
10692                        }
10693                        if (verificationParams.getOriginatingUid() >= 0) {
10694                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10695                                  verificationParams.getOriginatingUid());
10696                        }
10697                        if (verificationParams.getInstallerUid() >= 0) {
10698                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10699                                  verificationParams.getInstallerUid());
10700                        }
10701                    }
10702
10703                    final PackageVerificationState verificationState = new PackageVerificationState(
10704                            requiredUid, args);
10705
10706                    mPendingVerification.append(verificationId, verificationState);
10707
10708                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10709                            receivers, verificationState);
10710
10711                    // Apps installed for "all" users use the device owner to verify the app
10712                    UserHandle verifierUser = getUser();
10713                    if (verifierUser == UserHandle.ALL) {
10714                        verifierUser = UserHandle.OWNER;
10715                    }
10716
10717                    /*
10718                     * If any sufficient verifiers were listed in the package
10719                     * manifest, attempt to ask them.
10720                     */
10721                    if (sufficientVerifiers != null) {
10722                        final int N = sufficientVerifiers.size();
10723                        if (N == 0) {
10724                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10725                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10726                        } else {
10727                            for (int i = 0; i < N; i++) {
10728                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10729
10730                                final Intent sufficientIntent = new Intent(verification);
10731                                sufficientIntent.setComponent(verifierComponent);
10732                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10733                            }
10734                        }
10735                    }
10736
10737                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10738                            mRequiredVerifierPackage, receivers);
10739                    if (ret == PackageManager.INSTALL_SUCCEEDED
10740                            && mRequiredVerifierPackage != null) {
10741                        /*
10742                         * Send the intent to the required verification agent,
10743                         * but only start the verification timeout after the
10744                         * target BroadcastReceivers have run.
10745                         */
10746                        verification.setComponent(requiredVerifierComponent);
10747                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10748                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10749                                new BroadcastReceiver() {
10750                                    @Override
10751                                    public void onReceive(Context context, Intent intent) {
10752                                        final Message msg = mHandler
10753                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10754                                        msg.arg1 = verificationId;
10755                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10756                                    }
10757                                }, null, 0, null, null);
10758
10759                        /*
10760                         * We don't want the copy to proceed until verification
10761                         * succeeds, so null out this field.
10762                         */
10763                        mArgs = null;
10764                    }
10765                } else {
10766                    /*
10767                     * No package verification is enabled, so immediately start
10768                     * the remote call to initiate copy using temporary file.
10769                     */
10770                    ret = args.copyApk(mContainerService, true);
10771                }
10772            }
10773
10774            mRet = ret;
10775        }
10776
10777        @Override
10778        void handleReturnCode() {
10779            // If mArgs is null, then MCS couldn't be reached. When it
10780            // reconnects, it will try again to install. At that point, this
10781            // will succeed.
10782            if (mArgs != null) {
10783                processPendingInstall(mArgs, mRet);
10784            }
10785        }
10786
10787        @Override
10788        void handleServiceError() {
10789            mArgs = createInstallArgs(this);
10790            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10791        }
10792
10793        public boolean isForwardLocked() {
10794            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10795        }
10796    }
10797
10798    /**
10799     * Used during creation of InstallArgs
10800     *
10801     * @param installFlags package installation flags
10802     * @return true if should be installed on external storage
10803     */
10804    private static boolean installOnExternalAsec(int installFlags) {
10805        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10806            return false;
10807        }
10808        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10809            return true;
10810        }
10811        return false;
10812    }
10813
10814    /**
10815     * Used during creation of InstallArgs
10816     *
10817     * @param installFlags package installation flags
10818     * @return true if should be installed as forward locked
10819     */
10820    private static boolean installForwardLocked(int installFlags) {
10821        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10822    }
10823
10824    private InstallArgs createInstallArgs(InstallParams params) {
10825        if (params.move != null) {
10826            return new MoveInstallArgs(params);
10827        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10828            return new AsecInstallArgs(params);
10829        } else {
10830            return new FileInstallArgs(params);
10831        }
10832    }
10833
10834    /**
10835     * Create args that describe an existing installed package. Typically used
10836     * when cleaning up old installs, or used as a move source.
10837     */
10838    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10839            String resourcePath, String[] instructionSets) {
10840        final boolean isInAsec;
10841        if (installOnExternalAsec(installFlags)) {
10842            /* Apps on SD card are always in ASEC containers. */
10843            isInAsec = true;
10844        } else if (installForwardLocked(installFlags)
10845                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10846            /*
10847             * Forward-locked apps are only in ASEC containers if they're the
10848             * new style
10849             */
10850            isInAsec = true;
10851        } else {
10852            isInAsec = false;
10853        }
10854
10855        if (isInAsec) {
10856            return new AsecInstallArgs(codePath, instructionSets,
10857                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10858        } else {
10859            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10860        }
10861    }
10862
10863    static abstract class InstallArgs {
10864        /** @see InstallParams#origin */
10865        final OriginInfo origin;
10866        /** @see InstallParams#move */
10867        final MoveInfo move;
10868
10869        final IPackageInstallObserver2 observer;
10870        // Always refers to PackageManager flags only
10871        final int installFlags;
10872        final String installerPackageName;
10873        final String volumeUuid;
10874        final ManifestDigest manifestDigest;
10875        final UserHandle user;
10876        final String abiOverride;
10877        final String[] installGrantPermissions;
10878
10879        // The list of instruction sets supported by this app. This is currently
10880        // only used during the rmdex() phase to clean up resources. We can get rid of this
10881        // if we move dex files under the common app path.
10882        /* nullable */ String[] instructionSets;
10883
10884        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10885                int installFlags, String installerPackageName, String volumeUuid,
10886                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10887                String abiOverride, String[] installGrantPermissions) {
10888            this.origin = origin;
10889            this.move = move;
10890            this.installFlags = installFlags;
10891            this.observer = observer;
10892            this.installerPackageName = installerPackageName;
10893            this.volumeUuid = volumeUuid;
10894            this.manifestDigest = manifestDigest;
10895            this.user = user;
10896            this.instructionSets = instructionSets;
10897            this.abiOverride = abiOverride;
10898            this.installGrantPermissions = installGrantPermissions;
10899        }
10900
10901        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10902        abstract int doPreInstall(int status);
10903
10904        /**
10905         * Rename package into final resting place. All paths on the given
10906         * scanned package should be updated to reflect the rename.
10907         */
10908        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10909        abstract int doPostInstall(int status, int uid);
10910
10911        /** @see PackageSettingBase#codePathString */
10912        abstract String getCodePath();
10913        /** @see PackageSettingBase#resourcePathString */
10914        abstract String getResourcePath();
10915
10916        // Need installer lock especially for dex file removal.
10917        abstract void cleanUpResourcesLI();
10918        abstract boolean doPostDeleteLI(boolean delete);
10919
10920        /**
10921         * Called before the source arguments are copied. This is used mostly
10922         * for MoveParams when it needs to read the source file to put it in the
10923         * destination.
10924         */
10925        int doPreCopy() {
10926            return PackageManager.INSTALL_SUCCEEDED;
10927        }
10928
10929        /**
10930         * Called after the source arguments are copied. This is used mostly for
10931         * MoveParams when it needs to read the source file to put it in the
10932         * destination.
10933         *
10934         * @return
10935         */
10936        int doPostCopy(int uid) {
10937            return PackageManager.INSTALL_SUCCEEDED;
10938        }
10939
10940        protected boolean isFwdLocked() {
10941            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10942        }
10943
10944        protected boolean isExternalAsec() {
10945            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10946        }
10947
10948        UserHandle getUser() {
10949            return user;
10950        }
10951    }
10952
10953    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10954        if (!allCodePaths.isEmpty()) {
10955            if (instructionSets == null) {
10956                throw new IllegalStateException("instructionSet == null");
10957            }
10958            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10959            for (String codePath : allCodePaths) {
10960                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10961                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10962                    if (retCode < 0) {
10963                        Slog.w(TAG, "Couldn't remove dex file for package: "
10964                                + " at location " + codePath + ", retcode=" + retCode);
10965                        // we don't consider this to be a failure of the core package deletion
10966                    }
10967                }
10968            }
10969        }
10970    }
10971
10972    /**
10973     * Logic to handle installation of non-ASEC applications, including copying
10974     * and renaming logic.
10975     */
10976    class FileInstallArgs extends InstallArgs {
10977        private File codeFile;
10978        private File resourceFile;
10979
10980        // Example topology:
10981        // /data/app/com.example/base.apk
10982        // /data/app/com.example/split_foo.apk
10983        // /data/app/com.example/lib/arm/libfoo.so
10984        // /data/app/com.example/lib/arm64/libfoo.so
10985        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10986
10987        /** New install */
10988        FileInstallArgs(InstallParams params) {
10989            super(params.origin, params.move, params.observer, params.installFlags,
10990                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10991                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10992                    params.grantedRuntimePermissions);
10993            if (isFwdLocked()) {
10994                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10995            }
10996        }
10997
10998        /** Existing install */
10999        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11000            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11001                    null, null);
11002            this.codeFile = (codePath != null) ? new File(codePath) : null;
11003            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11004        }
11005
11006        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11007            if (origin.staged) {
11008                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11009                codeFile = origin.file;
11010                resourceFile = origin.file;
11011                return PackageManager.INSTALL_SUCCEEDED;
11012            }
11013
11014            try {
11015                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11016                codeFile = tempDir;
11017                resourceFile = tempDir;
11018            } catch (IOException e) {
11019                Slog.w(TAG, "Failed to create copy file: " + e);
11020                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11021            }
11022
11023            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11024                @Override
11025                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11026                    if (!FileUtils.isValidExtFilename(name)) {
11027                        throw new IllegalArgumentException("Invalid filename: " + name);
11028                    }
11029                    try {
11030                        final File file = new File(codeFile, name);
11031                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11032                                O_RDWR | O_CREAT, 0644);
11033                        Os.chmod(file.getAbsolutePath(), 0644);
11034                        return new ParcelFileDescriptor(fd);
11035                    } catch (ErrnoException e) {
11036                        throw new RemoteException("Failed to open: " + e.getMessage());
11037                    }
11038                }
11039            };
11040
11041            int ret = PackageManager.INSTALL_SUCCEEDED;
11042            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11043            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11044                Slog.e(TAG, "Failed to copy package");
11045                return ret;
11046            }
11047
11048            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11049            NativeLibraryHelper.Handle handle = null;
11050            try {
11051                handle = NativeLibraryHelper.Handle.create(codeFile);
11052                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11053                        abiOverride);
11054            } catch (IOException e) {
11055                Slog.e(TAG, "Copying native libraries failed", e);
11056                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11057            } finally {
11058                IoUtils.closeQuietly(handle);
11059            }
11060
11061            return ret;
11062        }
11063
11064        int doPreInstall(int status) {
11065            if (status != PackageManager.INSTALL_SUCCEEDED) {
11066                cleanUp();
11067            }
11068            return status;
11069        }
11070
11071        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11072            if (status != PackageManager.INSTALL_SUCCEEDED) {
11073                cleanUp();
11074                return false;
11075            }
11076
11077            final File targetDir = codeFile.getParentFile();
11078            final File beforeCodeFile = codeFile;
11079            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11080
11081            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11082            try {
11083                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11084            } catch (ErrnoException e) {
11085                Slog.w(TAG, "Failed to rename", e);
11086                return false;
11087            }
11088
11089            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11090                Slog.w(TAG, "Failed to restorecon");
11091                return false;
11092            }
11093
11094            // Reflect the rename internally
11095            codeFile = afterCodeFile;
11096            resourceFile = afterCodeFile;
11097
11098            // Reflect the rename in scanned details
11099            pkg.codePath = afterCodeFile.getAbsolutePath();
11100            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11101                    pkg.baseCodePath);
11102            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11103                    pkg.splitCodePaths);
11104
11105            // Reflect the rename in app info
11106            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11107            pkg.applicationInfo.setCodePath(pkg.codePath);
11108            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11109            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11110            pkg.applicationInfo.setResourcePath(pkg.codePath);
11111            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11112            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11113
11114            return true;
11115        }
11116
11117        int doPostInstall(int status, int uid) {
11118            if (status != PackageManager.INSTALL_SUCCEEDED) {
11119                cleanUp();
11120            }
11121            return status;
11122        }
11123
11124        @Override
11125        String getCodePath() {
11126            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11127        }
11128
11129        @Override
11130        String getResourcePath() {
11131            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11132        }
11133
11134        private boolean cleanUp() {
11135            if (codeFile == null || !codeFile.exists()) {
11136                return false;
11137            }
11138
11139            if (codeFile.isDirectory()) {
11140                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11141            } else {
11142                codeFile.delete();
11143            }
11144
11145            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11146                resourceFile.delete();
11147            }
11148
11149            return true;
11150        }
11151
11152        void cleanUpResourcesLI() {
11153            // Try enumerating all code paths before deleting
11154            List<String> allCodePaths = Collections.EMPTY_LIST;
11155            if (codeFile != null && codeFile.exists()) {
11156                try {
11157                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11158                    allCodePaths = pkg.getAllCodePaths();
11159                } catch (PackageParserException e) {
11160                    // Ignored; we tried our best
11161                }
11162            }
11163
11164            cleanUp();
11165            removeDexFiles(allCodePaths, instructionSets);
11166        }
11167
11168        boolean doPostDeleteLI(boolean delete) {
11169            // XXX err, shouldn't we respect the delete flag?
11170            cleanUpResourcesLI();
11171            return true;
11172        }
11173    }
11174
11175    private boolean isAsecExternal(String cid) {
11176        final String asecPath = PackageHelper.getSdFilesystem(cid);
11177        return !asecPath.startsWith(mAsecInternalPath);
11178    }
11179
11180    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11181            PackageManagerException {
11182        if (copyRet < 0) {
11183            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11184                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11185                throw new PackageManagerException(copyRet, message);
11186            }
11187        }
11188    }
11189
11190    /**
11191     * Extract the MountService "container ID" from the full code path of an
11192     * .apk.
11193     */
11194    static String cidFromCodePath(String fullCodePath) {
11195        int eidx = fullCodePath.lastIndexOf("/");
11196        String subStr1 = fullCodePath.substring(0, eidx);
11197        int sidx = subStr1.lastIndexOf("/");
11198        return subStr1.substring(sidx+1, eidx);
11199    }
11200
11201    /**
11202     * Logic to handle installation of ASEC applications, including copying and
11203     * renaming logic.
11204     */
11205    class AsecInstallArgs extends InstallArgs {
11206        static final String RES_FILE_NAME = "pkg.apk";
11207        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11208
11209        String cid;
11210        String packagePath;
11211        String resourcePath;
11212
11213        /** New install */
11214        AsecInstallArgs(InstallParams params) {
11215            super(params.origin, params.move, params.observer, params.installFlags,
11216                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11217                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11218                    params.grantedRuntimePermissions);
11219        }
11220
11221        /** Existing install */
11222        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11223                        boolean isExternal, boolean isForwardLocked) {
11224            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11225                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11226                    instructionSets, null, null);
11227            // Hackily pretend we're still looking at a full code path
11228            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11229                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11230            }
11231
11232            // Extract cid from fullCodePath
11233            int eidx = fullCodePath.lastIndexOf("/");
11234            String subStr1 = fullCodePath.substring(0, eidx);
11235            int sidx = subStr1.lastIndexOf("/");
11236            cid = subStr1.substring(sidx+1, eidx);
11237            setMountPath(subStr1);
11238        }
11239
11240        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11241            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11242                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11243                    instructionSets, null, null);
11244            this.cid = cid;
11245            setMountPath(PackageHelper.getSdDir(cid));
11246        }
11247
11248        void createCopyFile() {
11249            cid = mInstallerService.allocateExternalStageCidLegacy();
11250        }
11251
11252        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11253            if (origin.staged) {
11254                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11255                cid = origin.cid;
11256                setMountPath(PackageHelper.getSdDir(cid));
11257                return PackageManager.INSTALL_SUCCEEDED;
11258            }
11259
11260            if (temp) {
11261                createCopyFile();
11262            } else {
11263                /*
11264                 * Pre-emptively destroy the container since it's destroyed if
11265                 * copying fails due to it existing anyway.
11266                 */
11267                PackageHelper.destroySdDir(cid);
11268            }
11269
11270            final String newMountPath = imcs.copyPackageToContainer(
11271                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11272                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11273
11274            if (newMountPath != null) {
11275                setMountPath(newMountPath);
11276                return PackageManager.INSTALL_SUCCEEDED;
11277            } else {
11278                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11279            }
11280        }
11281
11282        @Override
11283        String getCodePath() {
11284            return packagePath;
11285        }
11286
11287        @Override
11288        String getResourcePath() {
11289            return resourcePath;
11290        }
11291
11292        int doPreInstall(int status) {
11293            if (status != PackageManager.INSTALL_SUCCEEDED) {
11294                // Destroy container
11295                PackageHelper.destroySdDir(cid);
11296            } else {
11297                boolean mounted = PackageHelper.isContainerMounted(cid);
11298                if (!mounted) {
11299                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11300                            Process.SYSTEM_UID);
11301                    if (newMountPath != null) {
11302                        setMountPath(newMountPath);
11303                    } else {
11304                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11305                    }
11306                }
11307            }
11308            return status;
11309        }
11310
11311        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11312            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11313            String newMountPath = null;
11314            if (PackageHelper.isContainerMounted(cid)) {
11315                // Unmount the container
11316                if (!PackageHelper.unMountSdDir(cid)) {
11317                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11318                    return false;
11319                }
11320            }
11321            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11322                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11323                        " which might be stale. Will try to clean up.");
11324                // Clean up the stale container and proceed to recreate.
11325                if (!PackageHelper.destroySdDir(newCacheId)) {
11326                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11327                    return false;
11328                }
11329                // Successfully cleaned up stale container. Try to rename again.
11330                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11331                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11332                            + " inspite of cleaning it up.");
11333                    return false;
11334                }
11335            }
11336            if (!PackageHelper.isContainerMounted(newCacheId)) {
11337                Slog.w(TAG, "Mounting container " + newCacheId);
11338                newMountPath = PackageHelper.mountSdDir(newCacheId,
11339                        getEncryptKey(), Process.SYSTEM_UID);
11340            } else {
11341                newMountPath = PackageHelper.getSdDir(newCacheId);
11342            }
11343            if (newMountPath == null) {
11344                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11345                return false;
11346            }
11347            Log.i(TAG, "Succesfully renamed " + cid +
11348                    " to " + newCacheId +
11349                    " at new path: " + newMountPath);
11350            cid = newCacheId;
11351
11352            final File beforeCodeFile = new File(packagePath);
11353            setMountPath(newMountPath);
11354            final File afterCodeFile = new File(packagePath);
11355
11356            // Reflect the rename in scanned details
11357            pkg.codePath = afterCodeFile.getAbsolutePath();
11358            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11359                    pkg.baseCodePath);
11360            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11361                    pkg.splitCodePaths);
11362
11363            // Reflect the rename in app info
11364            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11365            pkg.applicationInfo.setCodePath(pkg.codePath);
11366            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11367            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11368            pkg.applicationInfo.setResourcePath(pkg.codePath);
11369            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11370            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11371
11372            return true;
11373        }
11374
11375        private void setMountPath(String mountPath) {
11376            final File mountFile = new File(mountPath);
11377
11378            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11379            if (monolithicFile.exists()) {
11380                packagePath = monolithicFile.getAbsolutePath();
11381                if (isFwdLocked()) {
11382                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11383                } else {
11384                    resourcePath = packagePath;
11385                }
11386            } else {
11387                packagePath = mountFile.getAbsolutePath();
11388                resourcePath = packagePath;
11389            }
11390        }
11391
11392        int doPostInstall(int status, int uid) {
11393            if (status != PackageManager.INSTALL_SUCCEEDED) {
11394                cleanUp();
11395            } else {
11396                final int groupOwner;
11397                final String protectedFile;
11398                if (isFwdLocked()) {
11399                    groupOwner = UserHandle.getSharedAppGid(uid);
11400                    protectedFile = RES_FILE_NAME;
11401                } else {
11402                    groupOwner = -1;
11403                    protectedFile = null;
11404                }
11405
11406                if (uid < Process.FIRST_APPLICATION_UID
11407                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11408                    Slog.e(TAG, "Failed to finalize " + cid);
11409                    PackageHelper.destroySdDir(cid);
11410                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11411                }
11412
11413                boolean mounted = PackageHelper.isContainerMounted(cid);
11414                if (!mounted) {
11415                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11416                }
11417            }
11418            return status;
11419        }
11420
11421        private void cleanUp() {
11422            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11423
11424            // Destroy secure container
11425            PackageHelper.destroySdDir(cid);
11426        }
11427
11428        private List<String> getAllCodePaths() {
11429            final File codeFile = new File(getCodePath());
11430            if (codeFile != null && codeFile.exists()) {
11431                try {
11432                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11433                    return pkg.getAllCodePaths();
11434                } catch (PackageParserException e) {
11435                    // Ignored; we tried our best
11436                }
11437            }
11438            return Collections.EMPTY_LIST;
11439        }
11440
11441        void cleanUpResourcesLI() {
11442            // Enumerate all code paths before deleting
11443            cleanUpResourcesLI(getAllCodePaths());
11444        }
11445
11446        private void cleanUpResourcesLI(List<String> allCodePaths) {
11447            cleanUp();
11448            removeDexFiles(allCodePaths, instructionSets);
11449        }
11450
11451        String getPackageName() {
11452            return getAsecPackageName(cid);
11453        }
11454
11455        boolean doPostDeleteLI(boolean delete) {
11456            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11457            final List<String> allCodePaths = getAllCodePaths();
11458            boolean mounted = PackageHelper.isContainerMounted(cid);
11459            if (mounted) {
11460                // Unmount first
11461                if (PackageHelper.unMountSdDir(cid)) {
11462                    mounted = false;
11463                }
11464            }
11465            if (!mounted && delete) {
11466                cleanUpResourcesLI(allCodePaths);
11467            }
11468            return !mounted;
11469        }
11470
11471        @Override
11472        int doPreCopy() {
11473            if (isFwdLocked()) {
11474                if (!PackageHelper.fixSdPermissions(cid,
11475                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11476                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11477                }
11478            }
11479
11480            return PackageManager.INSTALL_SUCCEEDED;
11481        }
11482
11483        @Override
11484        int doPostCopy(int uid) {
11485            if (isFwdLocked()) {
11486                if (uid < Process.FIRST_APPLICATION_UID
11487                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11488                                RES_FILE_NAME)) {
11489                    Slog.e(TAG, "Failed to finalize " + cid);
11490                    PackageHelper.destroySdDir(cid);
11491                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11492                }
11493            }
11494
11495            return PackageManager.INSTALL_SUCCEEDED;
11496        }
11497    }
11498
11499    /**
11500     * Logic to handle movement of existing installed applications.
11501     */
11502    class MoveInstallArgs extends InstallArgs {
11503        private File codeFile;
11504        private File resourceFile;
11505
11506        /** New install */
11507        MoveInstallArgs(InstallParams params) {
11508            super(params.origin, params.move, params.observer, params.installFlags,
11509                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11510                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11511                    params.grantedRuntimePermissions);
11512        }
11513
11514        int copyApk(IMediaContainerService imcs, boolean temp) {
11515            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11516                    + move.fromUuid + " to " + move.toUuid);
11517            synchronized (mInstaller) {
11518                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11519                        move.dataAppName, move.appId, move.seinfo) != 0) {
11520                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11521                }
11522            }
11523
11524            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11525            resourceFile = codeFile;
11526            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11527
11528            return PackageManager.INSTALL_SUCCEEDED;
11529        }
11530
11531        int doPreInstall(int status) {
11532            if (status != PackageManager.INSTALL_SUCCEEDED) {
11533                cleanUp(move.toUuid);
11534            }
11535            return status;
11536        }
11537
11538        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11539            if (status != PackageManager.INSTALL_SUCCEEDED) {
11540                cleanUp(move.toUuid);
11541                return false;
11542            }
11543
11544            // Reflect the move in app info
11545            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11546            pkg.applicationInfo.setCodePath(pkg.codePath);
11547            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11548            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11549            pkg.applicationInfo.setResourcePath(pkg.codePath);
11550            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11551            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11552
11553            return true;
11554        }
11555
11556        int doPostInstall(int status, int uid) {
11557            if (status == PackageManager.INSTALL_SUCCEEDED) {
11558                cleanUp(move.fromUuid);
11559            } else {
11560                cleanUp(move.toUuid);
11561            }
11562            return status;
11563        }
11564
11565        @Override
11566        String getCodePath() {
11567            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11568        }
11569
11570        @Override
11571        String getResourcePath() {
11572            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11573        }
11574
11575        private boolean cleanUp(String volumeUuid) {
11576            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11577                    move.dataAppName);
11578            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11579            synchronized (mInstallLock) {
11580                // Clean up both app data and code
11581                removeDataDirsLI(volumeUuid, move.packageName);
11582                if (codeFile.isDirectory()) {
11583                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11584                } else {
11585                    codeFile.delete();
11586                }
11587            }
11588            return true;
11589        }
11590
11591        void cleanUpResourcesLI() {
11592            throw new UnsupportedOperationException();
11593        }
11594
11595        boolean doPostDeleteLI(boolean delete) {
11596            throw new UnsupportedOperationException();
11597        }
11598    }
11599
11600    static String getAsecPackageName(String packageCid) {
11601        int idx = packageCid.lastIndexOf("-");
11602        if (idx == -1) {
11603            return packageCid;
11604        }
11605        return packageCid.substring(0, idx);
11606    }
11607
11608    // Utility method used to create code paths based on package name and available index.
11609    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11610        String idxStr = "";
11611        int idx = 1;
11612        // Fall back to default value of idx=1 if prefix is not
11613        // part of oldCodePath
11614        if (oldCodePath != null) {
11615            String subStr = oldCodePath;
11616            // Drop the suffix right away
11617            if (suffix != null && subStr.endsWith(suffix)) {
11618                subStr = subStr.substring(0, subStr.length() - suffix.length());
11619            }
11620            // If oldCodePath already contains prefix find out the
11621            // ending index to either increment or decrement.
11622            int sidx = subStr.lastIndexOf(prefix);
11623            if (sidx != -1) {
11624                subStr = subStr.substring(sidx + prefix.length());
11625                if (subStr != null) {
11626                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11627                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11628                    }
11629                    try {
11630                        idx = Integer.parseInt(subStr);
11631                        if (idx <= 1) {
11632                            idx++;
11633                        } else {
11634                            idx--;
11635                        }
11636                    } catch(NumberFormatException e) {
11637                    }
11638                }
11639            }
11640        }
11641        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11642        return prefix + idxStr;
11643    }
11644
11645    private File getNextCodePath(File targetDir, String packageName) {
11646        int suffix = 1;
11647        File result;
11648        do {
11649            result = new File(targetDir, packageName + "-" + suffix);
11650            suffix++;
11651        } while (result.exists());
11652        return result;
11653    }
11654
11655    // Utility method that returns the relative package path with respect
11656    // to the installation directory. Like say for /data/data/com.test-1.apk
11657    // string com.test-1 is returned.
11658    static String deriveCodePathName(String codePath) {
11659        if (codePath == null) {
11660            return null;
11661        }
11662        final File codeFile = new File(codePath);
11663        final String name = codeFile.getName();
11664        if (codeFile.isDirectory()) {
11665            return name;
11666        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11667            final int lastDot = name.lastIndexOf('.');
11668            return name.substring(0, lastDot);
11669        } else {
11670            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11671            return null;
11672        }
11673    }
11674
11675    class PackageInstalledInfo {
11676        String name;
11677        int uid;
11678        // The set of users that originally had this package installed.
11679        int[] origUsers;
11680        // The set of users that now have this package installed.
11681        int[] newUsers;
11682        PackageParser.Package pkg;
11683        int returnCode;
11684        String returnMsg;
11685        PackageRemovedInfo removedInfo;
11686
11687        public void setError(int code, String msg) {
11688            returnCode = code;
11689            returnMsg = msg;
11690            Slog.w(TAG, msg);
11691        }
11692
11693        public void setError(String msg, PackageParserException e) {
11694            returnCode = e.error;
11695            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11696            Slog.w(TAG, msg, e);
11697        }
11698
11699        public void setError(String msg, PackageManagerException e) {
11700            returnCode = e.error;
11701            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11702            Slog.w(TAG, msg, e);
11703        }
11704
11705        // In some error cases we want to convey more info back to the observer
11706        String origPackage;
11707        String origPermission;
11708    }
11709
11710    /*
11711     * Install a non-existing package.
11712     */
11713    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11714            UserHandle user, String installerPackageName, String volumeUuid,
11715            PackageInstalledInfo res) {
11716        // Remember this for later, in case we need to rollback this install
11717        String pkgName = pkg.packageName;
11718
11719        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11720        final boolean dataDirExists = Environment
11721                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11722        synchronized(mPackages) {
11723            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11724                // A package with the same name is already installed, though
11725                // it has been renamed to an older name.  The package we
11726                // are trying to install should be installed as an update to
11727                // the existing one, but that has not been requested, so bail.
11728                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11729                        + " without first uninstalling package running as "
11730                        + mSettings.mRenamedPackages.get(pkgName));
11731                return;
11732            }
11733            if (mPackages.containsKey(pkgName)) {
11734                // Don't allow installation over an existing package with the same name.
11735                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11736                        + " without first uninstalling.");
11737                return;
11738            }
11739        }
11740
11741        try {
11742            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11743                    System.currentTimeMillis(), user);
11744
11745            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11746            // delete the partially installed application. the data directory will have to be
11747            // restored if it was already existing
11748            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11749                // remove package from internal structures.  Note that we want deletePackageX to
11750                // delete the package data and cache directories that it created in
11751                // scanPackageLocked, unless those directories existed before we even tried to
11752                // install.
11753                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11754                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11755                                res.removedInfo, true);
11756            }
11757
11758        } catch (PackageManagerException e) {
11759            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11760        }
11761    }
11762
11763    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11764        // Can't rotate keys during boot or if sharedUser.
11765        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11766                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11767            return false;
11768        }
11769        // app is using upgradeKeySets; make sure all are valid
11770        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11771        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11772        for (int i = 0; i < upgradeKeySets.length; i++) {
11773            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11774                Slog.wtf(TAG, "Package "
11775                         + (oldPs.name != null ? oldPs.name : "<null>")
11776                         + " contains upgrade-key-set reference to unknown key-set: "
11777                         + upgradeKeySets[i]
11778                         + " reverting to signatures check.");
11779                return false;
11780            }
11781        }
11782        return true;
11783    }
11784
11785    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11786        // Upgrade keysets are being used.  Determine if new package has a superset of the
11787        // required keys.
11788        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11789        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11790        for (int i = 0; i < upgradeKeySets.length; i++) {
11791            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11792            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11793                return true;
11794            }
11795        }
11796        return false;
11797    }
11798
11799    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11800            UserHandle user, String installerPackageName, String volumeUuid,
11801            PackageInstalledInfo res) {
11802        final PackageParser.Package oldPackage;
11803        final String pkgName = pkg.packageName;
11804        final int[] allUsers;
11805        final boolean[] perUserInstalled;
11806
11807        // First find the old package info and check signatures
11808        synchronized(mPackages) {
11809            oldPackage = mPackages.get(pkgName);
11810            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11811            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11812            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11813                if(!checkUpgradeKeySetLP(ps, pkg)) {
11814                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11815                            "New package not signed by keys specified by upgrade-keysets: "
11816                            + pkgName);
11817                    return;
11818                }
11819            } else {
11820                // default to original signature matching
11821                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11822                    != PackageManager.SIGNATURE_MATCH) {
11823                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11824                            "New package has a different signature: " + pkgName);
11825                    return;
11826                }
11827            }
11828
11829            // In case of rollback, remember per-user/profile install state
11830            allUsers = sUserManager.getUserIds();
11831            perUserInstalled = new boolean[allUsers.length];
11832            for (int i = 0; i < allUsers.length; i++) {
11833                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11834            }
11835        }
11836
11837        boolean sysPkg = (isSystemApp(oldPackage));
11838        if (sysPkg) {
11839            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11840                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11841        } else {
11842            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11843                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11844        }
11845    }
11846
11847    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11848            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11849            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11850            String volumeUuid, PackageInstalledInfo res) {
11851        String pkgName = deletedPackage.packageName;
11852        boolean deletedPkg = true;
11853        boolean updatedSettings = false;
11854
11855        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11856                + deletedPackage);
11857        long origUpdateTime;
11858        if (pkg.mExtras != null) {
11859            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11860        } else {
11861            origUpdateTime = 0;
11862        }
11863
11864        // First delete the existing package while retaining the data directory
11865        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11866                res.removedInfo, true)) {
11867            // If the existing package wasn't successfully deleted
11868            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11869            deletedPkg = false;
11870        } else {
11871            // Successfully deleted the old package; proceed with replace.
11872
11873            // If deleted package lived in a container, give users a chance to
11874            // relinquish resources before killing.
11875            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11876                if (DEBUG_INSTALL) {
11877                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11878                }
11879                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11880                final ArrayList<String> pkgList = new ArrayList<String>(1);
11881                pkgList.add(deletedPackage.applicationInfo.packageName);
11882                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11883            }
11884
11885            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11886            try {
11887                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11888                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11889                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11890                        perUserInstalled, res, user);
11891                updatedSettings = true;
11892            } catch (PackageManagerException e) {
11893                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11894            }
11895        }
11896
11897        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11898            // remove package from internal structures.  Note that we want deletePackageX to
11899            // delete the package data and cache directories that it created in
11900            // scanPackageLocked, unless those directories existed before we even tried to
11901            // install.
11902            if(updatedSettings) {
11903                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11904                deletePackageLI(
11905                        pkgName, null, true, allUsers, perUserInstalled,
11906                        PackageManager.DELETE_KEEP_DATA,
11907                                res.removedInfo, true);
11908            }
11909            // Since we failed to install the new package we need to restore the old
11910            // package that we deleted.
11911            if (deletedPkg) {
11912                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11913                File restoreFile = new File(deletedPackage.codePath);
11914                // Parse old package
11915                boolean oldExternal = isExternal(deletedPackage);
11916                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11917                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11918                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11919                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11920                try {
11921                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11922                } catch (PackageManagerException e) {
11923                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11924                            + e.getMessage());
11925                    return;
11926                }
11927                // Restore of old package succeeded. Update permissions.
11928                // writer
11929                synchronized (mPackages) {
11930                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11931                            UPDATE_PERMISSIONS_ALL);
11932                    // can downgrade to reader
11933                    mSettings.writeLPr();
11934                }
11935                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11936            }
11937        }
11938    }
11939
11940    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11941            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11942            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11943            String volumeUuid, PackageInstalledInfo res) {
11944        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11945                + ", old=" + deletedPackage);
11946        boolean disabledSystem = false;
11947        boolean updatedSettings = false;
11948        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11949        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11950                != 0) {
11951            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11952        }
11953        String packageName = deletedPackage.packageName;
11954        if (packageName == null) {
11955            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11956                    "Attempt to delete null packageName.");
11957            return;
11958        }
11959        PackageParser.Package oldPkg;
11960        PackageSetting oldPkgSetting;
11961        // reader
11962        synchronized (mPackages) {
11963            oldPkg = mPackages.get(packageName);
11964            oldPkgSetting = mSettings.mPackages.get(packageName);
11965            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11966                    (oldPkgSetting == null)) {
11967                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11968                        "Couldn't find package:" + packageName + " information");
11969                return;
11970            }
11971        }
11972
11973        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11974
11975        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11976        res.removedInfo.removedPackage = packageName;
11977        // Remove existing system package
11978        removePackageLI(oldPkgSetting, true);
11979        // writer
11980        synchronized (mPackages) {
11981            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11982            if (!disabledSystem && deletedPackage != null) {
11983                // We didn't need to disable the .apk as a current system package,
11984                // which means we are replacing another update that is already
11985                // installed.  We need to make sure to delete the older one's .apk.
11986                res.removedInfo.args = createInstallArgsForExisting(0,
11987                        deletedPackage.applicationInfo.getCodePath(),
11988                        deletedPackage.applicationInfo.getResourcePath(),
11989                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11990            } else {
11991                res.removedInfo.args = null;
11992            }
11993        }
11994
11995        // Successfully disabled the old package. Now proceed with re-installation
11996        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11997
11998        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11999        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12000
12001        PackageParser.Package newPackage = null;
12002        try {
12003            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12004            if (newPackage.mExtras != null) {
12005                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12006                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12007                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12008
12009                // is the update attempting to change shared user? that isn't going to work...
12010                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12011                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12012                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12013                            + " to " + newPkgSetting.sharedUser);
12014                    updatedSettings = true;
12015                }
12016            }
12017
12018            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12019                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12020                        perUserInstalled, res, user);
12021                updatedSettings = true;
12022            }
12023
12024        } catch (PackageManagerException e) {
12025            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12026        }
12027
12028        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12029            // Re installation failed. Restore old information
12030            // Remove new pkg information
12031            if (newPackage != null) {
12032                removeInstalledPackageLI(newPackage, true);
12033            }
12034            // Add back the old system package
12035            try {
12036                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12037            } catch (PackageManagerException e) {
12038                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12039            }
12040            // Restore the old system information in Settings
12041            synchronized (mPackages) {
12042                if (disabledSystem) {
12043                    mSettings.enableSystemPackageLPw(packageName);
12044                }
12045                if (updatedSettings) {
12046                    mSettings.setInstallerPackageName(packageName,
12047                            oldPkgSetting.installerPackageName);
12048                }
12049                mSettings.writeLPr();
12050            }
12051        }
12052    }
12053
12054    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12055            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12056            UserHandle user) {
12057        String pkgName = newPackage.packageName;
12058        synchronized (mPackages) {
12059            //write settings. the installStatus will be incomplete at this stage.
12060            //note that the new package setting would have already been
12061            //added to mPackages. It hasn't been persisted yet.
12062            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12063            mSettings.writeLPr();
12064        }
12065
12066        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12067
12068        synchronized (mPackages) {
12069            updatePermissionsLPw(newPackage.packageName, newPackage,
12070                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12071                            ? UPDATE_PERMISSIONS_ALL : 0));
12072            // For system-bundled packages, we assume that installing an upgraded version
12073            // of the package implies that the user actually wants to run that new code,
12074            // so we enable the package.
12075            PackageSetting ps = mSettings.mPackages.get(pkgName);
12076            if (ps != null) {
12077                if (isSystemApp(newPackage)) {
12078                    // NB: implicit assumption that system package upgrades apply to all users
12079                    if (DEBUG_INSTALL) {
12080                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12081                    }
12082                    if (res.origUsers != null) {
12083                        for (int userHandle : res.origUsers) {
12084                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12085                                    userHandle, installerPackageName);
12086                        }
12087                    }
12088                    // Also convey the prior install/uninstall state
12089                    if (allUsers != null && perUserInstalled != null) {
12090                        for (int i = 0; i < allUsers.length; i++) {
12091                            if (DEBUG_INSTALL) {
12092                                Slog.d(TAG, "    user " + allUsers[i]
12093                                        + " => " + perUserInstalled[i]);
12094                            }
12095                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12096                        }
12097                        // these install state changes will be persisted in the
12098                        // upcoming call to mSettings.writeLPr().
12099                    }
12100                }
12101                // It's implied that when a user requests installation, they want the app to be
12102                // installed and enabled.
12103                int userId = user.getIdentifier();
12104                if (userId != UserHandle.USER_ALL) {
12105                    ps.setInstalled(true, userId);
12106                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12107                }
12108            }
12109            res.name = pkgName;
12110            res.uid = newPackage.applicationInfo.uid;
12111            res.pkg = newPackage;
12112            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12113            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12114            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12115            //to update install status
12116            mSettings.writeLPr();
12117        }
12118    }
12119
12120    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12121        final int installFlags = args.installFlags;
12122        final String installerPackageName = args.installerPackageName;
12123        final String volumeUuid = args.volumeUuid;
12124        final File tmpPackageFile = new File(args.getCodePath());
12125        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12126        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12127                || (args.volumeUuid != null));
12128        boolean replace = false;
12129        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12130        if (args.move != null) {
12131            // moving a complete application; perfom an initial scan on the new install location
12132            scanFlags |= SCAN_INITIAL;
12133        }
12134        // Result object to be returned
12135        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12136
12137        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12138        // Retrieve PackageSettings and parse package
12139        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12140                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12141                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12142        PackageParser pp = new PackageParser();
12143        pp.setSeparateProcesses(mSeparateProcesses);
12144        pp.setDisplayMetrics(mMetrics);
12145
12146        final PackageParser.Package pkg;
12147        try {
12148            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12149        } catch (PackageParserException e) {
12150            res.setError("Failed parse during installPackageLI", e);
12151            return;
12152        }
12153
12154        // Mark that we have an install time CPU ABI override.
12155        pkg.cpuAbiOverride = args.abiOverride;
12156
12157        String pkgName = res.name = pkg.packageName;
12158        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12159            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12160                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12161                return;
12162            }
12163        }
12164
12165        try {
12166            pp.collectCertificates(pkg, parseFlags);
12167            pp.collectManifestDigest(pkg);
12168        } catch (PackageParserException e) {
12169            res.setError("Failed collect during installPackageLI", e);
12170            return;
12171        }
12172
12173        /* If the installer passed in a manifest digest, compare it now. */
12174        if (args.manifestDigest != null) {
12175            if (DEBUG_INSTALL) {
12176                final String parsedManifest = pkg.manifestDigest == null ? "null"
12177                        : pkg.manifestDigest.toString();
12178                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12179                        + parsedManifest);
12180            }
12181
12182            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12183                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12184                return;
12185            }
12186        } else if (DEBUG_INSTALL) {
12187            final String parsedManifest = pkg.manifestDigest == null
12188                    ? "null" : pkg.manifestDigest.toString();
12189            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12190        }
12191
12192        // Get rid of all references to package scan path via parser.
12193        pp = null;
12194        String oldCodePath = null;
12195        boolean systemApp = false;
12196        synchronized (mPackages) {
12197            // Check if installing already existing package
12198            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12199                String oldName = mSettings.mRenamedPackages.get(pkgName);
12200                if (pkg.mOriginalPackages != null
12201                        && pkg.mOriginalPackages.contains(oldName)
12202                        && mPackages.containsKey(oldName)) {
12203                    // This package is derived from an original package,
12204                    // and this device has been updating from that original
12205                    // name.  We must continue using the original name, so
12206                    // rename the new package here.
12207                    pkg.setPackageName(oldName);
12208                    pkgName = pkg.packageName;
12209                    replace = true;
12210                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12211                            + oldName + " pkgName=" + pkgName);
12212                } else if (mPackages.containsKey(pkgName)) {
12213                    // This package, under its official name, already exists
12214                    // on the device; we should replace it.
12215                    replace = true;
12216                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12217                }
12218
12219                // Prevent apps opting out from runtime permissions
12220                if (replace) {
12221                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12222                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12223                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12224                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12225                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12226                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12227                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12228                                        + " doesn't support runtime permissions but the old"
12229                                        + " target SDK " + oldTargetSdk + " does.");
12230                        return;
12231                    }
12232                }
12233            }
12234
12235            PackageSetting ps = mSettings.mPackages.get(pkgName);
12236            if (ps != null) {
12237                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12238
12239                // Quick sanity check that we're signed correctly if updating;
12240                // we'll check this again later when scanning, but we want to
12241                // bail early here before tripping over redefined permissions.
12242                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12243                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12244                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12245                                + pkg.packageName + " upgrade keys do not match the "
12246                                + "previously installed version");
12247                        return;
12248                    }
12249                } else {
12250                    try {
12251                        verifySignaturesLP(ps, pkg);
12252                    } catch (PackageManagerException e) {
12253                        res.setError(e.error, e.getMessage());
12254                        return;
12255                    }
12256                }
12257
12258                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12259                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12260                    systemApp = (ps.pkg.applicationInfo.flags &
12261                            ApplicationInfo.FLAG_SYSTEM) != 0;
12262                }
12263                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12264            }
12265
12266            // Check whether the newly-scanned package wants to define an already-defined perm
12267            int N = pkg.permissions.size();
12268            for (int i = N-1; i >= 0; i--) {
12269                PackageParser.Permission perm = pkg.permissions.get(i);
12270                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12271                if (bp != null) {
12272                    // If the defining package is signed with our cert, it's okay.  This
12273                    // also includes the "updating the same package" case, of course.
12274                    // "updating same package" could also involve key-rotation.
12275                    final boolean sigsOk;
12276                    if (bp.sourcePackage.equals(pkg.packageName)
12277                            && (bp.packageSetting instanceof PackageSetting)
12278                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12279                                    scanFlags))) {
12280                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12281                    } else {
12282                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12283                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12284                    }
12285                    if (!sigsOk) {
12286                        // If the owning package is the system itself, we log but allow
12287                        // install to proceed; we fail the install on all other permission
12288                        // redefinitions.
12289                        if (!bp.sourcePackage.equals("android")) {
12290                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12291                                    + pkg.packageName + " attempting to redeclare permission "
12292                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12293                            res.origPermission = perm.info.name;
12294                            res.origPackage = bp.sourcePackage;
12295                            return;
12296                        } else {
12297                            Slog.w(TAG, "Package " + pkg.packageName
12298                                    + " attempting to redeclare system permission "
12299                                    + perm.info.name + "; ignoring new declaration");
12300                            pkg.permissions.remove(i);
12301                        }
12302                    }
12303                }
12304            }
12305
12306        }
12307
12308        if (systemApp && onExternal) {
12309            // Disable updates to system apps on sdcard
12310            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12311                    "Cannot install updates to system apps on sdcard");
12312            return;
12313        }
12314
12315        if (args.move != null) {
12316            // We did an in-place move, so dex is ready to roll
12317            scanFlags |= SCAN_NO_DEX;
12318            scanFlags |= SCAN_MOVE;
12319
12320            synchronized (mPackages) {
12321                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12322                if (ps == null) {
12323                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12324                            "Missing settings for moved package " + pkgName);
12325                }
12326
12327                // We moved the entire application as-is, so bring over the
12328                // previously derived ABI information.
12329                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12330                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12331            }
12332
12333        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12334            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12335            scanFlags |= SCAN_NO_DEX;
12336
12337            try {
12338                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12339                        true /* extract libs */);
12340            } catch (PackageManagerException pme) {
12341                Slog.e(TAG, "Error deriving application ABI", pme);
12342                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12343                return;
12344            }
12345
12346            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12347            int result = mPackageDexOptimizer
12348                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12349                            false /* defer */, false /* inclDependencies */,
12350                            true /*bootComplete*/, false /*useJit*/);
12351            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12352                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12353                return;
12354            }
12355        }
12356
12357        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12358            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12359            return;
12360        }
12361
12362        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12363
12364        if (replace) {
12365            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12366                    installerPackageName, volumeUuid, res);
12367        } else {
12368            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12369                    args.user, installerPackageName, volumeUuid, res);
12370        }
12371        synchronized (mPackages) {
12372            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12373            if (ps != null) {
12374                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12375            }
12376        }
12377    }
12378
12379    private void startIntentFilterVerifications(int userId, boolean replacing,
12380            PackageParser.Package pkg) {
12381        if (mIntentFilterVerifierComponent == null) {
12382            Slog.w(TAG, "No IntentFilter verification will not be done as "
12383                    + "there is no IntentFilterVerifier available!");
12384            return;
12385        }
12386
12387        final int verifierUid = getPackageUid(
12388                mIntentFilterVerifierComponent.getPackageName(),
12389                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12390
12391        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12392        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12393        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12394        mHandler.sendMessage(msg);
12395    }
12396
12397    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12398            PackageParser.Package pkg) {
12399        int size = pkg.activities.size();
12400        if (size == 0) {
12401            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12402                    "No activity, so no need to verify any IntentFilter!");
12403            return;
12404        }
12405
12406        final boolean hasDomainURLs = hasDomainURLs(pkg);
12407        if (!hasDomainURLs) {
12408            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12409                    "No domain URLs, so no need to verify any IntentFilter!");
12410            return;
12411        }
12412
12413        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12414                + " if any IntentFilter from the " + size
12415                + " Activities needs verification ...");
12416
12417        int count = 0;
12418        final String packageName = pkg.packageName;
12419
12420        synchronized (mPackages) {
12421            // If this is a new install and we see that we've already run verification for this
12422            // package, we have nothing to do: it means the state was restored from backup.
12423            if (!replacing) {
12424                IntentFilterVerificationInfo ivi =
12425                        mSettings.getIntentFilterVerificationLPr(packageName);
12426                if (ivi != null) {
12427                    if (DEBUG_DOMAIN_VERIFICATION) {
12428                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12429                                + ivi.getStatusString());
12430                    }
12431                    return;
12432                }
12433            }
12434
12435            // If any filters need to be verified, then all need to be.
12436            boolean needToVerify = false;
12437            for (PackageParser.Activity a : pkg.activities) {
12438                for (ActivityIntentInfo filter : a.intents) {
12439                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12440                        if (DEBUG_DOMAIN_VERIFICATION) {
12441                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12442                        }
12443                        needToVerify = true;
12444                        break;
12445                    }
12446                }
12447            }
12448
12449            if (needToVerify) {
12450                final int verificationId = mIntentFilterVerificationToken++;
12451                for (PackageParser.Activity a : pkg.activities) {
12452                    for (ActivityIntentInfo filter : a.intents) {
12453                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12454                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12455                                    "Verification needed for IntentFilter:" + filter.toString());
12456                            mIntentFilterVerifier.addOneIntentFilterVerification(
12457                                    verifierUid, userId, verificationId, filter, packageName);
12458                            count++;
12459                        }
12460                    }
12461                }
12462            }
12463        }
12464
12465        if (count > 0) {
12466            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12467                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12468                    +  " for userId:" + userId);
12469            mIntentFilterVerifier.startVerifications(userId);
12470        } else {
12471            if (DEBUG_DOMAIN_VERIFICATION) {
12472                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12473            }
12474        }
12475    }
12476
12477    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12478        final ComponentName cn  = filter.activity.getComponentName();
12479        final String packageName = cn.getPackageName();
12480
12481        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12482                packageName);
12483        if (ivi == null) {
12484            return true;
12485        }
12486        int status = ivi.getStatus();
12487        switch (status) {
12488            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12489            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12490                return true;
12491
12492            default:
12493                // Nothing to do
12494                return false;
12495        }
12496    }
12497
12498    private static boolean isMultiArch(PackageSetting ps) {
12499        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12500    }
12501
12502    private static boolean isMultiArch(ApplicationInfo info) {
12503        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12504    }
12505
12506    private static boolean isExternal(PackageParser.Package pkg) {
12507        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12508    }
12509
12510    private static boolean isExternal(PackageSetting ps) {
12511        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12512    }
12513
12514    private static boolean isExternal(ApplicationInfo info) {
12515        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12516    }
12517
12518    private static boolean isSystemApp(PackageParser.Package pkg) {
12519        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12520    }
12521
12522    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12523        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12524    }
12525
12526    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12527        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12528    }
12529
12530    private static boolean isSystemApp(PackageSetting ps) {
12531        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12532    }
12533
12534    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12535        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12536    }
12537
12538    private int packageFlagsToInstallFlags(PackageSetting ps) {
12539        int installFlags = 0;
12540        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12541            // This existing package was an external ASEC install when we have
12542            // the external flag without a UUID
12543            installFlags |= PackageManager.INSTALL_EXTERNAL;
12544        }
12545        if (ps.isForwardLocked()) {
12546            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12547        }
12548        return installFlags;
12549    }
12550
12551    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12552        if (isExternal(pkg)) {
12553            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12554                return mSettings.getExternalVersion();
12555            } else {
12556                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12557            }
12558        } else {
12559            return mSettings.getInternalVersion();
12560        }
12561    }
12562
12563    private void deleteTempPackageFiles() {
12564        final FilenameFilter filter = new FilenameFilter() {
12565            public boolean accept(File dir, String name) {
12566                return name.startsWith("vmdl") && name.endsWith(".tmp");
12567            }
12568        };
12569        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12570            file.delete();
12571        }
12572    }
12573
12574    @Override
12575    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12576            int flags) {
12577        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12578                flags);
12579    }
12580
12581    @Override
12582    public void deletePackage(final String packageName,
12583            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12584        mContext.enforceCallingOrSelfPermission(
12585                android.Manifest.permission.DELETE_PACKAGES, null);
12586        Preconditions.checkNotNull(packageName);
12587        Preconditions.checkNotNull(observer);
12588        final int uid = Binder.getCallingUid();
12589        if (UserHandle.getUserId(uid) != userId) {
12590            mContext.enforceCallingPermission(
12591                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12592                    "deletePackage for user " + userId);
12593        }
12594        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12595            try {
12596                observer.onPackageDeleted(packageName,
12597                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12598            } catch (RemoteException re) {
12599            }
12600            return;
12601        }
12602
12603        boolean uninstallBlocked = false;
12604        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12605            int[] users = sUserManager.getUserIds();
12606            for (int i = 0; i < users.length; ++i) {
12607                if (getBlockUninstallForUser(packageName, users[i])) {
12608                    uninstallBlocked = true;
12609                    break;
12610                }
12611            }
12612        } else {
12613            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12614        }
12615        if (uninstallBlocked) {
12616            try {
12617                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12618                        null);
12619            } catch (RemoteException re) {
12620            }
12621            return;
12622        }
12623
12624        if (DEBUG_REMOVE) {
12625            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12626        }
12627        // Queue up an async operation since the package deletion may take a little while.
12628        mHandler.post(new Runnable() {
12629            public void run() {
12630                mHandler.removeCallbacks(this);
12631                final int returnCode = deletePackageX(packageName, userId, flags);
12632                if (observer != null) {
12633                    try {
12634                        observer.onPackageDeleted(packageName, returnCode, null);
12635                    } catch (RemoteException e) {
12636                        Log.i(TAG, "Observer no longer exists.");
12637                    } //end catch
12638                } //end if
12639            } //end run
12640        });
12641    }
12642
12643    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12644        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12645                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12646        try {
12647            if (dpm != null) {
12648                if (dpm.isDeviceOwner(packageName)) {
12649                    return true;
12650                }
12651                int[] users;
12652                if (userId == UserHandle.USER_ALL) {
12653                    users = sUserManager.getUserIds();
12654                } else {
12655                    users = new int[]{userId};
12656                }
12657                for (int i = 0; i < users.length; ++i) {
12658                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12659                        return true;
12660                    }
12661                }
12662            }
12663        } catch (RemoteException e) {
12664        }
12665        return false;
12666    }
12667
12668    /**
12669     *  This method is an internal method that could be get invoked either
12670     *  to delete an installed package or to clean up a failed installation.
12671     *  After deleting an installed package, a broadcast is sent to notify any
12672     *  listeners that the package has been installed. For cleaning up a failed
12673     *  installation, the broadcast is not necessary since the package's
12674     *  installation wouldn't have sent the initial broadcast either
12675     *  The key steps in deleting a package are
12676     *  deleting the package information in internal structures like mPackages,
12677     *  deleting the packages base directories through installd
12678     *  updating mSettings to reflect current status
12679     *  persisting settings for later use
12680     *  sending a broadcast if necessary
12681     */
12682    private int deletePackageX(String packageName, int userId, int flags) {
12683        final PackageRemovedInfo info = new PackageRemovedInfo();
12684        final boolean res;
12685
12686        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12687                ? UserHandle.ALL : new UserHandle(userId);
12688
12689        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12690            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12691            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12692        }
12693
12694        boolean removedForAllUsers = false;
12695        boolean systemUpdate = false;
12696
12697        // for the uninstall-updates case and restricted profiles, remember the per-
12698        // userhandle installed state
12699        int[] allUsers;
12700        boolean[] perUserInstalled;
12701        synchronized (mPackages) {
12702            PackageSetting ps = mSettings.mPackages.get(packageName);
12703            allUsers = sUserManager.getUserIds();
12704            perUserInstalled = new boolean[allUsers.length];
12705            for (int i = 0; i < allUsers.length; i++) {
12706                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12707            }
12708        }
12709
12710        synchronized (mInstallLock) {
12711            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12712            res = deletePackageLI(packageName, removeForUser,
12713                    true, allUsers, perUserInstalled,
12714                    flags | REMOVE_CHATTY, info, true);
12715            systemUpdate = info.isRemovedPackageSystemUpdate;
12716            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12717                removedForAllUsers = true;
12718            }
12719            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12720                    + " removedForAllUsers=" + removedForAllUsers);
12721        }
12722
12723        if (res) {
12724            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12725
12726            // If the removed package was a system update, the old system package
12727            // was re-enabled; we need to broadcast this information
12728            if (systemUpdate) {
12729                Bundle extras = new Bundle(1);
12730                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12731                        ? info.removedAppId : info.uid);
12732                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12733
12734                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12735                        extras, null, null, null);
12736                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12737                        extras, null, null, null);
12738                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12739                        null, packageName, null, null);
12740            }
12741        }
12742        // Force a gc here.
12743        Runtime.getRuntime().gc();
12744        // Delete the resources here after sending the broadcast to let
12745        // other processes clean up before deleting resources.
12746        if (info.args != null) {
12747            synchronized (mInstallLock) {
12748                info.args.doPostDeleteLI(true);
12749            }
12750        }
12751
12752        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12753    }
12754
12755    class PackageRemovedInfo {
12756        String removedPackage;
12757        int uid = -1;
12758        int removedAppId = -1;
12759        int[] removedUsers = null;
12760        boolean isRemovedPackageSystemUpdate = false;
12761        // Clean up resources deleted packages.
12762        InstallArgs args = null;
12763
12764        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12765            Bundle extras = new Bundle(1);
12766            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12767            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12768            if (replacing) {
12769                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12770            }
12771            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12772            if (removedPackage != null) {
12773                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12774                        extras, null, null, removedUsers);
12775                if (fullRemove && !replacing) {
12776                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12777                            extras, null, null, removedUsers);
12778                }
12779            }
12780            if (removedAppId >= 0) {
12781                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12782                        removedUsers);
12783            }
12784        }
12785    }
12786
12787    /*
12788     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12789     * flag is not set, the data directory is removed as well.
12790     * make sure this flag is set for partially installed apps. If not its meaningless to
12791     * delete a partially installed application.
12792     */
12793    private void removePackageDataLI(PackageSetting ps,
12794            int[] allUserHandles, boolean[] perUserInstalled,
12795            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12796        String packageName = ps.name;
12797        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12798        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12799        // Retrieve object to delete permissions for shared user later on
12800        final PackageSetting deletedPs;
12801        // reader
12802        synchronized (mPackages) {
12803            deletedPs = mSettings.mPackages.get(packageName);
12804            if (outInfo != null) {
12805                outInfo.removedPackage = packageName;
12806                outInfo.removedUsers = deletedPs != null
12807                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12808                        : null;
12809            }
12810        }
12811        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12812            removeDataDirsLI(ps.volumeUuid, packageName);
12813            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12814        }
12815        // writer
12816        synchronized (mPackages) {
12817            if (deletedPs != null) {
12818                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12819                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12820                    clearDefaultBrowserIfNeeded(packageName);
12821                    if (outInfo != null) {
12822                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12823                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12824                    }
12825                    updatePermissionsLPw(deletedPs.name, null, 0);
12826                    if (deletedPs.sharedUser != null) {
12827                        // Remove permissions associated with package. Since runtime
12828                        // permissions are per user we have to kill the removed package
12829                        // or packages running under the shared user of the removed
12830                        // package if revoking the permissions requested only by the removed
12831                        // package is successful and this causes a change in gids.
12832                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12833                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12834                                    userId);
12835                            if (userIdToKill == UserHandle.USER_ALL
12836                                    || userIdToKill >= UserHandle.USER_OWNER) {
12837                                // If gids changed for this user, kill all affected packages.
12838                                mHandler.post(new Runnable() {
12839                                    @Override
12840                                    public void run() {
12841                                        // This has to happen with no lock held.
12842                                        killApplication(deletedPs.name, deletedPs.appId,
12843                                                KILL_APP_REASON_GIDS_CHANGED);
12844                                    }
12845                                });
12846                                break;
12847                            }
12848                        }
12849                    }
12850                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12851                }
12852                // make sure to preserve per-user disabled state if this removal was just
12853                // a downgrade of a system app to the factory package
12854                if (allUserHandles != null && perUserInstalled != null) {
12855                    if (DEBUG_REMOVE) {
12856                        Slog.d(TAG, "Propagating install state across downgrade");
12857                    }
12858                    for (int i = 0; i < allUserHandles.length; i++) {
12859                        if (DEBUG_REMOVE) {
12860                            Slog.d(TAG, "    user " + allUserHandles[i]
12861                                    + " => " + perUserInstalled[i]);
12862                        }
12863                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12864                    }
12865                }
12866            }
12867            // can downgrade to reader
12868            if (writeSettings) {
12869                // Save settings now
12870                mSettings.writeLPr();
12871            }
12872        }
12873        if (outInfo != null) {
12874            // A user ID was deleted here. Go through all users and remove it
12875            // from KeyStore.
12876            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12877        }
12878    }
12879
12880    static boolean locationIsPrivileged(File path) {
12881        try {
12882            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12883                    .getCanonicalPath();
12884            return path.getCanonicalPath().startsWith(privilegedAppDir);
12885        } catch (IOException e) {
12886            Slog.e(TAG, "Unable to access code path " + path);
12887        }
12888        return false;
12889    }
12890
12891    /*
12892     * Tries to delete system package.
12893     */
12894    private boolean deleteSystemPackageLI(PackageSetting newPs,
12895            int[] allUserHandles, boolean[] perUserInstalled,
12896            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12897        final boolean applyUserRestrictions
12898                = (allUserHandles != null) && (perUserInstalled != null);
12899        PackageSetting disabledPs = null;
12900        // Confirm if the system package has been updated
12901        // An updated system app can be deleted. This will also have to restore
12902        // the system pkg from system partition
12903        // reader
12904        synchronized (mPackages) {
12905            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12906        }
12907        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12908                + " disabledPs=" + disabledPs);
12909        if (disabledPs == null) {
12910            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12911            return false;
12912        } else if (DEBUG_REMOVE) {
12913            Slog.d(TAG, "Deleting system pkg from data partition");
12914        }
12915        if (DEBUG_REMOVE) {
12916            if (applyUserRestrictions) {
12917                Slog.d(TAG, "Remembering install states:");
12918                for (int i = 0; i < allUserHandles.length; i++) {
12919                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12920                }
12921            }
12922        }
12923        // Delete the updated package
12924        outInfo.isRemovedPackageSystemUpdate = true;
12925        if (disabledPs.versionCode < newPs.versionCode) {
12926            // Delete data for downgrades
12927            flags &= ~PackageManager.DELETE_KEEP_DATA;
12928        } else {
12929            // Preserve data by setting flag
12930            flags |= PackageManager.DELETE_KEEP_DATA;
12931        }
12932        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12933                allUserHandles, perUserInstalled, outInfo, writeSettings);
12934        if (!ret) {
12935            return false;
12936        }
12937        // writer
12938        synchronized (mPackages) {
12939            // Reinstate the old system package
12940            mSettings.enableSystemPackageLPw(newPs.name);
12941            // Remove any native libraries from the upgraded package.
12942            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12943        }
12944        // Install the system package
12945        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12946        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12947        if (locationIsPrivileged(disabledPs.codePath)) {
12948            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12949        }
12950
12951        final PackageParser.Package newPkg;
12952        try {
12953            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12954        } catch (PackageManagerException e) {
12955            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12956            return false;
12957        }
12958
12959        // writer
12960        synchronized (mPackages) {
12961            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12962
12963            // Propagate the permissions state as we do not want to drop on the floor
12964            // runtime permissions. The update permissions method below will take
12965            // care of removing obsolete permissions and grant install permissions.
12966            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
12967            updatePermissionsLPw(newPkg.packageName, newPkg,
12968                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12969
12970            if (applyUserRestrictions) {
12971                if (DEBUG_REMOVE) {
12972                    Slog.d(TAG, "Propagating install state across reinstall");
12973                }
12974                for (int i = 0; i < allUserHandles.length; i++) {
12975                    if (DEBUG_REMOVE) {
12976                        Slog.d(TAG, "    user " + allUserHandles[i]
12977                                + " => " + perUserInstalled[i]);
12978                    }
12979                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12980
12981                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12982                }
12983                // Regardless of writeSettings we need to ensure that this restriction
12984                // state propagation is persisted
12985                mSettings.writeAllUsersPackageRestrictionsLPr();
12986            }
12987            // can downgrade to reader here
12988            if (writeSettings) {
12989                mSettings.writeLPr();
12990            }
12991        }
12992        return true;
12993    }
12994
12995    private boolean deleteInstalledPackageLI(PackageSetting ps,
12996            boolean deleteCodeAndResources, int flags,
12997            int[] allUserHandles, boolean[] perUserInstalled,
12998            PackageRemovedInfo outInfo, boolean writeSettings) {
12999        if (outInfo != null) {
13000            outInfo.uid = ps.appId;
13001        }
13002
13003        // Delete package data from internal structures and also remove data if flag is set
13004        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13005
13006        // Delete application code and resources
13007        if (deleteCodeAndResources && (outInfo != null)) {
13008            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13009                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13010            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13011        }
13012        return true;
13013    }
13014
13015    @Override
13016    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13017            int userId) {
13018        mContext.enforceCallingOrSelfPermission(
13019                android.Manifest.permission.DELETE_PACKAGES, null);
13020        synchronized (mPackages) {
13021            PackageSetting ps = mSettings.mPackages.get(packageName);
13022            if (ps == null) {
13023                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13024                return false;
13025            }
13026            if (!ps.getInstalled(userId)) {
13027                // Can't block uninstall for an app that is not installed or enabled.
13028                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13029                return false;
13030            }
13031            ps.setBlockUninstall(blockUninstall, userId);
13032            mSettings.writePackageRestrictionsLPr(userId);
13033        }
13034        return true;
13035    }
13036
13037    @Override
13038    public boolean getBlockUninstallForUser(String packageName, int userId) {
13039        synchronized (mPackages) {
13040            PackageSetting ps = mSettings.mPackages.get(packageName);
13041            if (ps == null) {
13042                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13043                return false;
13044            }
13045            return ps.getBlockUninstall(userId);
13046        }
13047    }
13048
13049    /*
13050     * This method handles package deletion in general
13051     */
13052    private boolean deletePackageLI(String packageName, UserHandle user,
13053            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13054            int flags, PackageRemovedInfo outInfo,
13055            boolean writeSettings) {
13056        if (packageName == null) {
13057            Slog.w(TAG, "Attempt to delete null packageName.");
13058            return false;
13059        }
13060        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13061        PackageSetting ps;
13062        boolean dataOnly = false;
13063        int removeUser = -1;
13064        int appId = -1;
13065        synchronized (mPackages) {
13066            ps = mSettings.mPackages.get(packageName);
13067            if (ps == null) {
13068                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13069                return false;
13070            }
13071            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13072                    && user.getIdentifier() != UserHandle.USER_ALL) {
13073                // The caller is asking that the package only be deleted for a single
13074                // user.  To do this, we just mark its uninstalled state and delete
13075                // its data.  If this is a system app, we only allow this to happen if
13076                // they have set the special DELETE_SYSTEM_APP which requests different
13077                // semantics than normal for uninstalling system apps.
13078                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13079                final int userId = user.getIdentifier();
13080                ps.setUserState(userId,
13081                        COMPONENT_ENABLED_STATE_DEFAULT,
13082                        false, //installed
13083                        true,  //stopped
13084                        true,  //notLaunched
13085                        false, //hidden
13086                        null, null, null,
13087                        false, // blockUninstall
13088                        ps.readUserState(userId).domainVerificationStatus, 0);
13089                if (!isSystemApp(ps)) {
13090                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13091                        // Other user still have this package installed, so all
13092                        // we need to do is clear this user's data and save that
13093                        // it is uninstalled.
13094                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13095                        removeUser = user.getIdentifier();
13096                        appId = ps.appId;
13097                        scheduleWritePackageRestrictionsLocked(removeUser);
13098                    } else {
13099                        // We need to set it back to 'installed' so the uninstall
13100                        // broadcasts will be sent correctly.
13101                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13102                        ps.setInstalled(true, user.getIdentifier());
13103                    }
13104                } else {
13105                    // This is a system app, so we assume that the
13106                    // other users still have this package installed, so all
13107                    // we need to do is clear this user's data and save that
13108                    // it is uninstalled.
13109                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13110                    removeUser = user.getIdentifier();
13111                    appId = ps.appId;
13112                    scheduleWritePackageRestrictionsLocked(removeUser);
13113                }
13114            }
13115        }
13116
13117        if (removeUser >= 0) {
13118            // From above, we determined that we are deleting this only
13119            // for a single user.  Continue the work here.
13120            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13121            if (outInfo != null) {
13122                outInfo.removedPackage = packageName;
13123                outInfo.removedAppId = appId;
13124                outInfo.removedUsers = new int[] {removeUser};
13125            }
13126            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13127            removeKeystoreDataIfNeeded(removeUser, appId);
13128            schedulePackageCleaning(packageName, removeUser, false);
13129            synchronized (mPackages) {
13130                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13131                    scheduleWritePackageRestrictionsLocked(removeUser);
13132                }
13133                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13134            }
13135            return true;
13136        }
13137
13138        if (dataOnly) {
13139            // Delete application data first
13140            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13141            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13142            return true;
13143        }
13144
13145        boolean ret = false;
13146        if (isSystemApp(ps)) {
13147            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13148            // When an updated system application is deleted we delete the existing resources as well and
13149            // fall back to existing code in system partition
13150            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13151                    flags, outInfo, writeSettings);
13152        } else {
13153            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13154            // Kill application pre-emptively especially for apps on sd.
13155            killApplication(packageName, ps.appId, "uninstall pkg");
13156            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13157                    allUserHandles, perUserInstalled,
13158                    outInfo, writeSettings);
13159        }
13160
13161        return ret;
13162    }
13163
13164    private final class ClearStorageConnection implements ServiceConnection {
13165        IMediaContainerService mContainerService;
13166
13167        @Override
13168        public void onServiceConnected(ComponentName name, IBinder service) {
13169            synchronized (this) {
13170                mContainerService = IMediaContainerService.Stub.asInterface(service);
13171                notifyAll();
13172            }
13173        }
13174
13175        @Override
13176        public void onServiceDisconnected(ComponentName name) {
13177        }
13178    }
13179
13180    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13181        final boolean mounted;
13182        if (Environment.isExternalStorageEmulated()) {
13183            mounted = true;
13184        } else {
13185            final String status = Environment.getExternalStorageState();
13186
13187            mounted = status.equals(Environment.MEDIA_MOUNTED)
13188                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13189        }
13190
13191        if (!mounted) {
13192            return;
13193        }
13194
13195        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13196        int[] users;
13197        if (userId == UserHandle.USER_ALL) {
13198            users = sUserManager.getUserIds();
13199        } else {
13200            users = new int[] { userId };
13201        }
13202        final ClearStorageConnection conn = new ClearStorageConnection();
13203        if (mContext.bindServiceAsUser(
13204                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13205            try {
13206                for (int curUser : users) {
13207                    long timeout = SystemClock.uptimeMillis() + 5000;
13208                    synchronized (conn) {
13209                        long now = SystemClock.uptimeMillis();
13210                        while (conn.mContainerService == null && now < timeout) {
13211                            try {
13212                                conn.wait(timeout - now);
13213                            } catch (InterruptedException e) {
13214                            }
13215                        }
13216                    }
13217                    if (conn.mContainerService == null) {
13218                        return;
13219                    }
13220
13221                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13222                    clearDirectory(conn.mContainerService,
13223                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13224                    if (allData) {
13225                        clearDirectory(conn.mContainerService,
13226                                userEnv.buildExternalStorageAppDataDirs(packageName));
13227                        clearDirectory(conn.mContainerService,
13228                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13229                    }
13230                }
13231            } finally {
13232                mContext.unbindService(conn);
13233            }
13234        }
13235    }
13236
13237    @Override
13238    public void clearApplicationUserData(final String packageName,
13239            final IPackageDataObserver observer, final int userId) {
13240        mContext.enforceCallingOrSelfPermission(
13241                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13242        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13243        // Queue up an async operation since the package deletion may take a little while.
13244        mHandler.post(new Runnable() {
13245            public void run() {
13246                mHandler.removeCallbacks(this);
13247                final boolean succeeded;
13248                synchronized (mInstallLock) {
13249                    succeeded = clearApplicationUserDataLI(packageName, userId);
13250                }
13251                clearExternalStorageDataSync(packageName, userId, true);
13252                if (succeeded) {
13253                    // invoke DeviceStorageMonitor's update method to clear any notifications
13254                    DeviceStorageMonitorInternal
13255                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13256                    if (dsm != null) {
13257                        dsm.checkMemory();
13258                    }
13259                }
13260                if(observer != null) {
13261                    try {
13262                        observer.onRemoveCompleted(packageName, succeeded);
13263                    } catch (RemoteException e) {
13264                        Log.i(TAG, "Observer no longer exists.");
13265                    }
13266                } //end if observer
13267            } //end run
13268        });
13269    }
13270
13271    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13272        if (packageName == null) {
13273            Slog.w(TAG, "Attempt to delete null packageName.");
13274            return false;
13275        }
13276
13277        // Try finding details about the requested package
13278        PackageParser.Package pkg;
13279        synchronized (mPackages) {
13280            pkg = mPackages.get(packageName);
13281            if (pkg == null) {
13282                final PackageSetting ps = mSettings.mPackages.get(packageName);
13283                if (ps != null) {
13284                    pkg = ps.pkg;
13285                }
13286            }
13287
13288            if (pkg == null) {
13289                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13290                return false;
13291            }
13292
13293            PackageSetting ps = (PackageSetting) pkg.mExtras;
13294            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13295        }
13296
13297        // Always delete data directories for package, even if we found no other
13298        // record of app. This helps users recover from UID mismatches without
13299        // resorting to a full data wipe.
13300        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13301        if (retCode < 0) {
13302            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13303            return false;
13304        }
13305
13306        final int appId = pkg.applicationInfo.uid;
13307        removeKeystoreDataIfNeeded(userId, appId);
13308
13309        // Create a native library symlink only if we have native libraries
13310        // and if the native libraries are 32 bit libraries. We do not provide
13311        // this symlink for 64 bit libraries.
13312        if (pkg.applicationInfo.primaryCpuAbi != null &&
13313                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13314            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13315            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13316                    nativeLibPath, userId) < 0) {
13317                Slog.w(TAG, "Failed linking native library dir");
13318                return false;
13319            }
13320        }
13321
13322        return true;
13323    }
13324
13325    /**
13326     * Reverts user permission state changes (permissions and flags) in
13327     * all packages for a given user.
13328     *
13329     * @param userId The device user for which to do a reset.
13330     */
13331    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13332        final int packageCount = mPackages.size();
13333        for (int i = 0; i < packageCount; i++) {
13334            PackageParser.Package pkg = mPackages.valueAt(i);
13335            PackageSetting ps = (PackageSetting) pkg.mExtras;
13336            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13337        }
13338    }
13339
13340    /**
13341     * Reverts user permission state changes (permissions and flags).
13342     *
13343     * @param ps The package for which to reset.
13344     * @param userId The device user for which to do a reset.
13345     */
13346    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13347            final PackageSetting ps, final int userId) {
13348        if (ps.pkg == null) {
13349            return;
13350        }
13351
13352        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13353                | FLAG_PERMISSION_USER_FIXED
13354                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13355
13356        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13357                | FLAG_PERMISSION_POLICY_FIXED;
13358
13359        boolean writeInstallPermissions = false;
13360        boolean writeRuntimePermissions = false;
13361
13362        final int permissionCount = ps.pkg.requestedPermissions.size();
13363        for (int i = 0; i < permissionCount; i++) {
13364            String permission = ps.pkg.requestedPermissions.get(i);
13365
13366            BasePermission bp = mSettings.mPermissions.get(permission);
13367            if (bp == null) {
13368                continue;
13369            }
13370
13371            // If shared user we just reset the state to which only this app contributed.
13372            if (ps.sharedUser != null) {
13373                boolean used = false;
13374                final int packageCount = ps.sharedUser.packages.size();
13375                for (int j = 0; j < packageCount; j++) {
13376                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13377                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13378                            && pkg.pkg.requestedPermissions.contains(permission)) {
13379                        used = true;
13380                        break;
13381                    }
13382                }
13383                if (used) {
13384                    continue;
13385                }
13386            }
13387
13388            PermissionsState permissionsState = ps.getPermissionsState();
13389
13390            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13391
13392            // Always clear the user settable flags.
13393            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13394                    bp.name) != null;
13395            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13396                if (hasInstallState) {
13397                    writeInstallPermissions = true;
13398                } else {
13399                    writeRuntimePermissions = true;
13400                }
13401            }
13402
13403            // Below is only runtime permission handling.
13404            if (!bp.isRuntime()) {
13405                continue;
13406            }
13407
13408            // Never clobber system or policy.
13409            if ((oldFlags & policyOrSystemFlags) != 0) {
13410                continue;
13411            }
13412
13413            // If this permission was granted by default, make sure it is.
13414            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13415                if (permissionsState.grantRuntimePermission(bp, userId)
13416                        != PERMISSION_OPERATION_FAILURE) {
13417                    writeRuntimePermissions = true;
13418                }
13419            } else {
13420                // Otherwise, reset the permission.
13421                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13422                switch (revokeResult) {
13423                    case PERMISSION_OPERATION_SUCCESS: {
13424                        writeRuntimePermissions = true;
13425                    } break;
13426
13427                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13428                        writeRuntimePermissions = true;
13429                        final int appId = ps.appId;
13430                        mHandler.post(new Runnable() {
13431                            @Override
13432                            public void run() {
13433                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13434                            }
13435                        });
13436                    } break;
13437                }
13438            }
13439        }
13440
13441        // Synchronously write as we are taking permissions away.
13442        if (writeRuntimePermissions) {
13443            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13444        }
13445
13446        // Synchronously write as we are taking permissions away.
13447        if (writeInstallPermissions) {
13448            mSettings.writeLPr();
13449        }
13450    }
13451
13452    /**
13453     * Remove entries from the keystore daemon. Will only remove it if the
13454     * {@code appId} is valid.
13455     */
13456    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13457        if (appId < 0) {
13458            return;
13459        }
13460
13461        final KeyStore keyStore = KeyStore.getInstance();
13462        if (keyStore != null) {
13463            if (userId == UserHandle.USER_ALL) {
13464                for (final int individual : sUserManager.getUserIds()) {
13465                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13466                }
13467            } else {
13468                keyStore.clearUid(UserHandle.getUid(userId, appId));
13469            }
13470        } else {
13471            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13472        }
13473    }
13474
13475    @Override
13476    public void deleteApplicationCacheFiles(final String packageName,
13477            final IPackageDataObserver observer) {
13478        mContext.enforceCallingOrSelfPermission(
13479                android.Manifest.permission.DELETE_CACHE_FILES, null);
13480        // Queue up an async operation since the package deletion may take a little while.
13481        final int userId = UserHandle.getCallingUserId();
13482        mHandler.post(new Runnable() {
13483            public void run() {
13484                mHandler.removeCallbacks(this);
13485                final boolean succeded;
13486                synchronized (mInstallLock) {
13487                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13488                }
13489                clearExternalStorageDataSync(packageName, userId, false);
13490                if (observer != null) {
13491                    try {
13492                        observer.onRemoveCompleted(packageName, succeded);
13493                    } catch (RemoteException e) {
13494                        Log.i(TAG, "Observer no longer exists.");
13495                    }
13496                } //end if observer
13497            } //end run
13498        });
13499    }
13500
13501    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13502        if (packageName == null) {
13503            Slog.w(TAG, "Attempt to delete null packageName.");
13504            return false;
13505        }
13506        PackageParser.Package p;
13507        synchronized (mPackages) {
13508            p = mPackages.get(packageName);
13509        }
13510        if (p == null) {
13511            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13512            return false;
13513        }
13514        final ApplicationInfo applicationInfo = p.applicationInfo;
13515        if (applicationInfo == null) {
13516            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13517            return false;
13518        }
13519        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13520        if (retCode < 0) {
13521            Slog.w(TAG, "Couldn't remove cache files for package: "
13522                       + packageName + " u" + userId);
13523            return false;
13524        }
13525        return true;
13526    }
13527
13528    @Override
13529    public void getPackageSizeInfo(final String packageName, int userHandle,
13530            final IPackageStatsObserver observer) {
13531        mContext.enforceCallingOrSelfPermission(
13532                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13533        if (packageName == null) {
13534            throw new IllegalArgumentException("Attempt to get size of null packageName");
13535        }
13536
13537        PackageStats stats = new PackageStats(packageName, userHandle);
13538
13539        /*
13540         * Queue up an async operation since the package measurement may take a
13541         * little while.
13542         */
13543        Message msg = mHandler.obtainMessage(INIT_COPY);
13544        msg.obj = new MeasureParams(stats, observer);
13545        mHandler.sendMessage(msg);
13546    }
13547
13548    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13549            PackageStats pStats) {
13550        if (packageName == null) {
13551            Slog.w(TAG, "Attempt to get size of null packageName.");
13552            return false;
13553        }
13554        PackageParser.Package p;
13555        boolean dataOnly = false;
13556        String libDirRoot = null;
13557        String asecPath = null;
13558        PackageSetting ps = null;
13559        synchronized (mPackages) {
13560            p = mPackages.get(packageName);
13561            ps = mSettings.mPackages.get(packageName);
13562            if(p == null) {
13563                dataOnly = true;
13564                if((ps == null) || (ps.pkg == null)) {
13565                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13566                    return false;
13567                }
13568                p = ps.pkg;
13569            }
13570            if (ps != null) {
13571                libDirRoot = ps.legacyNativeLibraryPathString;
13572            }
13573            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13574                final long token = Binder.clearCallingIdentity();
13575                try {
13576                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13577                    if (secureContainerId != null) {
13578                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13579                    }
13580                } finally {
13581                    Binder.restoreCallingIdentity(token);
13582                }
13583            }
13584        }
13585        String publicSrcDir = null;
13586        if(!dataOnly) {
13587            final ApplicationInfo applicationInfo = p.applicationInfo;
13588            if (applicationInfo == null) {
13589                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13590                return false;
13591            }
13592            if (p.isForwardLocked()) {
13593                publicSrcDir = applicationInfo.getBaseResourcePath();
13594            }
13595        }
13596        // TODO: extend to measure size of split APKs
13597        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13598        // not just the first level.
13599        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13600        // just the primary.
13601        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13602
13603        String apkPath;
13604        File packageDir = new File(p.codePath);
13605
13606        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13607            apkPath = packageDir.getAbsolutePath();
13608            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13609            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13610                libDirRoot = null;
13611            }
13612        } else {
13613            apkPath = p.baseCodePath;
13614        }
13615
13616        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13617                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13618        if (res < 0) {
13619            return false;
13620        }
13621
13622        // Fix-up for forward-locked applications in ASEC containers.
13623        if (!isExternal(p)) {
13624            pStats.codeSize += pStats.externalCodeSize;
13625            pStats.externalCodeSize = 0L;
13626        }
13627
13628        return true;
13629    }
13630
13631
13632    @Override
13633    public void addPackageToPreferred(String packageName) {
13634        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13635    }
13636
13637    @Override
13638    public void removePackageFromPreferred(String packageName) {
13639        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13640    }
13641
13642    @Override
13643    public List<PackageInfo> getPreferredPackages(int flags) {
13644        return new ArrayList<PackageInfo>();
13645    }
13646
13647    private int getUidTargetSdkVersionLockedLPr(int uid) {
13648        Object obj = mSettings.getUserIdLPr(uid);
13649        if (obj instanceof SharedUserSetting) {
13650            final SharedUserSetting sus = (SharedUserSetting) obj;
13651            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13652            final Iterator<PackageSetting> it = sus.packages.iterator();
13653            while (it.hasNext()) {
13654                final PackageSetting ps = it.next();
13655                if (ps.pkg != null) {
13656                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13657                    if (v < vers) vers = v;
13658                }
13659            }
13660            return vers;
13661        } else if (obj instanceof PackageSetting) {
13662            final PackageSetting ps = (PackageSetting) obj;
13663            if (ps.pkg != null) {
13664                return ps.pkg.applicationInfo.targetSdkVersion;
13665            }
13666        }
13667        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13668    }
13669
13670    @Override
13671    public void addPreferredActivity(IntentFilter filter, int match,
13672            ComponentName[] set, ComponentName activity, int userId) {
13673        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13674                "Adding preferred");
13675    }
13676
13677    private void addPreferredActivityInternal(IntentFilter filter, int match,
13678            ComponentName[] set, ComponentName activity, boolean always, int userId,
13679            String opname) {
13680        // writer
13681        int callingUid = Binder.getCallingUid();
13682        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13683        if (filter.countActions() == 0) {
13684            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13685            return;
13686        }
13687        synchronized (mPackages) {
13688            if (mContext.checkCallingOrSelfPermission(
13689                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13690                    != PackageManager.PERMISSION_GRANTED) {
13691                if (getUidTargetSdkVersionLockedLPr(callingUid)
13692                        < Build.VERSION_CODES.FROYO) {
13693                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13694                            + callingUid);
13695                    return;
13696                }
13697                mContext.enforceCallingOrSelfPermission(
13698                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13699            }
13700
13701            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13702            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13703                    + userId + ":");
13704            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13705            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13706            scheduleWritePackageRestrictionsLocked(userId);
13707        }
13708    }
13709
13710    @Override
13711    public void replacePreferredActivity(IntentFilter filter, int match,
13712            ComponentName[] set, ComponentName activity, int userId) {
13713        if (filter.countActions() != 1) {
13714            throw new IllegalArgumentException(
13715                    "replacePreferredActivity expects filter to have only 1 action.");
13716        }
13717        if (filter.countDataAuthorities() != 0
13718                || filter.countDataPaths() != 0
13719                || filter.countDataSchemes() > 1
13720                || filter.countDataTypes() != 0) {
13721            throw new IllegalArgumentException(
13722                    "replacePreferredActivity expects filter to have no data authorities, " +
13723                    "paths, or types; and at most one scheme.");
13724        }
13725
13726        final int callingUid = Binder.getCallingUid();
13727        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13728        synchronized (mPackages) {
13729            if (mContext.checkCallingOrSelfPermission(
13730                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13731                    != PackageManager.PERMISSION_GRANTED) {
13732                if (getUidTargetSdkVersionLockedLPr(callingUid)
13733                        < Build.VERSION_CODES.FROYO) {
13734                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13735                            + Binder.getCallingUid());
13736                    return;
13737                }
13738                mContext.enforceCallingOrSelfPermission(
13739                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13740            }
13741
13742            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13743            if (pir != null) {
13744                // Get all of the existing entries that exactly match this filter.
13745                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13746                if (existing != null && existing.size() == 1) {
13747                    PreferredActivity cur = existing.get(0);
13748                    if (DEBUG_PREFERRED) {
13749                        Slog.i(TAG, "Checking replace of preferred:");
13750                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13751                        if (!cur.mPref.mAlways) {
13752                            Slog.i(TAG, "  -- CUR; not mAlways!");
13753                        } else {
13754                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13755                            Slog.i(TAG, "  -- CUR: mSet="
13756                                    + Arrays.toString(cur.mPref.mSetComponents));
13757                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13758                            Slog.i(TAG, "  -- NEW: mMatch="
13759                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13760                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13761                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13762                        }
13763                    }
13764                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13765                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13766                            && cur.mPref.sameSet(set)) {
13767                        // Setting the preferred activity to what it happens to be already
13768                        if (DEBUG_PREFERRED) {
13769                            Slog.i(TAG, "Replacing with same preferred activity "
13770                                    + cur.mPref.mShortComponent + " for user "
13771                                    + userId + ":");
13772                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13773                        }
13774                        return;
13775                    }
13776                }
13777
13778                if (existing != null) {
13779                    if (DEBUG_PREFERRED) {
13780                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13781                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13782                    }
13783                    for (int i = 0; i < existing.size(); i++) {
13784                        PreferredActivity pa = existing.get(i);
13785                        if (DEBUG_PREFERRED) {
13786                            Slog.i(TAG, "Removing existing preferred activity "
13787                                    + pa.mPref.mComponent + ":");
13788                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13789                        }
13790                        pir.removeFilter(pa);
13791                    }
13792                }
13793            }
13794            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13795                    "Replacing preferred");
13796        }
13797    }
13798
13799    @Override
13800    public void clearPackagePreferredActivities(String packageName) {
13801        final int uid = Binder.getCallingUid();
13802        // writer
13803        synchronized (mPackages) {
13804            PackageParser.Package pkg = mPackages.get(packageName);
13805            if (pkg == null || pkg.applicationInfo.uid != uid) {
13806                if (mContext.checkCallingOrSelfPermission(
13807                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13808                        != PackageManager.PERMISSION_GRANTED) {
13809                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13810                            < Build.VERSION_CODES.FROYO) {
13811                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13812                                + Binder.getCallingUid());
13813                        return;
13814                    }
13815                    mContext.enforceCallingOrSelfPermission(
13816                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13817                }
13818            }
13819
13820            int user = UserHandle.getCallingUserId();
13821            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13822                scheduleWritePackageRestrictionsLocked(user);
13823            }
13824        }
13825    }
13826
13827    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13828    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13829        ArrayList<PreferredActivity> removed = null;
13830        boolean changed = false;
13831        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13832            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13833            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13834            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13835                continue;
13836            }
13837            Iterator<PreferredActivity> it = pir.filterIterator();
13838            while (it.hasNext()) {
13839                PreferredActivity pa = it.next();
13840                // Mark entry for removal only if it matches the package name
13841                // and the entry is of type "always".
13842                if (packageName == null ||
13843                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13844                                && pa.mPref.mAlways)) {
13845                    if (removed == null) {
13846                        removed = new ArrayList<PreferredActivity>();
13847                    }
13848                    removed.add(pa);
13849                }
13850            }
13851            if (removed != null) {
13852                for (int j=0; j<removed.size(); j++) {
13853                    PreferredActivity pa = removed.get(j);
13854                    pir.removeFilter(pa);
13855                }
13856                changed = true;
13857            }
13858        }
13859        return changed;
13860    }
13861
13862    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13863    private void clearIntentFilterVerificationsLPw(int userId) {
13864        final int packageCount = mPackages.size();
13865        for (int i = 0; i < packageCount; i++) {
13866            PackageParser.Package pkg = mPackages.valueAt(i);
13867            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13868        }
13869    }
13870
13871    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13872    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13873        if (userId == UserHandle.USER_ALL) {
13874            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13875                    sUserManager.getUserIds())) {
13876                for (int oneUserId : sUserManager.getUserIds()) {
13877                    scheduleWritePackageRestrictionsLocked(oneUserId);
13878                }
13879            }
13880        } else {
13881            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13882                scheduleWritePackageRestrictionsLocked(userId);
13883            }
13884        }
13885    }
13886
13887    void clearDefaultBrowserIfNeeded(String packageName) {
13888        for (int oneUserId : sUserManager.getUserIds()) {
13889            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13890            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13891            if (packageName.equals(defaultBrowserPackageName)) {
13892                setDefaultBrowserPackageName(null, oneUserId);
13893            }
13894        }
13895    }
13896
13897    @Override
13898    public void resetApplicationPreferences(int userId) {
13899        mContext.enforceCallingOrSelfPermission(
13900                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13901        // writer
13902        synchronized (mPackages) {
13903            final long identity = Binder.clearCallingIdentity();
13904            try {
13905                clearPackagePreferredActivitiesLPw(null, userId);
13906                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13907                // TODO: We have to reset the default SMS and Phone. This requires
13908                // significant refactoring to keep all default apps in the package
13909                // manager (cleaner but more work) or have the services provide
13910                // callbacks to the package manager to request a default app reset.
13911                applyFactoryDefaultBrowserLPw(userId);
13912                clearIntentFilterVerificationsLPw(userId);
13913                primeDomainVerificationsLPw(userId);
13914                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13915                scheduleWritePackageRestrictionsLocked(userId);
13916            } finally {
13917                Binder.restoreCallingIdentity(identity);
13918            }
13919        }
13920    }
13921
13922    @Override
13923    public int getPreferredActivities(List<IntentFilter> outFilters,
13924            List<ComponentName> outActivities, String packageName) {
13925
13926        int num = 0;
13927        final int userId = UserHandle.getCallingUserId();
13928        // reader
13929        synchronized (mPackages) {
13930            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13931            if (pir != null) {
13932                final Iterator<PreferredActivity> it = pir.filterIterator();
13933                while (it.hasNext()) {
13934                    final PreferredActivity pa = it.next();
13935                    if (packageName == null
13936                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13937                                    && pa.mPref.mAlways)) {
13938                        if (outFilters != null) {
13939                            outFilters.add(new IntentFilter(pa));
13940                        }
13941                        if (outActivities != null) {
13942                            outActivities.add(pa.mPref.mComponent);
13943                        }
13944                    }
13945                }
13946            }
13947        }
13948
13949        return num;
13950    }
13951
13952    @Override
13953    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13954            int userId) {
13955        int callingUid = Binder.getCallingUid();
13956        if (callingUid != Process.SYSTEM_UID) {
13957            throw new SecurityException(
13958                    "addPersistentPreferredActivity can only be run by the system");
13959        }
13960        if (filter.countActions() == 0) {
13961            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13962            return;
13963        }
13964        synchronized (mPackages) {
13965            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13966                    " :");
13967            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13968            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13969                    new PersistentPreferredActivity(filter, activity));
13970            scheduleWritePackageRestrictionsLocked(userId);
13971        }
13972    }
13973
13974    @Override
13975    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13976        int callingUid = Binder.getCallingUid();
13977        if (callingUid != Process.SYSTEM_UID) {
13978            throw new SecurityException(
13979                    "clearPackagePersistentPreferredActivities can only be run by the system");
13980        }
13981        ArrayList<PersistentPreferredActivity> removed = null;
13982        boolean changed = false;
13983        synchronized (mPackages) {
13984            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13985                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13986                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13987                        .valueAt(i);
13988                if (userId != thisUserId) {
13989                    continue;
13990                }
13991                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13992                while (it.hasNext()) {
13993                    PersistentPreferredActivity ppa = it.next();
13994                    // Mark entry for removal only if it matches the package name.
13995                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13996                        if (removed == null) {
13997                            removed = new ArrayList<PersistentPreferredActivity>();
13998                        }
13999                        removed.add(ppa);
14000                    }
14001                }
14002                if (removed != null) {
14003                    for (int j=0; j<removed.size(); j++) {
14004                        PersistentPreferredActivity ppa = removed.get(j);
14005                        ppir.removeFilter(ppa);
14006                    }
14007                    changed = true;
14008                }
14009            }
14010
14011            if (changed) {
14012                scheduleWritePackageRestrictionsLocked(userId);
14013            }
14014        }
14015    }
14016
14017    /**
14018     * Common machinery for picking apart a restored XML blob and passing
14019     * it to a caller-supplied functor to be applied to the running system.
14020     */
14021    private void restoreFromXml(XmlPullParser parser, int userId,
14022            String expectedStartTag, BlobXmlRestorer functor)
14023            throws IOException, XmlPullParserException {
14024        int type;
14025        while ((type = parser.next()) != XmlPullParser.START_TAG
14026                && type != XmlPullParser.END_DOCUMENT) {
14027        }
14028        if (type != XmlPullParser.START_TAG) {
14029            // oops didn't find a start tag?!
14030            if (DEBUG_BACKUP) {
14031                Slog.e(TAG, "Didn't find start tag during restore");
14032            }
14033            return;
14034        }
14035
14036        // this is supposed to be TAG_PREFERRED_BACKUP
14037        if (!expectedStartTag.equals(parser.getName())) {
14038            if (DEBUG_BACKUP) {
14039                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14040            }
14041            return;
14042        }
14043
14044        // skip interfering stuff, then we're aligned with the backing implementation
14045        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14046        functor.apply(parser, userId);
14047    }
14048
14049    private interface BlobXmlRestorer {
14050        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14051    }
14052
14053    /**
14054     * Non-Binder method, support for the backup/restore mechanism: write the
14055     * full set of preferred activities in its canonical XML format.  Returns the
14056     * XML output as a byte array, or null if there is none.
14057     */
14058    @Override
14059    public byte[] getPreferredActivityBackup(int userId) {
14060        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14061            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14062        }
14063
14064        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14065        try {
14066            final XmlSerializer serializer = new FastXmlSerializer();
14067            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14068            serializer.startDocument(null, true);
14069            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14070
14071            synchronized (mPackages) {
14072                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14073            }
14074
14075            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14076            serializer.endDocument();
14077            serializer.flush();
14078        } catch (Exception e) {
14079            if (DEBUG_BACKUP) {
14080                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14081            }
14082            return null;
14083        }
14084
14085        return dataStream.toByteArray();
14086    }
14087
14088    @Override
14089    public void restorePreferredActivities(byte[] backup, int userId) {
14090        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14091            throw new SecurityException("Only the system may call restorePreferredActivities()");
14092        }
14093
14094        try {
14095            final XmlPullParser parser = Xml.newPullParser();
14096            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14097            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14098                    new BlobXmlRestorer() {
14099                        @Override
14100                        public void apply(XmlPullParser parser, int userId)
14101                                throws XmlPullParserException, IOException {
14102                            synchronized (mPackages) {
14103                                mSettings.readPreferredActivitiesLPw(parser, userId);
14104                            }
14105                        }
14106                    } );
14107        } catch (Exception e) {
14108            if (DEBUG_BACKUP) {
14109                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14110            }
14111        }
14112    }
14113
14114    /**
14115     * Non-Binder method, support for the backup/restore mechanism: write the
14116     * default browser (etc) settings in its canonical XML format.  Returns the default
14117     * browser XML representation as a byte array, or null if there is none.
14118     */
14119    @Override
14120    public byte[] getDefaultAppsBackup(int userId) {
14121        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14122            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14123        }
14124
14125        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14126        try {
14127            final XmlSerializer serializer = new FastXmlSerializer();
14128            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14129            serializer.startDocument(null, true);
14130            serializer.startTag(null, TAG_DEFAULT_APPS);
14131
14132            synchronized (mPackages) {
14133                mSettings.writeDefaultAppsLPr(serializer, userId);
14134            }
14135
14136            serializer.endTag(null, TAG_DEFAULT_APPS);
14137            serializer.endDocument();
14138            serializer.flush();
14139        } catch (Exception e) {
14140            if (DEBUG_BACKUP) {
14141                Slog.e(TAG, "Unable to write default apps for backup", e);
14142            }
14143            return null;
14144        }
14145
14146        return dataStream.toByteArray();
14147    }
14148
14149    @Override
14150    public void restoreDefaultApps(byte[] backup, int userId) {
14151        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14152            throw new SecurityException("Only the system may call restoreDefaultApps()");
14153        }
14154
14155        try {
14156            final XmlPullParser parser = Xml.newPullParser();
14157            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14158            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14159                    new BlobXmlRestorer() {
14160                        @Override
14161                        public void apply(XmlPullParser parser, int userId)
14162                                throws XmlPullParserException, IOException {
14163                            synchronized (mPackages) {
14164                                mSettings.readDefaultAppsLPw(parser, userId);
14165                            }
14166                        }
14167                    } );
14168        } catch (Exception e) {
14169            if (DEBUG_BACKUP) {
14170                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14171            }
14172        }
14173    }
14174
14175    @Override
14176    public byte[] getIntentFilterVerificationBackup(int userId) {
14177        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14178            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14179        }
14180
14181        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14182        try {
14183            final XmlSerializer serializer = new FastXmlSerializer();
14184            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14185            serializer.startDocument(null, true);
14186            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14187
14188            synchronized (mPackages) {
14189                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14190            }
14191
14192            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14193            serializer.endDocument();
14194            serializer.flush();
14195        } catch (Exception e) {
14196            if (DEBUG_BACKUP) {
14197                Slog.e(TAG, "Unable to write default apps for backup", e);
14198            }
14199            return null;
14200        }
14201
14202        return dataStream.toByteArray();
14203    }
14204
14205    @Override
14206    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14207        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14208            throw new SecurityException("Only the system may call restorePreferredActivities()");
14209        }
14210
14211        try {
14212            final XmlPullParser parser = Xml.newPullParser();
14213            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14214            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14215                    new BlobXmlRestorer() {
14216                        @Override
14217                        public void apply(XmlPullParser parser, int userId)
14218                                throws XmlPullParserException, IOException {
14219                            synchronized (mPackages) {
14220                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14221                                mSettings.writeLPr();
14222                            }
14223                        }
14224                    } );
14225        } catch (Exception e) {
14226            if (DEBUG_BACKUP) {
14227                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14228            }
14229        }
14230    }
14231
14232    @Override
14233    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14234            int sourceUserId, int targetUserId, int flags) {
14235        mContext.enforceCallingOrSelfPermission(
14236                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14237        int callingUid = Binder.getCallingUid();
14238        enforceOwnerRights(ownerPackage, callingUid);
14239        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14240        if (intentFilter.countActions() == 0) {
14241            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14242            return;
14243        }
14244        synchronized (mPackages) {
14245            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14246                    ownerPackage, targetUserId, flags);
14247            CrossProfileIntentResolver resolver =
14248                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14249            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14250            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14251            if (existing != null) {
14252                int size = existing.size();
14253                for (int i = 0; i < size; i++) {
14254                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14255                        return;
14256                    }
14257                }
14258            }
14259            resolver.addFilter(newFilter);
14260            scheduleWritePackageRestrictionsLocked(sourceUserId);
14261        }
14262    }
14263
14264    @Override
14265    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14266        mContext.enforceCallingOrSelfPermission(
14267                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14268        int callingUid = Binder.getCallingUid();
14269        enforceOwnerRights(ownerPackage, callingUid);
14270        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14271        synchronized (mPackages) {
14272            CrossProfileIntentResolver resolver =
14273                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14274            ArraySet<CrossProfileIntentFilter> set =
14275                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14276            for (CrossProfileIntentFilter filter : set) {
14277                if (filter.getOwnerPackage().equals(ownerPackage)) {
14278                    resolver.removeFilter(filter);
14279                }
14280            }
14281            scheduleWritePackageRestrictionsLocked(sourceUserId);
14282        }
14283    }
14284
14285    // Enforcing that callingUid is owning pkg on userId
14286    private void enforceOwnerRights(String pkg, int callingUid) {
14287        // The system owns everything.
14288        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14289            return;
14290        }
14291        int callingUserId = UserHandle.getUserId(callingUid);
14292        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14293        if (pi == null) {
14294            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14295                    + callingUserId);
14296        }
14297        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14298            throw new SecurityException("Calling uid " + callingUid
14299                    + " does not own package " + pkg);
14300        }
14301    }
14302
14303    @Override
14304    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14305        Intent intent = new Intent(Intent.ACTION_MAIN);
14306        intent.addCategory(Intent.CATEGORY_HOME);
14307
14308        final int callingUserId = UserHandle.getCallingUserId();
14309        List<ResolveInfo> list = queryIntentActivities(intent, null,
14310                PackageManager.GET_META_DATA, callingUserId);
14311        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14312                true, false, false, callingUserId);
14313
14314        allHomeCandidates.clear();
14315        if (list != null) {
14316            for (ResolveInfo ri : list) {
14317                allHomeCandidates.add(ri);
14318            }
14319        }
14320        return (preferred == null || preferred.activityInfo == null)
14321                ? null
14322                : new ComponentName(preferred.activityInfo.packageName,
14323                        preferred.activityInfo.name);
14324    }
14325
14326    @Override
14327    public void setApplicationEnabledSetting(String appPackageName,
14328            int newState, int flags, int userId, String callingPackage) {
14329        if (!sUserManager.exists(userId)) return;
14330        if (callingPackage == null) {
14331            callingPackage = Integer.toString(Binder.getCallingUid());
14332        }
14333        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14334    }
14335
14336    @Override
14337    public void setComponentEnabledSetting(ComponentName componentName,
14338            int newState, int flags, int userId) {
14339        if (!sUserManager.exists(userId)) return;
14340        setEnabledSetting(componentName.getPackageName(),
14341                componentName.getClassName(), newState, flags, userId, null);
14342    }
14343
14344    private void setEnabledSetting(final String packageName, String className, int newState,
14345            final int flags, int userId, String callingPackage) {
14346        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14347              || newState == COMPONENT_ENABLED_STATE_ENABLED
14348              || newState == COMPONENT_ENABLED_STATE_DISABLED
14349              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14350              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14351            throw new IllegalArgumentException("Invalid new component state: "
14352                    + newState);
14353        }
14354        PackageSetting pkgSetting;
14355        final int uid = Binder.getCallingUid();
14356        final int permission = mContext.checkCallingOrSelfPermission(
14357                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14358        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14359        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14360        boolean sendNow = false;
14361        boolean isApp = (className == null);
14362        String componentName = isApp ? packageName : className;
14363        int packageUid = -1;
14364        ArrayList<String> components;
14365
14366        // writer
14367        synchronized (mPackages) {
14368            pkgSetting = mSettings.mPackages.get(packageName);
14369            if (pkgSetting == null) {
14370                if (className == null) {
14371                    throw new IllegalArgumentException(
14372                            "Unknown package: " + packageName);
14373                }
14374                throw new IllegalArgumentException(
14375                        "Unknown component: " + packageName
14376                        + "/" + className);
14377            }
14378            // Allow root and verify that userId is not being specified by a different user
14379            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14380                throw new SecurityException(
14381                        "Permission Denial: attempt to change component state from pid="
14382                        + Binder.getCallingPid()
14383                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14384            }
14385            if (className == null) {
14386                // We're dealing with an application/package level state change
14387                if (pkgSetting.getEnabled(userId) == newState) {
14388                    // Nothing to do
14389                    return;
14390                }
14391                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14392                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14393                    // Don't care about who enables an app.
14394                    callingPackage = null;
14395                }
14396                pkgSetting.setEnabled(newState, userId, callingPackage);
14397                // pkgSetting.pkg.mSetEnabled = newState;
14398            } else {
14399                // We're dealing with a component level state change
14400                // First, verify that this is a valid class name.
14401                PackageParser.Package pkg = pkgSetting.pkg;
14402                if (pkg == null || !pkg.hasComponentClassName(className)) {
14403                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14404                        throw new IllegalArgumentException("Component class " + className
14405                                + " does not exist in " + packageName);
14406                    } else {
14407                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14408                                + className + " does not exist in " + packageName);
14409                    }
14410                }
14411                switch (newState) {
14412                case COMPONENT_ENABLED_STATE_ENABLED:
14413                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14414                        return;
14415                    }
14416                    break;
14417                case COMPONENT_ENABLED_STATE_DISABLED:
14418                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14419                        return;
14420                    }
14421                    break;
14422                case COMPONENT_ENABLED_STATE_DEFAULT:
14423                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14424                        return;
14425                    }
14426                    break;
14427                default:
14428                    Slog.e(TAG, "Invalid new component state: " + newState);
14429                    return;
14430                }
14431            }
14432            scheduleWritePackageRestrictionsLocked(userId);
14433            components = mPendingBroadcasts.get(userId, packageName);
14434            final boolean newPackage = components == null;
14435            if (newPackage) {
14436                components = new ArrayList<String>();
14437            }
14438            if (!components.contains(componentName)) {
14439                components.add(componentName);
14440            }
14441            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14442                sendNow = true;
14443                // Purge entry from pending broadcast list if another one exists already
14444                // since we are sending one right away.
14445                mPendingBroadcasts.remove(userId, packageName);
14446            } else {
14447                if (newPackage) {
14448                    mPendingBroadcasts.put(userId, packageName, components);
14449                }
14450                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14451                    // Schedule a message
14452                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14453                }
14454            }
14455        }
14456
14457        long callingId = Binder.clearCallingIdentity();
14458        try {
14459            if (sendNow) {
14460                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14461                sendPackageChangedBroadcast(packageName,
14462                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14463            }
14464        } finally {
14465            Binder.restoreCallingIdentity(callingId);
14466        }
14467    }
14468
14469    private void sendPackageChangedBroadcast(String packageName,
14470            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14471        if (DEBUG_INSTALL)
14472            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14473                    + componentNames);
14474        Bundle extras = new Bundle(4);
14475        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14476        String nameList[] = new String[componentNames.size()];
14477        componentNames.toArray(nameList);
14478        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14479        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14480        extras.putInt(Intent.EXTRA_UID, packageUid);
14481        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14482                new int[] {UserHandle.getUserId(packageUid)});
14483    }
14484
14485    @Override
14486    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14487        if (!sUserManager.exists(userId)) return;
14488        final int uid = Binder.getCallingUid();
14489        final int permission = mContext.checkCallingOrSelfPermission(
14490                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14491        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14492        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14493        // writer
14494        synchronized (mPackages) {
14495            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14496                    allowedByPermission, uid, userId)) {
14497                scheduleWritePackageRestrictionsLocked(userId);
14498            }
14499        }
14500    }
14501
14502    @Override
14503    public String getInstallerPackageName(String packageName) {
14504        // reader
14505        synchronized (mPackages) {
14506            return mSettings.getInstallerPackageNameLPr(packageName);
14507        }
14508    }
14509
14510    @Override
14511    public int getApplicationEnabledSetting(String packageName, int userId) {
14512        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14513        int uid = Binder.getCallingUid();
14514        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14515        // reader
14516        synchronized (mPackages) {
14517            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14518        }
14519    }
14520
14521    @Override
14522    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14523        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14524        int uid = Binder.getCallingUid();
14525        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14526        // reader
14527        synchronized (mPackages) {
14528            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14529        }
14530    }
14531
14532    @Override
14533    public void enterSafeMode() {
14534        enforceSystemOrRoot("Only the system can request entering safe mode");
14535
14536        if (!mSystemReady) {
14537            mSafeMode = true;
14538        }
14539    }
14540
14541    @Override
14542    public void systemReady() {
14543        mSystemReady = true;
14544
14545        // Read the compatibilty setting when the system is ready.
14546        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14547                mContext.getContentResolver(),
14548                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14549        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14550        if (DEBUG_SETTINGS) {
14551            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14552        }
14553
14554        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14555
14556        synchronized (mPackages) {
14557            // Verify that all of the preferred activity components actually
14558            // exist.  It is possible for applications to be updated and at
14559            // that point remove a previously declared activity component that
14560            // had been set as a preferred activity.  We try to clean this up
14561            // the next time we encounter that preferred activity, but it is
14562            // possible for the user flow to never be able to return to that
14563            // situation so here we do a sanity check to make sure we haven't
14564            // left any junk around.
14565            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14566            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14567                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14568                removed.clear();
14569                for (PreferredActivity pa : pir.filterSet()) {
14570                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14571                        removed.add(pa);
14572                    }
14573                }
14574                if (removed.size() > 0) {
14575                    for (int r=0; r<removed.size(); r++) {
14576                        PreferredActivity pa = removed.get(r);
14577                        Slog.w(TAG, "Removing dangling preferred activity: "
14578                                + pa.mPref.mComponent);
14579                        pir.removeFilter(pa);
14580                    }
14581                    mSettings.writePackageRestrictionsLPr(
14582                            mSettings.mPreferredActivities.keyAt(i));
14583                }
14584            }
14585
14586            for (int userId : UserManagerService.getInstance().getUserIds()) {
14587                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14588                    grantPermissionsUserIds = ArrayUtils.appendInt(
14589                            grantPermissionsUserIds, userId);
14590                }
14591            }
14592        }
14593        sUserManager.systemReady();
14594
14595        // If we upgraded grant all default permissions before kicking off.
14596        for (int userId : grantPermissionsUserIds) {
14597            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14598        }
14599
14600        // Kick off any messages waiting for system ready
14601        if (mPostSystemReadyMessages != null) {
14602            for (Message msg : mPostSystemReadyMessages) {
14603                msg.sendToTarget();
14604            }
14605            mPostSystemReadyMessages = null;
14606        }
14607
14608        // Watch for external volumes that come and go over time
14609        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14610        storage.registerListener(mStorageListener);
14611
14612        mInstallerService.systemReady();
14613        mPackageDexOptimizer.systemReady();
14614
14615        MountServiceInternal mountServiceInternal = LocalServices.getService(
14616                MountServiceInternal.class);
14617        mountServiceInternal.addExternalStoragePolicy(
14618                new MountServiceInternal.ExternalStorageMountPolicy() {
14619            @Override
14620            public int getMountMode(int uid, String packageName) {
14621                if (Process.isIsolated(uid)) {
14622                    return Zygote.MOUNT_EXTERNAL_NONE;
14623                }
14624                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14625                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14626                }
14627                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14628                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14629                }
14630                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14631                    return Zygote.MOUNT_EXTERNAL_READ;
14632                }
14633                return Zygote.MOUNT_EXTERNAL_WRITE;
14634            }
14635
14636            @Override
14637            public boolean hasExternalStorage(int uid, String packageName) {
14638                return true;
14639            }
14640        });
14641    }
14642
14643    @Override
14644    public boolean isSafeMode() {
14645        return mSafeMode;
14646    }
14647
14648    @Override
14649    public boolean hasSystemUidErrors() {
14650        return mHasSystemUidErrors;
14651    }
14652
14653    static String arrayToString(int[] array) {
14654        StringBuffer buf = new StringBuffer(128);
14655        buf.append('[');
14656        if (array != null) {
14657            for (int i=0; i<array.length; i++) {
14658                if (i > 0) buf.append(", ");
14659                buf.append(array[i]);
14660            }
14661        }
14662        buf.append(']');
14663        return buf.toString();
14664    }
14665
14666    static class DumpState {
14667        public static final int DUMP_LIBS = 1 << 0;
14668        public static final int DUMP_FEATURES = 1 << 1;
14669        public static final int DUMP_RESOLVERS = 1 << 2;
14670        public static final int DUMP_PERMISSIONS = 1 << 3;
14671        public static final int DUMP_PACKAGES = 1 << 4;
14672        public static final int DUMP_SHARED_USERS = 1 << 5;
14673        public static final int DUMP_MESSAGES = 1 << 6;
14674        public static final int DUMP_PROVIDERS = 1 << 7;
14675        public static final int DUMP_VERIFIERS = 1 << 8;
14676        public static final int DUMP_PREFERRED = 1 << 9;
14677        public static final int DUMP_PREFERRED_XML = 1 << 10;
14678        public static final int DUMP_KEYSETS = 1 << 11;
14679        public static final int DUMP_VERSION = 1 << 12;
14680        public static final int DUMP_INSTALLS = 1 << 13;
14681        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14682        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14683
14684        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14685
14686        private int mTypes;
14687
14688        private int mOptions;
14689
14690        private boolean mTitlePrinted;
14691
14692        private SharedUserSetting mSharedUser;
14693
14694        public boolean isDumping(int type) {
14695            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14696                return true;
14697            }
14698
14699            return (mTypes & type) != 0;
14700        }
14701
14702        public void setDump(int type) {
14703            mTypes |= type;
14704        }
14705
14706        public boolean isOptionEnabled(int option) {
14707            return (mOptions & option) != 0;
14708        }
14709
14710        public void setOptionEnabled(int option) {
14711            mOptions |= option;
14712        }
14713
14714        public boolean onTitlePrinted() {
14715            final boolean printed = mTitlePrinted;
14716            mTitlePrinted = true;
14717            return printed;
14718        }
14719
14720        public boolean getTitlePrinted() {
14721            return mTitlePrinted;
14722        }
14723
14724        public void setTitlePrinted(boolean enabled) {
14725            mTitlePrinted = enabled;
14726        }
14727
14728        public SharedUserSetting getSharedUser() {
14729            return mSharedUser;
14730        }
14731
14732        public void setSharedUser(SharedUserSetting user) {
14733            mSharedUser = user;
14734        }
14735    }
14736
14737    @Override
14738    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14739        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14740                != PackageManager.PERMISSION_GRANTED) {
14741            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14742                    + Binder.getCallingPid()
14743                    + ", uid=" + Binder.getCallingUid()
14744                    + " without permission "
14745                    + android.Manifest.permission.DUMP);
14746            return;
14747        }
14748
14749        DumpState dumpState = new DumpState();
14750        boolean fullPreferred = false;
14751        boolean checkin = false;
14752
14753        String packageName = null;
14754        ArraySet<String> permissionNames = null;
14755
14756        int opti = 0;
14757        while (opti < args.length) {
14758            String opt = args[opti];
14759            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14760                break;
14761            }
14762            opti++;
14763
14764            if ("-a".equals(opt)) {
14765                // Right now we only know how to print all.
14766            } else if ("-h".equals(opt)) {
14767                pw.println("Package manager dump options:");
14768                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14769                pw.println("    --checkin: dump for a checkin");
14770                pw.println("    -f: print details of intent filters");
14771                pw.println("    -h: print this help");
14772                pw.println("  cmd may be one of:");
14773                pw.println("    l[ibraries]: list known shared libraries");
14774                pw.println("    f[ibraries]: list device features");
14775                pw.println("    k[eysets]: print known keysets");
14776                pw.println("    r[esolvers]: dump intent resolvers");
14777                pw.println("    perm[issions]: dump permissions");
14778                pw.println("    permission [name ...]: dump declaration and use of given permission");
14779                pw.println("    pref[erred]: print preferred package settings");
14780                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14781                pw.println("    prov[iders]: dump content providers");
14782                pw.println("    p[ackages]: dump installed packages");
14783                pw.println("    s[hared-users]: dump shared user IDs");
14784                pw.println("    m[essages]: print collected runtime messages");
14785                pw.println("    v[erifiers]: print package verifier info");
14786                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14787                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14788                pw.println("    version: print database version info");
14789                pw.println("    write: write current settings now");
14790                pw.println("    installs: details about install sessions");
14791                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14792                pw.println("    <package.name>: info about given package");
14793                return;
14794            } else if ("--checkin".equals(opt)) {
14795                checkin = true;
14796            } else if ("-f".equals(opt)) {
14797                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14798            } else {
14799                pw.println("Unknown argument: " + opt + "; use -h for help");
14800            }
14801        }
14802
14803        // Is the caller requesting to dump a particular piece of data?
14804        if (opti < args.length) {
14805            String cmd = args[opti];
14806            opti++;
14807            // Is this a package name?
14808            if ("android".equals(cmd) || cmd.contains(".")) {
14809                packageName = cmd;
14810                // When dumping a single package, we always dump all of its
14811                // filter information since the amount of data will be reasonable.
14812                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14813            } else if ("check-permission".equals(cmd)) {
14814                if (opti >= args.length) {
14815                    pw.println("Error: check-permission missing permission argument");
14816                    return;
14817                }
14818                String perm = args[opti];
14819                opti++;
14820                if (opti >= args.length) {
14821                    pw.println("Error: check-permission missing package argument");
14822                    return;
14823                }
14824                String pkg = args[opti];
14825                opti++;
14826                int user = UserHandle.getUserId(Binder.getCallingUid());
14827                if (opti < args.length) {
14828                    try {
14829                        user = Integer.parseInt(args[opti]);
14830                    } catch (NumberFormatException e) {
14831                        pw.println("Error: check-permission user argument is not a number: "
14832                                + args[opti]);
14833                        return;
14834                    }
14835                }
14836                pw.println(checkPermission(perm, pkg, user));
14837                return;
14838            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14839                dumpState.setDump(DumpState.DUMP_LIBS);
14840            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14841                dumpState.setDump(DumpState.DUMP_FEATURES);
14842            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14843                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14844            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14845                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14846            } else if ("permission".equals(cmd)) {
14847                if (opti >= args.length) {
14848                    pw.println("Error: permission requires permission name");
14849                    return;
14850                }
14851                permissionNames = new ArraySet<>();
14852                while (opti < args.length) {
14853                    permissionNames.add(args[opti]);
14854                    opti++;
14855                }
14856                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14857                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14858            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14859                dumpState.setDump(DumpState.DUMP_PREFERRED);
14860            } else if ("preferred-xml".equals(cmd)) {
14861                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14862                if (opti < args.length && "--full".equals(args[opti])) {
14863                    fullPreferred = true;
14864                    opti++;
14865                }
14866            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14867                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14868            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14869                dumpState.setDump(DumpState.DUMP_PACKAGES);
14870            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14871                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14872            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14873                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14874            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14875                dumpState.setDump(DumpState.DUMP_MESSAGES);
14876            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14877                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14878            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14879                    || "intent-filter-verifiers".equals(cmd)) {
14880                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14881            } else if ("version".equals(cmd)) {
14882                dumpState.setDump(DumpState.DUMP_VERSION);
14883            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14884                dumpState.setDump(DumpState.DUMP_KEYSETS);
14885            } else if ("installs".equals(cmd)) {
14886                dumpState.setDump(DumpState.DUMP_INSTALLS);
14887            } else if ("write".equals(cmd)) {
14888                synchronized (mPackages) {
14889                    mSettings.writeLPr();
14890                    pw.println("Settings written.");
14891                    return;
14892                }
14893            }
14894        }
14895
14896        if (checkin) {
14897            pw.println("vers,1");
14898        }
14899
14900        // reader
14901        synchronized (mPackages) {
14902            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14903                if (!checkin) {
14904                    if (dumpState.onTitlePrinted())
14905                        pw.println();
14906                    pw.println("Database versions:");
14907                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14908                }
14909            }
14910
14911            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14912                if (!checkin) {
14913                    if (dumpState.onTitlePrinted())
14914                        pw.println();
14915                    pw.println("Verifiers:");
14916                    pw.print("  Required: ");
14917                    pw.print(mRequiredVerifierPackage);
14918                    pw.print(" (uid=");
14919                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14920                    pw.println(")");
14921                } else if (mRequiredVerifierPackage != null) {
14922                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14923                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14924                }
14925            }
14926
14927            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14928                    packageName == null) {
14929                if (mIntentFilterVerifierComponent != null) {
14930                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14931                    if (!checkin) {
14932                        if (dumpState.onTitlePrinted())
14933                            pw.println();
14934                        pw.println("Intent Filter Verifier:");
14935                        pw.print("  Using: ");
14936                        pw.print(verifierPackageName);
14937                        pw.print(" (uid=");
14938                        pw.print(getPackageUid(verifierPackageName, 0));
14939                        pw.println(")");
14940                    } else if (verifierPackageName != null) {
14941                        pw.print("ifv,"); pw.print(verifierPackageName);
14942                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14943                    }
14944                } else {
14945                    pw.println();
14946                    pw.println("No Intent Filter Verifier available!");
14947                }
14948            }
14949
14950            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14951                boolean printedHeader = false;
14952                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14953                while (it.hasNext()) {
14954                    String name = it.next();
14955                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14956                    if (!checkin) {
14957                        if (!printedHeader) {
14958                            if (dumpState.onTitlePrinted())
14959                                pw.println();
14960                            pw.println("Libraries:");
14961                            printedHeader = true;
14962                        }
14963                        pw.print("  ");
14964                    } else {
14965                        pw.print("lib,");
14966                    }
14967                    pw.print(name);
14968                    if (!checkin) {
14969                        pw.print(" -> ");
14970                    }
14971                    if (ent.path != null) {
14972                        if (!checkin) {
14973                            pw.print("(jar) ");
14974                            pw.print(ent.path);
14975                        } else {
14976                            pw.print(",jar,");
14977                            pw.print(ent.path);
14978                        }
14979                    } else {
14980                        if (!checkin) {
14981                            pw.print("(apk) ");
14982                            pw.print(ent.apk);
14983                        } else {
14984                            pw.print(",apk,");
14985                            pw.print(ent.apk);
14986                        }
14987                    }
14988                    pw.println();
14989                }
14990            }
14991
14992            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14993                if (dumpState.onTitlePrinted())
14994                    pw.println();
14995                if (!checkin) {
14996                    pw.println("Features:");
14997                }
14998                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14999                while (it.hasNext()) {
15000                    String name = it.next();
15001                    if (!checkin) {
15002                        pw.print("  ");
15003                    } else {
15004                        pw.print("feat,");
15005                    }
15006                    pw.println(name);
15007                }
15008            }
15009
15010            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15011                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15012                        : "Activity Resolver Table:", "  ", packageName,
15013                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15014                    dumpState.setTitlePrinted(true);
15015                }
15016                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15017                        : "Receiver Resolver Table:", "  ", packageName,
15018                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15019                    dumpState.setTitlePrinted(true);
15020                }
15021                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15022                        : "Service Resolver Table:", "  ", packageName,
15023                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15024                    dumpState.setTitlePrinted(true);
15025                }
15026                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15027                        : "Provider Resolver Table:", "  ", packageName,
15028                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15029                    dumpState.setTitlePrinted(true);
15030                }
15031            }
15032
15033            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15034                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15035                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15036                    int user = mSettings.mPreferredActivities.keyAt(i);
15037                    if (pir.dump(pw,
15038                            dumpState.getTitlePrinted()
15039                                ? "\nPreferred Activities User " + user + ":"
15040                                : "Preferred Activities User " + user + ":", "  ",
15041                            packageName, true, false)) {
15042                        dumpState.setTitlePrinted(true);
15043                    }
15044                }
15045            }
15046
15047            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15048                pw.flush();
15049                FileOutputStream fout = new FileOutputStream(fd);
15050                BufferedOutputStream str = new BufferedOutputStream(fout);
15051                XmlSerializer serializer = new FastXmlSerializer();
15052                try {
15053                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15054                    serializer.startDocument(null, true);
15055                    serializer.setFeature(
15056                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15057                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15058                    serializer.endDocument();
15059                    serializer.flush();
15060                } catch (IllegalArgumentException e) {
15061                    pw.println("Failed writing: " + e);
15062                } catch (IllegalStateException e) {
15063                    pw.println("Failed writing: " + e);
15064                } catch (IOException e) {
15065                    pw.println("Failed writing: " + e);
15066                }
15067            }
15068
15069            if (!checkin
15070                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15071                    && packageName == null) {
15072                pw.println();
15073                int count = mSettings.mPackages.size();
15074                if (count == 0) {
15075                    pw.println("No applications!");
15076                    pw.println();
15077                } else {
15078                    final String prefix = "  ";
15079                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15080                    if (allPackageSettings.size() == 0) {
15081                        pw.println("No domain preferred apps!");
15082                        pw.println();
15083                    } else {
15084                        pw.println("App verification status:");
15085                        pw.println();
15086                        count = 0;
15087                        for (PackageSetting ps : allPackageSettings) {
15088                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15089                            if (ivi == null || ivi.getPackageName() == null) continue;
15090                            pw.println(prefix + "Package: " + ivi.getPackageName());
15091                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15092                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15093                            pw.println();
15094                            count++;
15095                        }
15096                        if (count == 0) {
15097                            pw.println(prefix + "No app verification established.");
15098                            pw.println();
15099                        }
15100                        for (int userId : sUserManager.getUserIds()) {
15101                            pw.println("App linkages for user " + userId + ":");
15102                            pw.println();
15103                            count = 0;
15104                            for (PackageSetting ps : allPackageSettings) {
15105                                final long status = ps.getDomainVerificationStatusForUser(userId);
15106                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15107                                    continue;
15108                                }
15109                                pw.println(prefix + "Package: " + ps.name);
15110                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15111                                String statusStr = IntentFilterVerificationInfo.
15112                                        getStatusStringFromValue(status);
15113                                pw.println(prefix + "Status:  " + statusStr);
15114                                pw.println();
15115                                count++;
15116                            }
15117                            if (count == 0) {
15118                                pw.println(prefix + "No configured app linkages.");
15119                                pw.println();
15120                            }
15121                        }
15122                    }
15123                }
15124            }
15125
15126            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15127                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15128                if (packageName == null && permissionNames == null) {
15129                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15130                        if (iperm == 0) {
15131                            if (dumpState.onTitlePrinted())
15132                                pw.println();
15133                            pw.println("AppOp Permissions:");
15134                        }
15135                        pw.print("  AppOp Permission ");
15136                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15137                        pw.println(":");
15138                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15139                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15140                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15141                        }
15142                    }
15143                }
15144            }
15145
15146            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15147                boolean printedSomething = false;
15148                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15149                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15150                        continue;
15151                    }
15152                    if (!printedSomething) {
15153                        if (dumpState.onTitlePrinted())
15154                            pw.println();
15155                        pw.println("Registered ContentProviders:");
15156                        printedSomething = true;
15157                    }
15158                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15159                    pw.print("    "); pw.println(p.toString());
15160                }
15161                printedSomething = false;
15162                for (Map.Entry<String, PackageParser.Provider> entry :
15163                        mProvidersByAuthority.entrySet()) {
15164                    PackageParser.Provider p = entry.getValue();
15165                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15166                        continue;
15167                    }
15168                    if (!printedSomething) {
15169                        if (dumpState.onTitlePrinted())
15170                            pw.println();
15171                        pw.println("ContentProvider Authorities:");
15172                        printedSomething = true;
15173                    }
15174                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15175                    pw.print("    "); pw.println(p.toString());
15176                    if (p.info != null && p.info.applicationInfo != null) {
15177                        final String appInfo = p.info.applicationInfo.toString();
15178                        pw.print("      applicationInfo="); pw.println(appInfo);
15179                    }
15180                }
15181            }
15182
15183            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15184                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15185            }
15186
15187            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15188                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15189            }
15190
15191            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15192                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15193            }
15194
15195            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15196                // XXX should handle packageName != null by dumping only install data that
15197                // the given package is involved with.
15198                if (dumpState.onTitlePrinted()) pw.println();
15199                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15200            }
15201
15202            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15203                if (dumpState.onTitlePrinted()) pw.println();
15204                mSettings.dumpReadMessagesLPr(pw, dumpState);
15205
15206                pw.println();
15207                pw.println("Package warning messages:");
15208                BufferedReader in = null;
15209                String line = null;
15210                try {
15211                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15212                    while ((line = in.readLine()) != null) {
15213                        if (line.contains("ignored: updated version")) continue;
15214                        pw.println(line);
15215                    }
15216                } catch (IOException ignored) {
15217                } finally {
15218                    IoUtils.closeQuietly(in);
15219                }
15220            }
15221
15222            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15223                BufferedReader in = null;
15224                String line = null;
15225                try {
15226                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15227                    while ((line = in.readLine()) != null) {
15228                        if (line.contains("ignored: updated version")) continue;
15229                        pw.print("msg,");
15230                        pw.println(line);
15231                    }
15232                } catch (IOException ignored) {
15233                } finally {
15234                    IoUtils.closeQuietly(in);
15235                }
15236            }
15237        }
15238    }
15239
15240    private String dumpDomainString(String packageName) {
15241        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15242        List<IntentFilter> filters = getAllIntentFilters(packageName);
15243
15244        ArraySet<String> result = new ArraySet<>();
15245        if (iviList.size() > 0) {
15246            for (IntentFilterVerificationInfo ivi : iviList) {
15247                for (String host : ivi.getDomains()) {
15248                    result.add(host);
15249                }
15250            }
15251        }
15252        if (filters != null && filters.size() > 0) {
15253            for (IntentFilter filter : filters) {
15254                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15255                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15256                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15257                    result.addAll(filter.getHostsList());
15258                }
15259            }
15260        }
15261
15262        StringBuilder sb = new StringBuilder(result.size() * 16);
15263        for (String domain : result) {
15264            if (sb.length() > 0) sb.append(" ");
15265            sb.append(domain);
15266        }
15267        return sb.toString();
15268    }
15269
15270    // ------- apps on sdcard specific code -------
15271    static final boolean DEBUG_SD_INSTALL = false;
15272
15273    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15274
15275    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15276
15277    private boolean mMediaMounted = false;
15278
15279    static String getEncryptKey() {
15280        try {
15281            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15282                    SD_ENCRYPTION_KEYSTORE_NAME);
15283            if (sdEncKey == null) {
15284                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15285                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15286                if (sdEncKey == null) {
15287                    Slog.e(TAG, "Failed to create encryption keys");
15288                    return null;
15289                }
15290            }
15291            return sdEncKey;
15292        } catch (NoSuchAlgorithmException nsae) {
15293            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15294            return null;
15295        } catch (IOException ioe) {
15296            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15297            return null;
15298        }
15299    }
15300
15301    /*
15302     * Update media status on PackageManager.
15303     */
15304    @Override
15305    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15306        int callingUid = Binder.getCallingUid();
15307        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15308            throw new SecurityException("Media status can only be updated by the system");
15309        }
15310        // reader; this apparently protects mMediaMounted, but should probably
15311        // be a different lock in that case.
15312        synchronized (mPackages) {
15313            Log.i(TAG, "Updating external media status from "
15314                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15315                    + (mediaStatus ? "mounted" : "unmounted"));
15316            if (DEBUG_SD_INSTALL)
15317                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15318                        + ", mMediaMounted=" + mMediaMounted);
15319            if (mediaStatus == mMediaMounted) {
15320                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15321                        : 0, -1);
15322                mHandler.sendMessage(msg);
15323                return;
15324            }
15325            mMediaMounted = mediaStatus;
15326        }
15327        // Queue up an async operation since the package installation may take a
15328        // little while.
15329        mHandler.post(new Runnable() {
15330            public void run() {
15331                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15332            }
15333        });
15334    }
15335
15336    /**
15337     * Called by MountService when the initial ASECs to scan are available.
15338     * Should block until all the ASEC containers are finished being scanned.
15339     */
15340    public void scanAvailableAsecs() {
15341        updateExternalMediaStatusInner(true, false, false);
15342        if (mShouldRestoreconData) {
15343            SELinuxMMAC.setRestoreconDone();
15344            mShouldRestoreconData = false;
15345        }
15346    }
15347
15348    /*
15349     * Collect information of applications on external media, map them against
15350     * existing containers and update information based on current mount status.
15351     * Please note that we always have to report status if reportStatus has been
15352     * set to true especially when unloading packages.
15353     */
15354    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15355            boolean externalStorage) {
15356        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15357        int[] uidArr = EmptyArray.INT;
15358
15359        final String[] list = PackageHelper.getSecureContainerList();
15360        if (ArrayUtils.isEmpty(list)) {
15361            Log.i(TAG, "No secure containers found");
15362        } else {
15363            // Process list of secure containers and categorize them
15364            // as active or stale based on their package internal state.
15365
15366            // reader
15367            synchronized (mPackages) {
15368                for (String cid : list) {
15369                    // Leave stages untouched for now; installer service owns them
15370                    if (PackageInstallerService.isStageName(cid)) continue;
15371
15372                    if (DEBUG_SD_INSTALL)
15373                        Log.i(TAG, "Processing container " + cid);
15374                    String pkgName = getAsecPackageName(cid);
15375                    if (pkgName == null) {
15376                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15377                        continue;
15378                    }
15379                    if (DEBUG_SD_INSTALL)
15380                        Log.i(TAG, "Looking for pkg : " + pkgName);
15381
15382                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15383                    if (ps == null) {
15384                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15385                        continue;
15386                    }
15387
15388                    /*
15389                     * Skip packages that are not external if we're unmounting
15390                     * external storage.
15391                     */
15392                    if (externalStorage && !isMounted && !isExternal(ps)) {
15393                        continue;
15394                    }
15395
15396                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15397                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15398                    // The package status is changed only if the code path
15399                    // matches between settings and the container id.
15400                    if (ps.codePathString != null
15401                            && ps.codePathString.startsWith(args.getCodePath())) {
15402                        if (DEBUG_SD_INSTALL) {
15403                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15404                                    + " at code path: " + ps.codePathString);
15405                        }
15406
15407                        // We do have a valid package installed on sdcard
15408                        processCids.put(args, ps.codePathString);
15409                        final int uid = ps.appId;
15410                        if (uid != -1) {
15411                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15412                        }
15413                    } else {
15414                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15415                                + ps.codePathString);
15416                    }
15417                }
15418            }
15419
15420            Arrays.sort(uidArr);
15421        }
15422
15423        // Process packages with valid entries.
15424        if (isMounted) {
15425            if (DEBUG_SD_INSTALL)
15426                Log.i(TAG, "Loading packages");
15427            loadMediaPackages(processCids, uidArr);
15428            startCleaningPackages();
15429            mInstallerService.onSecureContainersAvailable();
15430        } else {
15431            if (DEBUG_SD_INSTALL)
15432                Log.i(TAG, "Unloading packages");
15433            unloadMediaPackages(processCids, uidArr, reportStatus);
15434        }
15435    }
15436
15437    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15438            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15439        final int size = infos.size();
15440        final String[] packageNames = new String[size];
15441        final int[] packageUids = new int[size];
15442        for (int i = 0; i < size; i++) {
15443            final ApplicationInfo info = infos.get(i);
15444            packageNames[i] = info.packageName;
15445            packageUids[i] = info.uid;
15446        }
15447        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15448                finishedReceiver);
15449    }
15450
15451    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15452            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15453        sendResourcesChangedBroadcast(mediaStatus, replacing,
15454                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15455    }
15456
15457    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15458            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15459        int size = pkgList.length;
15460        if (size > 0) {
15461            // Send broadcasts here
15462            Bundle extras = new Bundle();
15463            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15464            if (uidArr != null) {
15465                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15466            }
15467            if (replacing) {
15468                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15469            }
15470            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15471                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15472            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15473        }
15474    }
15475
15476   /*
15477     * Look at potentially valid container ids from processCids If package
15478     * information doesn't match the one on record or package scanning fails,
15479     * the cid is added to list of removeCids. We currently don't delete stale
15480     * containers.
15481     */
15482    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15483        ArrayList<String> pkgList = new ArrayList<String>();
15484        Set<AsecInstallArgs> keys = processCids.keySet();
15485
15486        for (AsecInstallArgs args : keys) {
15487            String codePath = processCids.get(args);
15488            if (DEBUG_SD_INSTALL)
15489                Log.i(TAG, "Loading container : " + args.cid);
15490            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15491            try {
15492                // Make sure there are no container errors first.
15493                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15494                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15495                            + " when installing from sdcard");
15496                    continue;
15497                }
15498                // Check code path here.
15499                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15500                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15501                            + " does not match one in settings " + codePath);
15502                    continue;
15503                }
15504                // Parse package
15505                int parseFlags = mDefParseFlags;
15506                if (args.isExternalAsec()) {
15507                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15508                }
15509                if (args.isFwdLocked()) {
15510                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15511                }
15512
15513                synchronized (mInstallLock) {
15514                    PackageParser.Package pkg = null;
15515                    try {
15516                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15517                    } catch (PackageManagerException e) {
15518                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15519                    }
15520                    // Scan the package
15521                    if (pkg != null) {
15522                        /*
15523                         * TODO why is the lock being held? doPostInstall is
15524                         * called in other places without the lock. This needs
15525                         * to be straightened out.
15526                         */
15527                        // writer
15528                        synchronized (mPackages) {
15529                            retCode = PackageManager.INSTALL_SUCCEEDED;
15530                            pkgList.add(pkg.packageName);
15531                            // Post process args
15532                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15533                                    pkg.applicationInfo.uid);
15534                        }
15535                    } else {
15536                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15537                    }
15538                }
15539
15540            } finally {
15541                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15542                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15543                }
15544            }
15545        }
15546        // writer
15547        synchronized (mPackages) {
15548            // If the platform SDK has changed since the last time we booted,
15549            // we need to re-grant app permission to catch any new ones that
15550            // appear. This is really a hack, and means that apps can in some
15551            // cases get permissions that the user didn't initially explicitly
15552            // allow... it would be nice to have some better way to handle
15553            // this situation.
15554            final VersionInfo ver = mSettings.getExternalVersion();
15555
15556            int updateFlags = UPDATE_PERMISSIONS_ALL;
15557            if (ver.sdkVersion != mSdkVersion) {
15558                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15559                        + mSdkVersion + "; regranting permissions for external");
15560                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15561            }
15562            updatePermissionsLPw(null, null, updateFlags);
15563
15564            // Yay, everything is now upgraded
15565            ver.forceCurrent();
15566
15567            // can downgrade to reader
15568            // Persist settings
15569            mSettings.writeLPr();
15570        }
15571        // Send a broadcast to let everyone know we are done processing
15572        if (pkgList.size() > 0) {
15573            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15574        }
15575    }
15576
15577   /*
15578     * Utility method to unload a list of specified containers
15579     */
15580    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15581        // Just unmount all valid containers.
15582        for (AsecInstallArgs arg : cidArgs) {
15583            synchronized (mInstallLock) {
15584                arg.doPostDeleteLI(false);
15585           }
15586       }
15587   }
15588
15589    /*
15590     * Unload packages mounted on external media. This involves deleting package
15591     * data from internal structures, sending broadcasts about diabled packages,
15592     * gc'ing to free up references, unmounting all secure containers
15593     * corresponding to packages on external media, and posting a
15594     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15595     * that we always have to post this message if status has been requested no
15596     * matter what.
15597     */
15598    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15599            final boolean reportStatus) {
15600        if (DEBUG_SD_INSTALL)
15601            Log.i(TAG, "unloading media packages");
15602        ArrayList<String> pkgList = new ArrayList<String>();
15603        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15604        final Set<AsecInstallArgs> keys = processCids.keySet();
15605        for (AsecInstallArgs args : keys) {
15606            String pkgName = args.getPackageName();
15607            if (DEBUG_SD_INSTALL)
15608                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15609            // Delete package internally
15610            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15611            synchronized (mInstallLock) {
15612                boolean res = deletePackageLI(pkgName, null, false, null, null,
15613                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15614                if (res) {
15615                    pkgList.add(pkgName);
15616                } else {
15617                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15618                    failedList.add(args);
15619                }
15620            }
15621        }
15622
15623        // reader
15624        synchronized (mPackages) {
15625            // We didn't update the settings after removing each package;
15626            // write them now for all packages.
15627            mSettings.writeLPr();
15628        }
15629
15630        // We have to absolutely send UPDATED_MEDIA_STATUS only
15631        // after confirming that all the receivers processed the ordered
15632        // broadcast when packages get disabled, force a gc to clean things up.
15633        // and unload all the containers.
15634        if (pkgList.size() > 0) {
15635            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15636                    new IIntentReceiver.Stub() {
15637                public void performReceive(Intent intent, int resultCode, String data,
15638                        Bundle extras, boolean ordered, boolean sticky,
15639                        int sendingUser) throws RemoteException {
15640                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15641                            reportStatus ? 1 : 0, 1, keys);
15642                    mHandler.sendMessage(msg);
15643                }
15644            });
15645        } else {
15646            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15647                    keys);
15648            mHandler.sendMessage(msg);
15649        }
15650    }
15651
15652    private void loadPrivatePackages(final VolumeInfo vol) {
15653        mHandler.post(new Runnable() {
15654            @Override
15655            public void run() {
15656                loadPrivatePackagesInner(vol);
15657            }
15658        });
15659    }
15660
15661    private void loadPrivatePackagesInner(VolumeInfo vol) {
15662        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15663        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15664
15665        final VersionInfo ver;
15666        final List<PackageSetting> packages;
15667        synchronized (mPackages) {
15668            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15669            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15670        }
15671
15672        for (PackageSetting ps : packages) {
15673            synchronized (mInstallLock) {
15674                final PackageParser.Package pkg;
15675                try {
15676                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15677                    loaded.add(pkg.applicationInfo);
15678                } catch (PackageManagerException e) {
15679                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15680                }
15681
15682                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15683                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15684                }
15685            }
15686        }
15687
15688        synchronized (mPackages) {
15689            int updateFlags = UPDATE_PERMISSIONS_ALL;
15690            if (ver.sdkVersion != mSdkVersion) {
15691                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15692                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15693                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15694            }
15695            updatePermissionsLPw(null, null, updateFlags);
15696
15697            // Yay, everything is now upgraded
15698            ver.forceCurrent();
15699
15700            mSettings.writeLPr();
15701        }
15702
15703        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15704        sendResourcesChangedBroadcast(true, false, loaded, null);
15705    }
15706
15707    private void unloadPrivatePackages(final VolumeInfo vol) {
15708        mHandler.post(new Runnable() {
15709            @Override
15710            public void run() {
15711                unloadPrivatePackagesInner(vol);
15712            }
15713        });
15714    }
15715
15716    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15717        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15718        synchronized (mInstallLock) {
15719        synchronized (mPackages) {
15720            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15721            for (PackageSetting ps : packages) {
15722                if (ps.pkg == null) continue;
15723
15724                final ApplicationInfo info = ps.pkg.applicationInfo;
15725                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15726                if (deletePackageLI(ps.name, null, false, null, null,
15727                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15728                    unloaded.add(info);
15729                } else {
15730                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15731                }
15732            }
15733
15734            mSettings.writeLPr();
15735        }
15736        }
15737
15738        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15739        sendResourcesChangedBroadcast(false, false, unloaded, null);
15740    }
15741
15742    /**
15743     * Examine all users present on given mounted volume, and destroy data
15744     * belonging to users that are no longer valid, or whose user ID has been
15745     * recycled.
15746     */
15747    private void reconcileUsers(String volumeUuid) {
15748        final File[] files = FileUtils
15749                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15750        for (File file : files) {
15751            if (!file.isDirectory()) continue;
15752
15753            final int userId;
15754            final UserInfo info;
15755            try {
15756                userId = Integer.parseInt(file.getName());
15757                info = sUserManager.getUserInfo(userId);
15758            } catch (NumberFormatException e) {
15759                Slog.w(TAG, "Invalid user directory " + file);
15760                continue;
15761            }
15762
15763            boolean destroyUser = false;
15764            if (info == null) {
15765                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15766                        + " because no matching user was found");
15767                destroyUser = true;
15768            } else {
15769                try {
15770                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15771                } catch (IOException e) {
15772                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15773                            + " because we failed to enforce serial number: " + e);
15774                    destroyUser = true;
15775                }
15776            }
15777
15778            if (destroyUser) {
15779                synchronized (mInstallLock) {
15780                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15781                }
15782            }
15783        }
15784
15785        final UserManager um = mContext.getSystemService(UserManager.class);
15786        for (UserInfo user : um.getUsers()) {
15787            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15788            if (userDir.exists()) continue;
15789
15790            try {
15791                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15792                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15793            } catch (IOException e) {
15794                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15795            }
15796        }
15797    }
15798
15799    /**
15800     * Examine all apps present on given mounted volume, and destroy apps that
15801     * aren't expected, either due to uninstallation or reinstallation on
15802     * another volume.
15803     */
15804    private void reconcileApps(String volumeUuid) {
15805        final File[] files = FileUtils
15806                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15807        for (File file : files) {
15808            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15809                    && !PackageInstallerService.isStageName(file.getName());
15810            if (!isPackage) {
15811                // Ignore entries which are not packages
15812                continue;
15813            }
15814
15815            boolean destroyApp = false;
15816            String packageName = null;
15817            try {
15818                final PackageLite pkg = PackageParser.parsePackageLite(file,
15819                        PackageParser.PARSE_MUST_BE_APK);
15820                packageName = pkg.packageName;
15821
15822                synchronized (mPackages) {
15823                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15824                    if (ps == null) {
15825                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15826                                + volumeUuid + " because we found no install record");
15827                        destroyApp = true;
15828                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15829                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15830                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15831                        destroyApp = true;
15832                    }
15833                }
15834
15835            } catch (PackageParserException e) {
15836                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15837                destroyApp = true;
15838            }
15839
15840            if (destroyApp) {
15841                synchronized (mInstallLock) {
15842                    if (packageName != null) {
15843                        removeDataDirsLI(volumeUuid, packageName);
15844                    }
15845                    if (file.isDirectory()) {
15846                        mInstaller.rmPackageDir(file.getAbsolutePath());
15847                    } else {
15848                        file.delete();
15849                    }
15850                }
15851            }
15852        }
15853    }
15854
15855    private void unfreezePackage(String packageName) {
15856        synchronized (mPackages) {
15857            final PackageSetting ps = mSettings.mPackages.get(packageName);
15858            if (ps != null) {
15859                ps.frozen = false;
15860            }
15861        }
15862    }
15863
15864    @Override
15865    public int movePackage(final String packageName, final String volumeUuid) {
15866        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15867
15868        final int moveId = mNextMoveId.getAndIncrement();
15869        try {
15870            movePackageInternal(packageName, volumeUuid, moveId);
15871        } catch (PackageManagerException e) {
15872            Slog.w(TAG, "Failed to move " + packageName, e);
15873            mMoveCallbacks.notifyStatusChanged(moveId,
15874                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15875        }
15876        return moveId;
15877    }
15878
15879    private void movePackageInternal(final String packageName, final String volumeUuid,
15880            final int moveId) throws PackageManagerException {
15881        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15882        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15883        final PackageManager pm = mContext.getPackageManager();
15884
15885        final boolean currentAsec;
15886        final String currentVolumeUuid;
15887        final File codeFile;
15888        final String installerPackageName;
15889        final String packageAbiOverride;
15890        final int appId;
15891        final String seinfo;
15892        final String label;
15893
15894        // reader
15895        synchronized (mPackages) {
15896            final PackageParser.Package pkg = mPackages.get(packageName);
15897            final PackageSetting ps = mSettings.mPackages.get(packageName);
15898            if (pkg == null || ps == null) {
15899                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15900            }
15901
15902            if (pkg.applicationInfo.isSystemApp()) {
15903                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15904                        "Cannot move system application");
15905            }
15906
15907            if (pkg.applicationInfo.isExternalAsec()) {
15908                currentAsec = true;
15909                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15910            } else if (pkg.applicationInfo.isForwardLocked()) {
15911                currentAsec = true;
15912                currentVolumeUuid = "forward_locked";
15913            } else {
15914                currentAsec = false;
15915                currentVolumeUuid = ps.volumeUuid;
15916
15917                final File probe = new File(pkg.codePath);
15918                final File probeOat = new File(probe, "oat");
15919                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15920                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15921                            "Move only supported for modern cluster style installs");
15922                }
15923            }
15924
15925            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15926                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15927                        "Package already moved to " + volumeUuid);
15928            }
15929
15930            if (ps.frozen) {
15931                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15932                        "Failed to move already frozen package");
15933            }
15934            ps.frozen = true;
15935
15936            codeFile = new File(pkg.codePath);
15937            installerPackageName = ps.installerPackageName;
15938            packageAbiOverride = ps.cpuAbiOverrideString;
15939            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15940            seinfo = pkg.applicationInfo.seinfo;
15941            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15942        }
15943
15944        // Now that we're guarded by frozen state, kill app during move
15945        final long token = Binder.clearCallingIdentity();
15946        try {
15947            killApplication(packageName, appId, "move pkg");
15948        } finally {
15949            Binder.restoreCallingIdentity(token);
15950        }
15951
15952        final Bundle extras = new Bundle();
15953        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15954        extras.putString(Intent.EXTRA_TITLE, label);
15955        mMoveCallbacks.notifyCreated(moveId, extras);
15956
15957        int installFlags;
15958        final boolean moveCompleteApp;
15959        final File measurePath;
15960
15961        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15962            installFlags = INSTALL_INTERNAL;
15963            moveCompleteApp = !currentAsec;
15964            measurePath = Environment.getDataAppDirectory(volumeUuid);
15965        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15966            installFlags = INSTALL_EXTERNAL;
15967            moveCompleteApp = false;
15968            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15969        } else {
15970            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15971            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15972                    || !volume.isMountedWritable()) {
15973                unfreezePackage(packageName);
15974                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15975                        "Move location not mounted private volume");
15976            }
15977
15978            Preconditions.checkState(!currentAsec);
15979
15980            installFlags = INSTALL_INTERNAL;
15981            moveCompleteApp = true;
15982            measurePath = Environment.getDataAppDirectory(volumeUuid);
15983        }
15984
15985        final PackageStats stats = new PackageStats(null, -1);
15986        synchronized (mInstaller) {
15987            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15988                unfreezePackage(packageName);
15989                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15990                        "Failed to measure package size");
15991            }
15992        }
15993
15994        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15995                + stats.dataSize);
15996
15997        final long startFreeBytes = measurePath.getFreeSpace();
15998        final long sizeBytes;
15999        if (moveCompleteApp) {
16000            sizeBytes = stats.codeSize + stats.dataSize;
16001        } else {
16002            sizeBytes = stats.codeSize;
16003        }
16004
16005        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16006            unfreezePackage(packageName);
16007            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16008                    "Not enough free space to move");
16009        }
16010
16011        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16012
16013        final CountDownLatch installedLatch = new CountDownLatch(1);
16014        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16015            @Override
16016            public void onUserActionRequired(Intent intent) throws RemoteException {
16017                throw new IllegalStateException();
16018            }
16019
16020            @Override
16021            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16022                    Bundle extras) throws RemoteException {
16023                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16024                        + PackageManager.installStatusToString(returnCode, msg));
16025
16026                installedLatch.countDown();
16027
16028                // Regardless of success or failure of the move operation,
16029                // always unfreeze the package
16030                unfreezePackage(packageName);
16031
16032                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16033                switch (status) {
16034                    case PackageInstaller.STATUS_SUCCESS:
16035                        mMoveCallbacks.notifyStatusChanged(moveId,
16036                                PackageManager.MOVE_SUCCEEDED);
16037                        break;
16038                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16039                        mMoveCallbacks.notifyStatusChanged(moveId,
16040                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16041                        break;
16042                    default:
16043                        mMoveCallbacks.notifyStatusChanged(moveId,
16044                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16045                        break;
16046                }
16047            }
16048        };
16049
16050        final MoveInfo move;
16051        if (moveCompleteApp) {
16052            // Kick off a thread to report progress estimates
16053            new Thread() {
16054                @Override
16055                public void run() {
16056                    while (true) {
16057                        try {
16058                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16059                                break;
16060                            }
16061                        } catch (InterruptedException ignored) {
16062                        }
16063
16064                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16065                        final int progress = 10 + (int) MathUtils.constrain(
16066                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16067                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16068                    }
16069                }
16070            }.start();
16071
16072            final String dataAppName = codeFile.getName();
16073            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16074                    dataAppName, appId, seinfo);
16075        } else {
16076            move = null;
16077        }
16078
16079        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16080
16081        final Message msg = mHandler.obtainMessage(INIT_COPY);
16082        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16083        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16084                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16085        mHandler.sendMessage(msg);
16086    }
16087
16088    @Override
16089    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16090        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16091
16092        final int realMoveId = mNextMoveId.getAndIncrement();
16093        final Bundle extras = new Bundle();
16094        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16095        mMoveCallbacks.notifyCreated(realMoveId, extras);
16096
16097        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16098            @Override
16099            public void onCreated(int moveId, Bundle extras) {
16100                // Ignored
16101            }
16102
16103            @Override
16104            public void onStatusChanged(int moveId, int status, long estMillis) {
16105                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16106            }
16107        };
16108
16109        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16110        storage.setPrimaryStorageUuid(volumeUuid, callback);
16111        return realMoveId;
16112    }
16113
16114    @Override
16115    public int getMoveStatus(int moveId) {
16116        mContext.enforceCallingOrSelfPermission(
16117                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16118        return mMoveCallbacks.mLastStatus.get(moveId);
16119    }
16120
16121    @Override
16122    public void registerMoveCallback(IPackageMoveObserver callback) {
16123        mContext.enforceCallingOrSelfPermission(
16124                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16125        mMoveCallbacks.register(callback);
16126    }
16127
16128    @Override
16129    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16130        mContext.enforceCallingOrSelfPermission(
16131                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16132        mMoveCallbacks.unregister(callback);
16133    }
16134
16135    @Override
16136    public boolean setInstallLocation(int loc) {
16137        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16138                null);
16139        if (getInstallLocation() == loc) {
16140            return true;
16141        }
16142        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16143                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16144            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16145                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16146            return true;
16147        }
16148        return false;
16149   }
16150
16151    @Override
16152    public int getInstallLocation() {
16153        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16154                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16155                PackageHelper.APP_INSTALL_AUTO);
16156    }
16157
16158    /** Called by UserManagerService */
16159    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16160        mDirtyUsers.remove(userHandle);
16161        mSettings.removeUserLPw(userHandle);
16162        mPendingBroadcasts.remove(userHandle);
16163        if (mInstaller != null) {
16164            // Technically, we shouldn't be doing this with the package lock
16165            // held.  However, this is very rare, and there is already so much
16166            // other disk I/O going on, that we'll let it slide for now.
16167            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16168            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16169                final String volumeUuid = vol.getFsUuid();
16170                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16171                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16172            }
16173        }
16174        mUserNeedsBadging.delete(userHandle);
16175        removeUnusedPackagesLILPw(userManager, userHandle);
16176    }
16177
16178    /**
16179     * We're removing userHandle and would like to remove any downloaded packages
16180     * that are no longer in use by any other user.
16181     * @param userHandle the user being removed
16182     */
16183    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16184        final boolean DEBUG_CLEAN_APKS = false;
16185        int [] users = userManager.getUserIdsLPr();
16186        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16187        while (psit.hasNext()) {
16188            PackageSetting ps = psit.next();
16189            if (ps.pkg == null) {
16190                continue;
16191            }
16192            final String packageName = ps.pkg.packageName;
16193            // Skip over if system app
16194            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16195                continue;
16196            }
16197            if (DEBUG_CLEAN_APKS) {
16198                Slog.i(TAG, "Checking package " + packageName);
16199            }
16200            boolean keep = false;
16201            for (int i = 0; i < users.length; i++) {
16202                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16203                    keep = true;
16204                    if (DEBUG_CLEAN_APKS) {
16205                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16206                                + users[i]);
16207                    }
16208                    break;
16209                }
16210            }
16211            if (!keep) {
16212                if (DEBUG_CLEAN_APKS) {
16213                    Slog.i(TAG, "  Removing package " + packageName);
16214                }
16215                mHandler.post(new Runnable() {
16216                    public void run() {
16217                        deletePackageX(packageName, userHandle, 0);
16218                    } //end run
16219                });
16220            }
16221        }
16222    }
16223
16224    /** Called by UserManagerService */
16225    void createNewUserLILPw(int userHandle) {
16226        if (mInstaller != null) {
16227            mInstaller.createUserConfig(userHandle);
16228            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16229            applyFactoryDefaultBrowserLPw(userHandle);
16230            primeDomainVerificationsLPw(userHandle);
16231        }
16232    }
16233
16234    void newUserCreated(final int userHandle) {
16235        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16236    }
16237
16238    @Override
16239    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16240        mContext.enforceCallingOrSelfPermission(
16241                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16242                "Only package verification agents can read the verifier device identity");
16243
16244        synchronized (mPackages) {
16245            return mSettings.getVerifierDeviceIdentityLPw();
16246        }
16247    }
16248
16249    @Override
16250    public void setPermissionEnforced(String permission, boolean enforced) {
16251        // TODO: Now that we no longer change GID for storage, this should to away.
16252        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16253                "setPermissionEnforced");
16254        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16255            synchronized (mPackages) {
16256                if (mSettings.mReadExternalStorageEnforced == null
16257                        || mSettings.mReadExternalStorageEnforced != enforced) {
16258                    mSettings.mReadExternalStorageEnforced = enforced;
16259                    mSettings.writeLPr();
16260                }
16261            }
16262            // kill any non-foreground processes so we restart them and
16263            // grant/revoke the GID.
16264            final IActivityManager am = ActivityManagerNative.getDefault();
16265            if (am != null) {
16266                final long token = Binder.clearCallingIdentity();
16267                try {
16268                    am.killProcessesBelowForeground("setPermissionEnforcement");
16269                } catch (RemoteException e) {
16270                } finally {
16271                    Binder.restoreCallingIdentity(token);
16272                }
16273            }
16274        } else {
16275            throw new IllegalArgumentException("No selective enforcement for " + permission);
16276        }
16277    }
16278
16279    @Override
16280    @Deprecated
16281    public boolean isPermissionEnforced(String permission) {
16282        return true;
16283    }
16284
16285    @Override
16286    public boolean isStorageLow() {
16287        final long token = Binder.clearCallingIdentity();
16288        try {
16289            final DeviceStorageMonitorInternal
16290                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16291            if (dsm != null) {
16292                return dsm.isMemoryLow();
16293            } else {
16294                return false;
16295            }
16296        } finally {
16297            Binder.restoreCallingIdentity(token);
16298        }
16299    }
16300
16301    @Override
16302    public IPackageInstaller getPackageInstaller() {
16303        return mInstallerService;
16304    }
16305
16306    private boolean userNeedsBadging(int userId) {
16307        int index = mUserNeedsBadging.indexOfKey(userId);
16308        if (index < 0) {
16309            final UserInfo userInfo;
16310            final long token = Binder.clearCallingIdentity();
16311            try {
16312                userInfo = sUserManager.getUserInfo(userId);
16313            } finally {
16314                Binder.restoreCallingIdentity(token);
16315            }
16316            final boolean b;
16317            if (userInfo != null && userInfo.isManagedProfile()) {
16318                b = true;
16319            } else {
16320                b = false;
16321            }
16322            mUserNeedsBadging.put(userId, b);
16323            return b;
16324        }
16325        return mUserNeedsBadging.valueAt(index);
16326    }
16327
16328    @Override
16329    public KeySet getKeySetByAlias(String packageName, String alias) {
16330        if (packageName == null || alias == null) {
16331            return null;
16332        }
16333        synchronized(mPackages) {
16334            final PackageParser.Package pkg = mPackages.get(packageName);
16335            if (pkg == null) {
16336                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16337                throw new IllegalArgumentException("Unknown package: " + packageName);
16338            }
16339            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16340            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16341        }
16342    }
16343
16344    @Override
16345    public KeySet getSigningKeySet(String packageName) {
16346        if (packageName == null) {
16347            return null;
16348        }
16349        synchronized(mPackages) {
16350            final PackageParser.Package pkg = mPackages.get(packageName);
16351            if (pkg == null) {
16352                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16353                throw new IllegalArgumentException("Unknown package: " + packageName);
16354            }
16355            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16356                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16357                throw new SecurityException("May not access signing KeySet of other apps.");
16358            }
16359            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16360            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16361        }
16362    }
16363
16364    @Override
16365    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16366        if (packageName == null || ks == null) {
16367            return false;
16368        }
16369        synchronized(mPackages) {
16370            final PackageParser.Package pkg = mPackages.get(packageName);
16371            if (pkg == null) {
16372                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16373                throw new IllegalArgumentException("Unknown package: " + packageName);
16374            }
16375            IBinder ksh = ks.getToken();
16376            if (ksh instanceof KeySetHandle) {
16377                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16378                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16379            }
16380            return false;
16381        }
16382    }
16383
16384    @Override
16385    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16386        if (packageName == null || ks == null) {
16387            return false;
16388        }
16389        synchronized(mPackages) {
16390            final PackageParser.Package pkg = mPackages.get(packageName);
16391            if (pkg == null) {
16392                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16393                throw new IllegalArgumentException("Unknown package: " + packageName);
16394            }
16395            IBinder ksh = ks.getToken();
16396            if (ksh instanceof KeySetHandle) {
16397                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16398                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16399            }
16400            return false;
16401        }
16402    }
16403
16404    public void getUsageStatsIfNoPackageUsageInfo() {
16405        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16406            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16407            if (usm == null) {
16408                throw new IllegalStateException("UsageStatsManager must be initialized");
16409            }
16410            long now = System.currentTimeMillis();
16411            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16412            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16413                String packageName = entry.getKey();
16414                PackageParser.Package pkg = mPackages.get(packageName);
16415                if (pkg == null) {
16416                    continue;
16417                }
16418                UsageStats usage = entry.getValue();
16419                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16420                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16421            }
16422        }
16423    }
16424
16425    /**
16426     * Check and throw if the given before/after packages would be considered a
16427     * downgrade.
16428     */
16429    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16430            throws PackageManagerException {
16431        if (after.versionCode < before.mVersionCode) {
16432            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16433                    "Update version code " + after.versionCode + " is older than current "
16434                    + before.mVersionCode);
16435        } else if (after.versionCode == before.mVersionCode) {
16436            if (after.baseRevisionCode < before.baseRevisionCode) {
16437                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16438                        "Update base revision code " + after.baseRevisionCode
16439                        + " is older than current " + before.baseRevisionCode);
16440            }
16441
16442            if (!ArrayUtils.isEmpty(after.splitNames)) {
16443                for (int i = 0; i < after.splitNames.length; i++) {
16444                    final String splitName = after.splitNames[i];
16445                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16446                    if (j != -1) {
16447                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16448                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16449                                    "Update split " + splitName + " revision code "
16450                                    + after.splitRevisionCodes[i] + " is older than current "
16451                                    + before.splitRevisionCodes[j]);
16452                        }
16453                    }
16454                }
16455            }
16456        }
16457    }
16458
16459    private static class MoveCallbacks extends Handler {
16460        private static final int MSG_CREATED = 1;
16461        private static final int MSG_STATUS_CHANGED = 2;
16462
16463        private final RemoteCallbackList<IPackageMoveObserver>
16464                mCallbacks = new RemoteCallbackList<>();
16465
16466        private final SparseIntArray mLastStatus = new SparseIntArray();
16467
16468        public MoveCallbacks(Looper looper) {
16469            super(looper);
16470        }
16471
16472        public void register(IPackageMoveObserver callback) {
16473            mCallbacks.register(callback);
16474        }
16475
16476        public void unregister(IPackageMoveObserver callback) {
16477            mCallbacks.unregister(callback);
16478        }
16479
16480        @Override
16481        public void handleMessage(Message msg) {
16482            final SomeArgs args = (SomeArgs) msg.obj;
16483            final int n = mCallbacks.beginBroadcast();
16484            for (int i = 0; i < n; i++) {
16485                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16486                try {
16487                    invokeCallback(callback, msg.what, args);
16488                } catch (RemoteException ignored) {
16489                }
16490            }
16491            mCallbacks.finishBroadcast();
16492            args.recycle();
16493        }
16494
16495        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16496                throws RemoteException {
16497            switch (what) {
16498                case MSG_CREATED: {
16499                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16500                    break;
16501                }
16502                case MSG_STATUS_CHANGED: {
16503                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16504                    break;
16505                }
16506            }
16507        }
16508
16509        private void notifyCreated(int moveId, Bundle extras) {
16510            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16511
16512            final SomeArgs args = SomeArgs.obtain();
16513            args.argi1 = moveId;
16514            args.arg2 = extras;
16515            obtainMessage(MSG_CREATED, args).sendToTarget();
16516        }
16517
16518        private void notifyStatusChanged(int moveId, int status) {
16519            notifyStatusChanged(moveId, status, -1);
16520        }
16521
16522        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16523            Slog.v(TAG, "Move " + moveId + " status " + status);
16524
16525            final SomeArgs args = SomeArgs.obtain();
16526            args.argi1 = moveId;
16527            args.argi2 = status;
16528            args.arg3 = estMillis;
16529            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16530
16531            synchronized (mLastStatus) {
16532                mLastStatus.put(moveId, status);
16533            }
16534        }
16535    }
16536
16537    private final class OnPermissionChangeListeners extends Handler {
16538        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16539
16540        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16541                new RemoteCallbackList<>();
16542
16543        public OnPermissionChangeListeners(Looper looper) {
16544            super(looper);
16545        }
16546
16547        @Override
16548        public void handleMessage(Message msg) {
16549            switch (msg.what) {
16550                case MSG_ON_PERMISSIONS_CHANGED: {
16551                    final int uid = msg.arg1;
16552                    handleOnPermissionsChanged(uid);
16553                } break;
16554            }
16555        }
16556
16557        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16558            mPermissionListeners.register(listener);
16559
16560        }
16561
16562        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16563            mPermissionListeners.unregister(listener);
16564        }
16565
16566        public void onPermissionsChanged(int uid) {
16567            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16568                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16569            }
16570        }
16571
16572        private void handleOnPermissionsChanged(int uid) {
16573            final int count = mPermissionListeners.beginBroadcast();
16574            try {
16575                for (int i = 0; i < count; i++) {
16576                    IOnPermissionsChangeListener callback = mPermissionListeners
16577                            .getBroadcastItem(i);
16578                    try {
16579                        callback.onPermissionsChanged(uid);
16580                    } catch (RemoteException e) {
16581                        Log.e(TAG, "Permission listener is dead", e);
16582                    }
16583                }
16584            } finally {
16585                mPermissionListeners.finishBroadcast();
16586            }
16587        }
16588    }
16589
16590    private class PackageManagerInternalImpl extends PackageManagerInternal {
16591        @Override
16592        public void setLocationPackagesProvider(PackagesProvider provider) {
16593            synchronized (mPackages) {
16594                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16595            }
16596        }
16597
16598        @Override
16599        public void setImePackagesProvider(PackagesProvider provider) {
16600            synchronized (mPackages) {
16601                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16602            }
16603        }
16604
16605        @Override
16606        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16607            synchronized (mPackages) {
16608                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16609            }
16610        }
16611
16612        @Override
16613        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16614            synchronized (mPackages) {
16615                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16616            }
16617        }
16618
16619        @Override
16620        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16621            synchronized (mPackages) {
16622                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16623            }
16624        }
16625
16626        @Override
16627        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16628            synchronized (mPackages) {
16629                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16630            }
16631        }
16632
16633        @Override
16634        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16635            synchronized (mPackages) {
16636                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16637            }
16638        }
16639
16640        @Override
16641        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16642            synchronized (mPackages) {
16643                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16644                        packageName, userId);
16645            }
16646        }
16647
16648        @Override
16649        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16650            synchronized (mPackages) {
16651                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16652                        packageName, userId);
16653            }
16654        }
16655        @Override
16656        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16657            synchronized (mPackages) {
16658                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16659                        packageName, userId);
16660            }
16661        }
16662    }
16663
16664    @Override
16665    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16666        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16667        synchronized (mPackages) {
16668            final long identity = Binder.clearCallingIdentity();
16669            try {
16670                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16671                        packageNames, userId);
16672            } finally {
16673                Binder.restoreCallingIdentity(identity);
16674            }
16675        }
16676    }
16677
16678    private static void enforceSystemOrPhoneCaller(String tag) {
16679        int callingUid = Binder.getCallingUid();
16680        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16681            throw new SecurityException(
16682                    "Cannot call " + tag + " from UID " + callingUid);
16683        }
16684    }
16685}
16686