PackageManagerService.java revision bb054c9dcc68d24e1d2ded709b721948b939018c
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Binder;
147import android.os.Build;
148import android.os.Bundle;
149import android.os.Debug;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.StorageEventListener;
170import android.os.storage.StorageManager;
171import android.os.storage.VolumeInfo;
172import android.os.storage.VolumeRecord;
173import android.security.KeyStore;
174import android.security.SystemKeyStore;
175import android.system.ErrnoException;
176import android.system.Os;
177import android.system.StructStat;
178import android.text.TextUtils;
179import android.text.format.DateUtils;
180import android.util.ArrayMap;
181import android.util.ArraySet;
182import android.util.AtomicFile;
183import android.util.DisplayMetrics;
184import android.util.EventLog;
185import android.util.ExceptionUtils;
186import android.util.Log;
187import android.util.LogPrinter;
188import android.util.MathUtils;
189import android.util.PrintStreamPrinter;
190import android.util.Slog;
191import android.util.SparseArray;
192import android.util.SparseBooleanArray;
193import android.util.SparseIntArray;
194import android.util.Xml;
195import android.view.Display;
196
197import dalvik.system.DexFile;
198import dalvik.system.VMRuntime;
199
200import libcore.io.IoUtils;
201import libcore.util.EmptyArray;
202
203import com.android.internal.R;
204import com.android.internal.annotations.GuardedBy;
205import com.android.internal.app.IMediaContainerService;
206import com.android.internal.app.ResolverActivity;
207import com.android.internal.content.NativeLibraryHelper;
208import com.android.internal.content.PackageHelper;
209import com.android.internal.os.IParcelFileDescriptorFactory;
210import com.android.internal.os.SomeArgs;
211import com.android.internal.os.Zygote;
212import com.android.internal.util.ArrayUtils;
213import com.android.internal.util.FastPrintWriter;
214import com.android.internal.util.FastXmlSerializer;
215import com.android.internal.util.IndentingPrintWriter;
216import com.android.internal.util.Preconditions;
217import com.android.server.EventLogTags;
218import com.android.server.FgThread;
219import com.android.server.IntentResolver;
220import com.android.server.LocalServices;
221import com.android.server.ServiceThread;
222import com.android.server.SystemConfig;
223import com.android.server.Watchdog;
224import com.android.server.pm.PermissionsState.PermissionState;
225import com.android.server.pm.Settings.DatabaseVersion;
226import com.android.server.storage.DeviceStorageMonitorInternal;
227
228import org.xmlpull.v1.XmlPullParser;
229import org.xmlpull.v1.XmlPullParserException;
230import org.xmlpull.v1.XmlSerializer;
231
232import java.io.BufferedInputStream;
233import java.io.BufferedOutputStream;
234import java.io.BufferedReader;
235import java.io.ByteArrayInputStream;
236import java.io.ByteArrayOutputStream;
237import java.io.File;
238import java.io.FileDescriptor;
239import java.io.FileNotFoundException;
240import java.io.FileOutputStream;
241import java.io.FileReader;
242import java.io.FilenameFilter;
243import java.io.IOException;
244import java.io.InputStream;
245import java.io.PrintWriter;
246import java.nio.charset.StandardCharsets;
247import java.security.NoSuchAlgorithmException;
248import java.security.PublicKey;
249import java.security.cert.CertificateEncodingException;
250import java.security.cert.CertificateException;
251import java.text.SimpleDateFormat;
252import java.util.ArrayList;
253import java.util.Arrays;
254import java.util.Collection;
255import java.util.Collections;
256import java.util.Comparator;
257import java.util.Date;
258import java.util.Iterator;
259import java.util.List;
260import java.util.Map;
261import java.util.Objects;
262import java.util.Set;
263import java.util.concurrent.CountDownLatch;
264import java.util.concurrent.TimeUnit;
265import java.util.concurrent.atomic.AtomicBoolean;
266import java.util.concurrent.atomic.AtomicInteger;
267import java.util.concurrent.atomic.AtomicLong;
268
269/**
270 * Keep track of all those .apks everywhere.
271 *
272 * This is very central to the platform's security; please run the unit
273 * tests whenever making modifications here:
274 *
275mmm frameworks/base/tests/AndroidTests
276adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
277adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
278 *
279 * {@hide}
280 */
281public class PackageManagerService extends IPackageManager.Stub {
282    static final String TAG = "PackageManager";
283    static final boolean DEBUG_SETTINGS = false;
284    static final boolean DEBUG_PREFERRED = false;
285    static final boolean DEBUG_UPGRADE = false;
286    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
287    private static final boolean DEBUG_BACKUP = true;
288    private static final boolean DEBUG_INSTALL = false;
289    private static final boolean DEBUG_REMOVE = false;
290    private static final boolean DEBUG_BROADCASTS = false;
291    private static final boolean DEBUG_SHOW_INFO = false;
292    private static final boolean DEBUG_PACKAGE_INFO = false;
293    private static final boolean DEBUG_INTENT_MATCHING = false;
294    private static final boolean DEBUG_PACKAGE_SCANNING = false;
295    private static final boolean DEBUG_VERIFY = false;
296    private static final boolean DEBUG_DEXOPT = false;
297    private static final boolean DEBUG_ABI_SELECTION = false;
298
299    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
300
301    private static final int RADIO_UID = Process.PHONE_UID;
302    private static final int LOG_UID = Process.LOG_UID;
303    private static final int NFC_UID = Process.NFC_UID;
304    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
305    private static final int SHELL_UID = Process.SHELL_UID;
306
307    // Cap the size of permission trees that 3rd party apps can define
308    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
309
310    // Suffix used during package installation when copying/moving
311    // package apks to install directory.
312    private static final String INSTALL_PACKAGE_SUFFIX = "-";
313
314    static final int SCAN_NO_DEX = 1<<1;
315    static final int SCAN_FORCE_DEX = 1<<2;
316    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
317    static final int SCAN_NEW_INSTALL = 1<<4;
318    static final int SCAN_NO_PATHS = 1<<5;
319    static final int SCAN_UPDATE_TIME = 1<<6;
320    static final int SCAN_DEFER_DEX = 1<<7;
321    static final int SCAN_BOOTING = 1<<8;
322    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
323    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
324    static final int SCAN_REQUIRE_KNOWN = 1<<12;
325    static final int SCAN_MOVE = 1<<13;
326    static final int SCAN_INITIAL = 1<<14;
327
328    static final int REMOVE_CHATTY = 1<<16;
329
330    private static final int[] EMPTY_INT_ARRAY = new int[0];
331
332    /**
333     * Timeout (in milliseconds) after which the watchdog should declare that
334     * our handler thread is wedged.  The usual default for such things is one
335     * minute but we sometimes do very lengthy I/O operations on this thread,
336     * such as installing multi-gigabyte applications, so ours needs to be longer.
337     */
338    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
339
340    /**
341     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
342     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
343     * settings entry if available, otherwise we use the hardcoded default.  If it's been
344     * more than this long since the last fstrim, we force one during the boot sequence.
345     *
346     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
347     * one gets run at the next available charging+idle time.  This final mandatory
348     * no-fstrim check kicks in only of the other scheduling criteria is never met.
349     */
350    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
351
352    /**
353     * Whether verification is enabled by default.
354     */
355    private static final boolean DEFAULT_VERIFY_ENABLE = true;
356
357    /**
358     * The default maximum time to wait for the verification agent to return in
359     * milliseconds.
360     */
361    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
362
363    /**
364     * The default response for package verification timeout.
365     *
366     * This can be either PackageManager.VERIFICATION_ALLOW or
367     * PackageManager.VERIFICATION_REJECT.
368     */
369    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
370
371    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
372
373    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
374            DEFAULT_CONTAINER_PACKAGE,
375            "com.android.defcontainer.DefaultContainerService");
376
377    private static final String KILL_APP_REASON_GIDS_CHANGED =
378            "permission grant or revoke changed gids";
379
380    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
381            "permissions revoked";
382
383    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
384
385    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
386
387    /** Permission grant: not grant the permission. */
388    private static final int GRANT_DENIED = 1;
389
390    /** Permission grant: grant the permission as an install permission. */
391    private static final int GRANT_INSTALL = 2;
392
393    /** Permission grant: grant the permission as an install permission for a legacy app. */
394    private static final int GRANT_INSTALL_LEGACY = 3;
395
396    /** Permission grant: grant the permission as a runtime one. */
397    private static final int GRANT_RUNTIME = 4;
398
399    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
400    private static final int GRANT_UPGRADE = 5;
401
402    /** Canonical intent used to identify what counts as a "web browser" app */
403    private static final Intent sBrowserIntent;
404    static {
405        sBrowserIntent = new Intent();
406        sBrowserIntent.setAction(Intent.ACTION_VIEW);
407        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
408        sBrowserIntent.setData(Uri.parse("http:"));
409    }
410
411    final ServiceThread mHandlerThread;
412
413    final PackageHandler mHandler;
414
415    /**
416     * Messages for {@link #mHandler} that need to wait for system ready before
417     * being dispatched.
418     */
419    private ArrayList<Message> mPostSystemReadyMessages;
420
421    final int mSdkVersion = Build.VERSION.SDK_INT;
422
423    final Context mContext;
424    final boolean mFactoryTest;
425    final boolean mOnlyCore;
426    final boolean mLazyDexOpt;
427    final long mDexOptLRUThresholdInMills;
428    final DisplayMetrics mMetrics;
429    final int mDefParseFlags;
430    final String[] mSeparateProcesses;
431    final boolean mIsUpgrade;
432
433    // This is where all application persistent data goes.
434    final File mAppDataDir;
435
436    // This is where all application persistent data goes for secondary users.
437    final File mUserAppDataDir;
438
439    /** The location for ASEC container files on internal storage. */
440    final String mAsecInternalPath;
441
442    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
443    // LOCK HELD.  Can be called with mInstallLock held.
444    @GuardedBy("mInstallLock")
445    final Installer mInstaller;
446
447    /** Directory where installed third-party apps stored */
448    final File mAppInstallDir;
449
450    /**
451     * Directory to which applications installed internally have their
452     * 32 bit native libraries copied.
453     */
454    private File mAppLib32InstallDir;
455
456    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
457    // apps.
458    final File mDrmAppPrivateInstallDir;
459
460    // ----------------------------------------------------------------
461
462    // Lock for state used when installing and doing other long running
463    // operations.  Methods that must be called with this lock held have
464    // the suffix "LI".
465    final Object mInstallLock = new Object();
466
467    // ----------------------------------------------------------------
468
469    // Keys are String (package name), values are Package.  This also serves
470    // as the lock for the global state.  Methods that must be called with
471    // this lock held have the prefix "LP".
472    @GuardedBy("mPackages")
473    final ArrayMap<String, PackageParser.Package> mPackages =
474            new ArrayMap<String, PackageParser.Package>();
475
476    // Tracks available target package names -> overlay package paths.
477    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
478        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
479
480    final Settings mSettings;
481    boolean mRestoredSettings;
482
483    // System configuration read by SystemConfig.
484    final int[] mGlobalGids;
485    final SparseArray<ArraySet<String>> mSystemPermissions;
486    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
487
488    // If mac_permissions.xml was found for seinfo labeling.
489    boolean mFoundPolicyFile;
490
491    // If a recursive restorecon of /data/data/<pkg> is needed.
492    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
493
494    public static final class SharedLibraryEntry {
495        public final String path;
496        public final String apk;
497
498        SharedLibraryEntry(String _path, String _apk) {
499            path = _path;
500            apk = _apk;
501        }
502    }
503
504    // Currently known shared libraries.
505    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
506            new ArrayMap<String, SharedLibraryEntry>();
507
508    // All available activities, for your resolving pleasure.
509    final ActivityIntentResolver mActivities =
510            new ActivityIntentResolver();
511
512    // All available receivers, for your resolving pleasure.
513    final ActivityIntentResolver mReceivers =
514            new ActivityIntentResolver();
515
516    // All available services, for your resolving pleasure.
517    final ServiceIntentResolver mServices = new ServiceIntentResolver();
518
519    // All available providers, for your resolving pleasure.
520    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
521
522    // Mapping from provider base names (first directory in content URI codePath)
523    // to the provider information.
524    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
525            new ArrayMap<String, PackageParser.Provider>();
526
527    // Mapping from instrumentation class names to info about them.
528    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
529            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
530
531    // Mapping from permission names to info about them.
532    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
533            new ArrayMap<String, PackageParser.PermissionGroup>();
534
535    // Packages whose data we have transfered into another package, thus
536    // should no longer exist.
537    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
538
539    // Broadcast actions that are only available to the system.
540    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
541
542    /** List of packages waiting for verification. */
543    final SparseArray<PackageVerificationState> mPendingVerification
544            = new SparseArray<PackageVerificationState>();
545
546    /** Set of packages associated with each app op permission. */
547    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
548
549    final PackageInstallerService mInstallerService;
550
551    private final PackageDexOptimizer mPackageDexOptimizer;
552
553    private AtomicInteger mNextMoveId = new AtomicInteger();
554    private final MoveCallbacks mMoveCallbacks;
555
556    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
557
558    // Cache of users who need badging.
559    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
560
561    /** Token for keys in mPendingVerification. */
562    private int mPendingVerificationToken = 0;
563
564    volatile boolean mSystemReady;
565    volatile boolean mSafeMode;
566    volatile boolean mHasSystemUidErrors;
567
568    ApplicationInfo mAndroidApplication;
569    final ActivityInfo mResolveActivity = new ActivityInfo();
570    final ResolveInfo mResolveInfo = new ResolveInfo();
571    ComponentName mResolveComponentName;
572    PackageParser.Package mPlatformPackage;
573    ComponentName mCustomResolverComponentName;
574
575    boolean mResolverReplaced = false;
576
577    private final ComponentName mIntentFilterVerifierComponent;
578    private int mIntentFilterVerificationToken = 0;
579
580    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
581            = new SparseArray<IntentFilterVerificationState>();
582
583    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
584            new DefaultPermissionGrantPolicy(this);
585
586    private static class IFVerificationParams {
587        PackageParser.Package pkg;
588        boolean replacing;
589        int userId;
590        int verifierUid;
591
592        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
593                int _userId, int _verifierUid) {
594            pkg = _pkg;
595            replacing = _replacing;
596            userId = _userId;
597            replacing = _replacing;
598            verifierUid = _verifierUid;
599        }
600    }
601
602    private interface IntentFilterVerifier<T extends IntentFilter> {
603        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
604                                               T filter, String packageName);
605        void startVerifications(int userId);
606        void receiveVerificationResponse(int verificationId);
607    }
608
609    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
610        private Context mContext;
611        private ComponentName mIntentFilterVerifierComponent;
612        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
613
614        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
615            mContext = context;
616            mIntentFilterVerifierComponent = verifierComponent;
617        }
618
619        private String getDefaultScheme() {
620            return IntentFilter.SCHEME_HTTPS;
621        }
622
623        @Override
624        public void startVerifications(int userId) {
625            // Launch verifications requests
626            int count = mCurrentIntentFilterVerifications.size();
627            for (int n=0; n<count; n++) {
628                int verificationId = mCurrentIntentFilterVerifications.get(n);
629                final IntentFilterVerificationState ivs =
630                        mIntentFilterVerificationStates.get(verificationId);
631
632                String packageName = ivs.getPackageName();
633
634                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
635                final int filterCount = filters.size();
636                ArraySet<String> domainsSet = new ArraySet<>();
637                for (int m=0; m<filterCount; m++) {
638                    PackageParser.ActivityIntentInfo filter = filters.get(m);
639                    domainsSet.addAll(filter.getHostsList());
640                }
641                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
642                synchronized (mPackages) {
643                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
644                            packageName, domainsList) != null) {
645                        scheduleWriteSettingsLocked();
646                    }
647                }
648                sendVerificationRequest(userId, verificationId, ivs);
649            }
650            mCurrentIntentFilterVerifications.clear();
651        }
652
653        private void sendVerificationRequest(int userId, int verificationId,
654                IntentFilterVerificationState ivs) {
655
656            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
657            verificationIntent.putExtra(
658                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
659                    verificationId);
660            verificationIntent.putExtra(
661                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
662                    getDefaultScheme());
663            verificationIntent.putExtra(
664                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
665                    ivs.getHostsString());
666            verificationIntent.putExtra(
667                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
668                    ivs.getPackageName());
669            verificationIntent.setComponent(mIntentFilterVerifierComponent);
670            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
671
672            UserHandle user = new UserHandle(userId);
673            mContext.sendBroadcastAsUser(verificationIntent, user);
674            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
675                    "Sending IntentFilter verification broadcast");
676        }
677
678        public void receiveVerificationResponse(int verificationId) {
679            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
680
681            final boolean verified = ivs.isVerified();
682
683            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
684            final int count = filters.size();
685            if (DEBUG_DOMAIN_VERIFICATION) {
686                Slog.i(TAG, "Received verification response " + verificationId
687                        + " for " + count + " filters, verified=" + verified);
688            }
689            for (int n=0; n<count; n++) {
690                PackageParser.ActivityIntentInfo filter = filters.get(n);
691                filter.setVerified(verified);
692
693                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
694                        + " verified with result:" + verified + " and hosts:"
695                        + ivs.getHostsString());
696            }
697
698            mIntentFilterVerificationStates.remove(verificationId);
699
700            final String packageName = ivs.getPackageName();
701            IntentFilterVerificationInfo ivi = null;
702
703            synchronized (mPackages) {
704                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
705            }
706            if (ivi == null) {
707                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
708                        + verificationId + " packageName:" + packageName);
709                return;
710            }
711            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
712                    "Updating IntentFilterVerificationInfo for package " + packageName
713                            +" verificationId:" + verificationId);
714
715            synchronized (mPackages) {
716                if (verified) {
717                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
718                } else {
719                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
720                }
721                scheduleWriteSettingsLocked();
722
723                final int userId = ivs.getUserId();
724                if (userId != UserHandle.USER_ALL) {
725                    final int userStatus =
726                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
727
728                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
729                    boolean needUpdate = false;
730
731                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
732                    // already been set by the User thru the Disambiguation dialog
733                    switch (userStatus) {
734                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
735                            if (verified) {
736                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
737                            } else {
738                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
739                            }
740                            needUpdate = true;
741                            break;
742
743                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
744                            if (verified) {
745                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
746                                needUpdate = true;
747                            }
748                            break;
749
750                        default:
751                            // Nothing to do
752                    }
753
754                    if (needUpdate) {
755                        mSettings.updateIntentFilterVerificationStatusLPw(
756                                packageName, updatedStatus, userId);
757                        scheduleWritePackageRestrictionsLocked(userId);
758                    }
759                }
760            }
761        }
762
763        @Override
764        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
765                    ActivityIntentInfo filter, String packageName) {
766            if (!hasValidDomains(filter)) {
767                return false;
768            }
769            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
770            if (ivs == null) {
771                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
772                        packageName);
773            }
774            if (DEBUG_DOMAIN_VERIFICATION) {
775                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
776            }
777            ivs.addFilter(filter);
778            return true;
779        }
780
781        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
782                int userId, int verificationId, String packageName) {
783            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
784                    verifierUid, userId, packageName);
785            ivs.setPendingState();
786            synchronized (mPackages) {
787                mIntentFilterVerificationStates.append(verificationId, ivs);
788                mCurrentIntentFilterVerifications.add(verificationId);
789            }
790            return ivs;
791        }
792    }
793
794    private static boolean hasValidDomains(ActivityIntentInfo filter) {
795        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
796                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
797        if (!hasHTTPorHTTPS) {
798            return false;
799        }
800        return true;
801    }
802
803    private IntentFilterVerifier mIntentFilterVerifier;
804
805    // Set of pending broadcasts for aggregating enable/disable of components.
806    static class PendingPackageBroadcasts {
807        // for each user id, a map of <package name -> components within that package>
808        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
809
810        public PendingPackageBroadcasts() {
811            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
812        }
813
814        public ArrayList<String> get(int userId, String packageName) {
815            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
816            return packages.get(packageName);
817        }
818
819        public void put(int userId, String packageName, ArrayList<String> components) {
820            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
821            packages.put(packageName, components);
822        }
823
824        public void remove(int userId, String packageName) {
825            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
826            if (packages != null) {
827                packages.remove(packageName);
828            }
829        }
830
831        public void remove(int userId) {
832            mUidMap.remove(userId);
833        }
834
835        public int userIdCount() {
836            return mUidMap.size();
837        }
838
839        public int userIdAt(int n) {
840            return mUidMap.keyAt(n);
841        }
842
843        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
844            return mUidMap.get(userId);
845        }
846
847        public int size() {
848            // total number of pending broadcast entries across all userIds
849            int num = 0;
850            for (int i = 0; i< mUidMap.size(); i++) {
851                num += mUidMap.valueAt(i).size();
852            }
853            return num;
854        }
855
856        public void clear() {
857            mUidMap.clear();
858        }
859
860        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
861            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
862            if (map == null) {
863                map = new ArrayMap<String, ArrayList<String>>();
864                mUidMap.put(userId, map);
865            }
866            return map;
867        }
868    }
869    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
870
871    // Service Connection to remote media container service to copy
872    // package uri's from external media onto secure containers
873    // or internal storage.
874    private IMediaContainerService mContainerService = null;
875
876    static final int SEND_PENDING_BROADCAST = 1;
877    static final int MCS_BOUND = 3;
878    static final int END_COPY = 4;
879    static final int INIT_COPY = 5;
880    static final int MCS_UNBIND = 6;
881    static final int START_CLEANING_PACKAGE = 7;
882    static final int FIND_INSTALL_LOC = 8;
883    static final int POST_INSTALL = 9;
884    static final int MCS_RECONNECT = 10;
885    static final int MCS_GIVE_UP = 11;
886    static final int UPDATED_MEDIA_STATUS = 12;
887    static final int WRITE_SETTINGS = 13;
888    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
889    static final int PACKAGE_VERIFIED = 15;
890    static final int CHECK_PENDING_VERIFICATION = 16;
891    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
892    static final int INTENT_FILTER_VERIFIED = 18;
893
894    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
895
896    // Delay time in millisecs
897    static final int BROADCAST_DELAY = 10 * 1000;
898
899    static UserManagerService sUserManager;
900
901    // Stores a list of users whose package restrictions file needs to be updated
902    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
903
904    final private DefaultContainerConnection mDefContainerConn =
905            new DefaultContainerConnection();
906    class DefaultContainerConnection implements ServiceConnection {
907        public void onServiceConnected(ComponentName name, IBinder service) {
908            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
909            IMediaContainerService imcs =
910                IMediaContainerService.Stub.asInterface(service);
911            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
912        }
913
914        public void onServiceDisconnected(ComponentName name) {
915            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
916        }
917    }
918
919    // Recordkeeping of restore-after-install operations that are currently in flight
920    // between the Package Manager and the Backup Manager
921    class PostInstallData {
922        public InstallArgs args;
923        public PackageInstalledInfo res;
924
925        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
926            args = _a;
927            res = _r;
928        }
929    }
930
931    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
932    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
933
934    // XML tags for backup/restore of various bits of state
935    private static final String TAG_PREFERRED_BACKUP = "pa";
936    private static final String TAG_DEFAULT_APPS = "da";
937    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
938
939    final String mRequiredVerifierPackage;
940    final String mRequiredInstallerPackage;
941
942    private final PackageUsage mPackageUsage = new PackageUsage();
943
944    private class PackageUsage {
945        private static final int WRITE_INTERVAL
946            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
947
948        private final Object mFileLock = new Object();
949        private final AtomicLong mLastWritten = new AtomicLong(0);
950        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
951
952        private boolean mIsHistoricalPackageUsageAvailable = true;
953
954        boolean isHistoricalPackageUsageAvailable() {
955            return mIsHistoricalPackageUsageAvailable;
956        }
957
958        void write(boolean force) {
959            if (force) {
960                writeInternal();
961                return;
962            }
963            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
964                && !DEBUG_DEXOPT) {
965                return;
966            }
967            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
968                new Thread("PackageUsage_DiskWriter") {
969                    @Override
970                    public void run() {
971                        try {
972                            writeInternal();
973                        } finally {
974                            mBackgroundWriteRunning.set(false);
975                        }
976                    }
977                }.start();
978            }
979        }
980
981        private void writeInternal() {
982            synchronized (mPackages) {
983                synchronized (mFileLock) {
984                    AtomicFile file = getFile();
985                    FileOutputStream f = null;
986                    try {
987                        f = file.startWrite();
988                        BufferedOutputStream out = new BufferedOutputStream(f);
989                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
990                        StringBuilder sb = new StringBuilder();
991                        for (PackageParser.Package pkg : mPackages.values()) {
992                            if (pkg.mLastPackageUsageTimeInMills == 0) {
993                                continue;
994                            }
995                            sb.setLength(0);
996                            sb.append(pkg.packageName);
997                            sb.append(' ');
998                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
999                            sb.append('\n');
1000                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1001                        }
1002                        out.flush();
1003                        file.finishWrite(f);
1004                    } catch (IOException e) {
1005                        if (f != null) {
1006                            file.failWrite(f);
1007                        }
1008                        Log.e(TAG, "Failed to write package usage times", e);
1009                    }
1010                }
1011            }
1012            mLastWritten.set(SystemClock.elapsedRealtime());
1013        }
1014
1015        void readLP() {
1016            synchronized (mFileLock) {
1017                AtomicFile file = getFile();
1018                BufferedInputStream in = null;
1019                try {
1020                    in = new BufferedInputStream(file.openRead());
1021                    StringBuffer sb = new StringBuffer();
1022                    while (true) {
1023                        String packageName = readToken(in, sb, ' ');
1024                        if (packageName == null) {
1025                            break;
1026                        }
1027                        String timeInMillisString = readToken(in, sb, '\n');
1028                        if (timeInMillisString == null) {
1029                            throw new IOException("Failed to find last usage time for package "
1030                                                  + packageName);
1031                        }
1032                        PackageParser.Package pkg = mPackages.get(packageName);
1033                        if (pkg == null) {
1034                            continue;
1035                        }
1036                        long timeInMillis;
1037                        try {
1038                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1039                        } catch (NumberFormatException e) {
1040                            throw new IOException("Failed to parse " + timeInMillisString
1041                                                  + " as a long.", e);
1042                        }
1043                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1044                    }
1045                } catch (FileNotFoundException expected) {
1046                    mIsHistoricalPackageUsageAvailable = false;
1047                } catch (IOException e) {
1048                    Log.w(TAG, "Failed to read package usage times", e);
1049                } finally {
1050                    IoUtils.closeQuietly(in);
1051                }
1052            }
1053            mLastWritten.set(SystemClock.elapsedRealtime());
1054        }
1055
1056        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1057                throws IOException {
1058            sb.setLength(0);
1059            while (true) {
1060                int ch = in.read();
1061                if (ch == -1) {
1062                    if (sb.length() == 0) {
1063                        return null;
1064                    }
1065                    throw new IOException("Unexpected EOF");
1066                }
1067                if (ch == endOfToken) {
1068                    return sb.toString();
1069                }
1070                sb.append((char)ch);
1071            }
1072        }
1073
1074        private AtomicFile getFile() {
1075            File dataDir = Environment.getDataDirectory();
1076            File systemDir = new File(dataDir, "system");
1077            File fname = new File(systemDir, "package-usage.list");
1078            return new AtomicFile(fname);
1079        }
1080    }
1081
1082    class PackageHandler extends Handler {
1083        private boolean mBound = false;
1084        final ArrayList<HandlerParams> mPendingInstalls =
1085            new ArrayList<HandlerParams>();
1086
1087        private boolean connectToService() {
1088            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1089                    " DefaultContainerService");
1090            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1091            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1092            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1093                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1094                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1095                mBound = true;
1096                return true;
1097            }
1098            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1099            return false;
1100        }
1101
1102        private void disconnectService() {
1103            mContainerService = null;
1104            mBound = false;
1105            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1106            mContext.unbindService(mDefContainerConn);
1107            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1108        }
1109
1110        PackageHandler(Looper looper) {
1111            super(looper);
1112        }
1113
1114        public void handleMessage(Message msg) {
1115            try {
1116                doHandleMessage(msg);
1117            } finally {
1118                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1119            }
1120        }
1121
1122        void doHandleMessage(Message msg) {
1123            switch (msg.what) {
1124                case INIT_COPY: {
1125                    HandlerParams params = (HandlerParams) msg.obj;
1126                    int idx = mPendingInstalls.size();
1127                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1128                    // If a bind was already initiated we dont really
1129                    // need to do anything. The pending install
1130                    // will be processed later on.
1131                    if (!mBound) {
1132                        // If this is the only one pending we might
1133                        // have to bind to the service again.
1134                        if (!connectToService()) {
1135                            Slog.e(TAG, "Failed to bind to media container service");
1136                            params.serviceError();
1137                            return;
1138                        } else {
1139                            // Once we bind to the service, the first
1140                            // pending request will be processed.
1141                            mPendingInstalls.add(idx, params);
1142                        }
1143                    } else {
1144                        mPendingInstalls.add(idx, params);
1145                        // Already bound to the service. Just make
1146                        // sure we trigger off processing the first request.
1147                        if (idx == 0) {
1148                            mHandler.sendEmptyMessage(MCS_BOUND);
1149                        }
1150                    }
1151                    break;
1152                }
1153                case MCS_BOUND: {
1154                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1155                    if (msg.obj != null) {
1156                        mContainerService = (IMediaContainerService) msg.obj;
1157                    }
1158                    if (mContainerService == null) {
1159                        if (!mBound) {
1160                            // Something seriously wrong since we are not bound and we are not
1161                            // waiting for connection. Bail out.
1162                            Slog.e(TAG, "Cannot bind to media container service");
1163                            for (HandlerParams params : mPendingInstalls) {
1164                                // Indicate service bind error
1165                                params.serviceError();
1166                            }
1167                            mPendingInstalls.clear();
1168                        } else {
1169                            Slog.w(TAG, "Waiting to connect to media container service");
1170                        }
1171                    } else if (mPendingInstalls.size() > 0) {
1172                        HandlerParams params = mPendingInstalls.get(0);
1173                        if (params != null) {
1174                            if (params.startCopy()) {
1175                                // We are done...  look for more work or to
1176                                // go idle.
1177                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1178                                        "Checking for more work or unbind...");
1179                                // Delete pending install
1180                                if (mPendingInstalls.size() > 0) {
1181                                    mPendingInstalls.remove(0);
1182                                }
1183                                if (mPendingInstalls.size() == 0) {
1184                                    if (mBound) {
1185                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1186                                                "Posting delayed MCS_UNBIND");
1187                                        removeMessages(MCS_UNBIND);
1188                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1189                                        // Unbind after a little delay, to avoid
1190                                        // continual thrashing.
1191                                        sendMessageDelayed(ubmsg, 10000);
1192                                    }
1193                                } else {
1194                                    // There are more pending requests in queue.
1195                                    // Just post MCS_BOUND message to trigger processing
1196                                    // of next pending install.
1197                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1198                                            "Posting MCS_BOUND for next work");
1199                                    mHandler.sendEmptyMessage(MCS_BOUND);
1200                                }
1201                            }
1202                        }
1203                    } else {
1204                        // Should never happen ideally.
1205                        Slog.w(TAG, "Empty queue");
1206                    }
1207                    break;
1208                }
1209                case MCS_RECONNECT: {
1210                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1211                    if (mPendingInstalls.size() > 0) {
1212                        if (mBound) {
1213                            disconnectService();
1214                        }
1215                        if (!connectToService()) {
1216                            Slog.e(TAG, "Failed to bind to media container service");
1217                            for (HandlerParams params : mPendingInstalls) {
1218                                // Indicate service bind error
1219                                params.serviceError();
1220                            }
1221                            mPendingInstalls.clear();
1222                        }
1223                    }
1224                    break;
1225                }
1226                case MCS_UNBIND: {
1227                    // If there is no actual work left, then time to unbind.
1228                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1229
1230                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1231                        if (mBound) {
1232                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1233
1234                            disconnectService();
1235                        }
1236                    } else if (mPendingInstalls.size() > 0) {
1237                        // There are more pending requests in queue.
1238                        // Just post MCS_BOUND message to trigger processing
1239                        // of next pending install.
1240                        mHandler.sendEmptyMessage(MCS_BOUND);
1241                    }
1242
1243                    break;
1244                }
1245                case MCS_GIVE_UP: {
1246                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1247                    mPendingInstalls.remove(0);
1248                    break;
1249                }
1250                case SEND_PENDING_BROADCAST: {
1251                    String packages[];
1252                    ArrayList<String> components[];
1253                    int size = 0;
1254                    int uids[];
1255                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1256                    synchronized (mPackages) {
1257                        if (mPendingBroadcasts == null) {
1258                            return;
1259                        }
1260                        size = mPendingBroadcasts.size();
1261                        if (size <= 0) {
1262                            // Nothing to be done. Just return
1263                            return;
1264                        }
1265                        packages = new String[size];
1266                        components = new ArrayList[size];
1267                        uids = new int[size];
1268                        int i = 0;  // filling out the above arrays
1269
1270                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1271                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1272                            Iterator<Map.Entry<String, ArrayList<String>>> it
1273                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1274                                            .entrySet().iterator();
1275                            while (it.hasNext() && i < size) {
1276                                Map.Entry<String, ArrayList<String>> ent = it.next();
1277                                packages[i] = ent.getKey();
1278                                components[i] = ent.getValue();
1279                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1280                                uids[i] = (ps != null)
1281                                        ? UserHandle.getUid(packageUserId, ps.appId)
1282                                        : -1;
1283                                i++;
1284                            }
1285                        }
1286                        size = i;
1287                        mPendingBroadcasts.clear();
1288                    }
1289                    // Send broadcasts
1290                    for (int i = 0; i < size; i++) {
1291                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1292                    }
1293                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1294                    break;
1295                }
1296                case START_CLEANING_PACKAGE: {
1297                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1298                    final String packageName = (String)msg.obj;
1299                    final int userId = msg.arg1;
1300                    final boolean andCode = msg.arg2 != 0;
1301                    synchronized (mPackages) {
1302                        if (userId == UserHandle.USER_ALL) {
1303                            int[] users = sUserManager.getUserIds();
1304                            for (int user : users) {
1305                                mSettings.addPackageToCleanLPw(
1306                                        new PackageCleanItem(user, packageName, andCode));
1307                            }
1308                        } else {
1309                            mSettings.addPackageToCleanLPw(
1310                                    new PackageCleanItem(userId, packageName, andCode));
1311                        }
1312                    }
1313                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1314                    startCleaningPackages();
1315                } break;
1316                case POST_INSTALL: {
1317                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1318                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1319                    mRunningInstalls.delete(msg.arg1);
1320                    boolean deleteOld = false;
1321
1322                    if (data != null) {
1323                        InstallArgs args = data.args;
1324                        PackageInstalledInfo res = data.res;
1325
1326                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1327                            final String packageName = res.pkg.applicationInfo.packageName;
1328                            res.removedInfo.sendBroadcast(false, true, false);
1329                            Bundle extras = new Bundle(1);
1330                            extras.putInt(Intent.EXTRA_UID, res.uid);
1331
1332                            // Now that we successfully installed the package, grant runtime
1333                            // permissions if requested before broadcasting the install.
1334                            if ((args.installFlags
1335                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1336                                grantRequestedRuntimePermissions(res.pkg,
1337                                        args.user.getIdentifier());
1338                            }
1339
1340                            // Determine the set of users who are adding this
1341                            // package for the first time vs. those who are seeing
1342                            // an update.
1343                            int[] firstUsers;
1344                            int[] updateUsers = new int[0];
1345                            if (res.origUsers == null || res.origUsers.length == 0) {
1346                                firstUsers = res.newUsers;
1347                            } else {
1348                                firstUsers = new int[0];
1349                                for (int i=0; i<res.newUsers.length; i++) {
1350                                    int user = res.newUsers[i];
1351                                    boolean isNew = true;
1352                                    for (int j=0; j<res.origUsers.length; j++) {
1353                                        if (res.origUsers[j] == user) {
1354                                            isNew = false;
1355                                            break;
1356                                        }
1357                                    }
1358                                    if (isNew) {
1359                                        int[] newFirst = new int[firstUsers.length+1];
1360                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1361                                                firstUsers.length);
1362                                        newFirst[firstUsers.length] = user;
1363                                        firstUsers = newFirst;
1364                                    } else {
1365                                        int[] newUpdate = new int[updateUsers.length+1];
1366                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1367                                                updateUsers.length);
1368                                        newUpdate[updateUsers.length] = user;
1369                                        updateUsers = newUpdate;
1370                                    }
1371                                }
1372                            }
1373                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1374                                    packageName, extras, null, null, firstUsers);
1375                            final boolean update = res.removedInfo.removedPackage != null;
1376                            if (update) {
1377                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1378                            }
1379                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1380                                    packageName, extras, null, null, updateUsers);
1381                            if (update) {
1382                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1383                                        packageName, extras, null, null, updateUsers);
1384                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1385                                        null, null, packageName, null, updateUsers);
1386
1387                                // treat asec-hosted packages like removable media on upgrade
1388                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1389                                    if (DEBUG_INSTALL) {
1390                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1391                                                + " is ASEC-hosted -> AVAILABLE");
1392                                    }
1393                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1394                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1395                                    pkgList.add(packageName);
1396                                    sendResourcesChangedBroadcast(true, true,
1397                                            pkgList,uidArray, null);
1398                                }
1399                            }
1400                            if (res.removedInfo.args != null) {
1401                                // Remove the replaced package's older resources safely now
1402                                deleteOld = true;
1403                            }
1404
1405                            // If this app is a browser and it's newly-installed for some
1406                            // users, clear any default-browser state in those users
1407                            if (firstUsers.length > 0) {
1408                                // the app's nature doesn't depend on the user, so we can just
1409                                // check its browser nature in any user and generalize.
1410                                if (packageIsBrowser(packageName, firstUsers[0])) {
1411                                    synchronized (mPackages) {
1412                                        for (int userId : firstUsers) {
1413                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1414                                        }
1415                                    }
1416                                }
1417                            }
1418                            // Log current value of "unknown sources" setting
1419                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1420                                getUnknownSourcesSettings());
1421                        }
1422                        // Force a gc to clear up things
1423                        Runtime.getRuntime().gc();
1424                        // We delete after a gc for applications  on sdcard.
1425                        if (deleteOld) {
1426                            synchronized (mInstallLock) {
1427                                res.removedInfo.args.doPostDeleteLI(true);
1428                            }
1429                        }
1430                        if (args.observer != null) {
1431                            try {
1432                                Bundle extras = extrasForInstallResult(res);
1433                                args.observer.onPackageInstalled(res.name, res.returnCode,
1434                                        res.returnMsg, extras);
1435                            } catch (RemoteException e) {
1436                                Slog.i(TAG, "Observer no longer exists.");
1437                            }
1438                        }
1439                    } else {
1440                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1441                    }
1442                } break;
1443                case UPDATED_MEDIA_STATUS: {
1444                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1445                    boolean reportStatus = msg.arg1 == 1;
1446                    boolean doGc = msg.arg2 == 1;
1447                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1448                    if (doGc) {
1449                        // Force a gc to clear up stale containers.
1450                        Runtime.getRuntime().gc();
1451                    }
1452                    if (msg.obj != null) {
1453                        @SuppressWarnings("unchecked")
1454                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1455                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1456                        // Unload containers
1457                        unloadAllContainers(args);
1458                    }
1459                    if (reportStatus) {
1460                        try {
1461                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1462                            PackageHelper.getMountService().finishMediaUpdate();
1463                        } catch (RemoteException e) {
1464                            Log.e(TAG, "MountService not running?");
1465                        }
1466                    }
1467                } break;
1468                case WRITE_SETTINGS: {
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470                    synchronized (mPackages) {
1471                        removeMessages(WRITE_SETTINGS);
1472                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1473                        mSettings.writeLPr();
1474                        mDirtyUsers.clear();
1475                    }
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1477                } break;
1478                case WRITE_PACKAGE_RESTRICTIONS: {
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1480                    synchronized (mPackages) {
1481                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1482                        for (int userId : mDirtyUsers) {
1483                            mSettings.writePackageRestrictionsLPr(userId);
1484                        }
1485                        mDirtyUsers.clear();
1486                    }
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1488                } break;
1489                case CHECK_PENDING_VERIFICATION: {
1490                    final int verificationId = msg.arg1;
1491                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1492
1493                    if ((state != null) && !state.timeoutExtended()) {
1494                        final InstallArgs args = state.getInstallArgs();
1495                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1496
1497                        Slog.i(TAG, "Verification timed out for " + originUri);
1498                        mPendingVerification.remove(verificationId);
1499
1500                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1501
1502                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1503                            Slog.i(TAG, "Continuing with installation of " + originUri);
1504                            state.setVerifierResponse(Binder.getCallingUid(),
1505                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1506                            broadcastPackageVerified(verificationId, originUri,
1507                                    PackageManager.VERIFICATION_ALLOW,
1508                                    state.getInstallArgs().getUser());
1509                            try {
1510                                ret = args.copyApk(mContainerService, true);
1511                            } catch (RemoteException e) {
1512                                Slog.e(TAG, "Could not contact the ContainerService");
1513                            }
1514                        } else {
1515                            broadcastPackageVerified(verificationId, originUri,
1516                                    PackageManager.VERIFICATION_REJECT,
1517                                    state.getInstallArgs().getUser());
1518                        }
1519
1520                        processPendingInstall(args, ret);
1521                        mHandler.sendEmptyMessage(MCS_UNBIND);
1522                    }
1523                    break;
1524                }
1525                case PACKAGE_VERIFIED: {
1526                    final int verificationId = msg.arg1;
1527
1528                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1529                    if (state == null) {
1530                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1531                        break;
1532                    }
1533
1534                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1535
1536                    state.setVerifierResponse(response.callerUid, response.code);
1537
1538                    if (state.isVerificationComplete()) {
1539                        mPendingVerification.remove(verificationId);
1540
1541                        final InstallArgs args = state.getInstallArgs();
1542                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1543
1544                        int ret;
1545                        if (state.isInstallAllowed()) {
1546                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1547                            broadcastPackageVerified(verificationId, originUri,
1548                                    response.code, state.getInstallArgs().getUser());
1549                            try {
1550                                ret = args.copyApk(mContainerService, true);
1551                            } catch (RemoteException e) {
1552                                Slog.e(TAG, "Could not contact the ContainerService");
1553                            }
1554                        } else {
1555                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1556                        }
1557
1558                        processPendingInstall(args, ret);
1559
1560                        mHandler.sendEmptyMessage(MCS_UNBIND);
1561                    }
1562
1563                    break;
1564                }
1565                case START_INTENT_FILTER_VERIFICATIONS: {
1566                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1567                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1568                            params.replacing, params.pkg);
1569                    break;
1570                }
1571                case INTENT_FILTER_VERIFIED: {
1572                    final int verificationId = msg.arg1;
1573
1574                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1575                            verificationId);
1576                    if (state == null) {
1577                        Slog.w(TAG, "Invalid IntentFilter verification token "
1578                                + verificationId + " received");
1579                        break;
1580                    }
1581
1582                    final int userId = state.getUserId();
1583
1584                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1585                            "Processing IntentFilter verification with token:"
1586                            + verificationId + " and userId:" + userId);
1587
1588                    final IntentFilterVerificationResponse response =
1589                            (IntentFilterVerificationResponse) msg.obj;
1590
1591                    state.setVerifierResponse(response.callerUid, response.code);
1592
1593                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1594                            "IntentFilter verification with token:" + verificationId
1595                            + " and userId:" + userId
1596                            + " is settings verifier response with response code:"
1597                            + response.code);
1598
1599                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1600                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1601                                + response.getFailedDomainsString());
1602                    }
1603
1604                    if (state.isVerificationComplete()) {
1605                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1606                    } else {
1607                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1608                                "IntentFilter verification with token:" + verificationId
1609                                + " was not said to be complete");
1610                    }
1611
1612                    break;
1613                }
1614            }
1615        }
1616    }
1617
1618    private StorageEventListener mStorageListener = new StorageEventListener() {
1619        @Override
1620        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1621            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1622                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1623                    final String volumeUuid = vol.getFsUuid();
1624
1625                    // Clean up any users or apps that were removed or recreated
1626                    // while this volume was missing
1627                    reconcileUsers(volumeUuid);
1628                    reconcileApps(volumeUuid);
1629
1630                    // Clean up any install sessions that expired or were
1631                    // cancelled while this volume was missing
1632                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1633
1634                    loadPrivatePackages(vol);
1635
1636                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1637                    unloadPrivatePackages(vol);
1638                }
1639            }
1640
1641            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1642                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1643                    updateExternalMediaStatus(true, false);
1644                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1645                    updateExternalMediaStatus(false, false);
1646                }
1647            }
1648        }
1649
1650        @Override
1651        public void onVolumeForgotten(String fsUuid) {
1652            // Remove any apps installed on the forgotten volume
1653            synchronized (mPackages) {
1654                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1655                for (PackageSetting ps : packages) {
1656                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1657                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1658                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1659                }
1660
1661                mSettings.writeLPr();
1662            }
1663        }
1664    };
1665
1666    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1667        if (userId >= UserHandle.USER_OWNER) {
1668            grantRequestedRuntimePermissionsForUser(pkg, userId);
1669        } else if (userId == UserHandle.USER_ALL) {
1670            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1671                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1672            }
1673        }
1674
1675        // We could have touched GID membership, so flush out packages.list
1676        synchronized (mPackages) {
1677            mSettings.writePackageListLPr();
1678        }
1679    }
1680
1681    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1682        SettingBase sb = (SettingBase) pkg.mExtras;
1683        if (sb == null) {
1684            return;
1685        }
1686
1687        PermissionsState permissionsState = sb.getPermissionsState();
1688
1689        for (String permission : pkg.requestedPermissions) {
1690            BasePermission bp = mSettings.mPermissions.get(permission);
1691            if (bp != null && bp.isRuntime()) {
1692                permissionsState.grantRuntimePermission(bp, userId);
1693            }
1694        }
1695    }
1696
1697    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1698        Bundle extras = null;
1699        switch (res.returnCode) {
1700            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1701                extras = new Bundle();
1702                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1703                        res.origPermission);
1704                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1705                        res.origPackage);
1706                break;
1707            }
1708            case PackageManager.INSTALL_SUCCEEDED: {
1709                extras = new Bundle();
1710                extras.putBoolean(Intent.EXTRA_REPLACING,
1711                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1712                break;
1713            }
1714        }
1715        return extras;
1716    }
1717
1718    void scheduleWriteSettingsLocked() {
1719        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1720            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1721        }
1722    }
1723
1724    void scheduleWritePackageRestrictionsLocked(int userId) {
1725        if (!sUserManager.exists(userId)) return;
1726        mDirtyUsers.add(userId);
1727        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1728            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1729        }
1730    }
1731
1732    public static PackageManagerService main(Context context, Installer installer,
1733            boolean factoryTest, boolean onlyCore) {
1734        PackageManagerService m = new PackageManagerService(context, installer,
1735                factoryTest, onlyCore);
1736        ServiceManager.addService("package", m);
1737        return m;
1738    }
1739
1740    static String[] splitString(String str, char sep) {
1741        int count = 1;
1742        int i = 0;
1743        while ((i=str.indexOf(sep, i)) >= 0) {
1744            count++;
1745            i++;
1746        }
1747
1748        String[] res = new String[count];
1749        i=0;
1750        count = 0;
1751        int lastI=0;
1752        while ((i=str.indexOf(sep, i)) >= 0) {
1753            res[count] = str.substring(lastI, i);
1754            count++;
1755            i++;
1756            lastI = i;
1757        }
1758        res[count] = str.substring(lastI, str.length());
1759        return res;
1760    }
1761
1762    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1763        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1764                Context.DISPLAY_SERVICE);
1765        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1766    }
1767
1768    public PackageManagerService(Context context, Installer installer,
1769            boolean factoryTest, boolean onlyCore) {
1770        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1771                SystemClock.uptimeMillis());
1772
1773        if (mSdkVersion <= 0) {
1774            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1775        }
1776
1777        mContext = context;
1778        mFactoryTest = factoryTest;
1779        mOnlyCore = onlyCore;
1780        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1781        mMetrics = new DisplayMetrics();
1782        mSettings = new Settings(mPackages);
1783        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1784                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1785        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1786                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1787        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1788                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1789        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1790                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1791        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1792                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1793        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1794                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1795
1796        // TODO: add a property to control this?
1797        long dexOptLRUThresholdInMinutes;
1798        if (mLazyDexOpt) {
1799            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1800        } else {
1801            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1802        }
1803        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1804
1805        String separateProcesses = SystemProperties.get("debug.separate_processes");
1806        if (separateProcesses != null && separateProcesses.length() > 0) {
1807            if ("*".equals(separateProcesses)) {
1808                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1809                mSeparateProcesses = null;
1810                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1811            } else {
1812                mDefParseFlags = 0;
1813                mSeparateProcesses = separateProcesses.split(",");
1814                Slog.w(TAG, "Running with debug.separate_processes: "
1815                        + separateProcesses);
1816            }
1817        } else {
1818            mDefParseFlags = 0;
1819            mSeparateProcesses = null;
1820        }
1821
1822        mInstaller = installer;
1823        mPackageDexOptimizer = new PackageDexOptimizer(this);
1824        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1825
1826        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1827                FgThread.get().getLooper());
1828
1829        getDefaultDisplayMetrics(context, mMetrics);
1830
1831        SystemConfig systemConfig = SystemConfig.getInstance();
1832        mGlobalGids = systemConfig.getGlobalGids();
1833        mSystemPermissions = systemConfig.getSystemPermissions();
1834        mAvailableFeatures = systemConfig.getAvailableFeatures();
1835
1836        synchronized (mInstallLock) {
1837        // writer
1838        synchronized (mPackages) {
1839            mHandlerThread = new ServiceThread(TAG,
1840                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1841            mHandlerThread.start();
1842            mHandler = new PackageHandler(mHandlerThread.getLooper());
1843            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1844
1845            File dataDir = Environment.getDataDirectory();
1846            mAppDataDir = new File(dataDir, "data");
1847            mAppInstallDir = new File(dataDir, "app");
1848            mAppLib32InstallDir = new File(dataDir, "app-lib");
1849            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1850            mUserAppDataDir = new File(dataDir, "user");
1851            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1852
1853            sUserManager = new UserManagerService(context, this,
1854                    mInstallLock, mPackages);
1855
1856            // Propagate permission configuration in to package manager.
1857            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1858                    = systemConfig.getPermissions();
1859            for (int i=0; i<permConfig.size(); i++) {
1860                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1861                BasePermission bp = mSettings.mPermissions.get(perm.name);
1862                if (bp == null) {
1863                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1864                    mSettings.mPermissions.put(perm.name, bp);
1865                }
1866                if (perm.gids != null) {
1867                    bp.setGids(perm.gids, perm.perUser);
1868                }
1869            }
1870
1871            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1872            for (int i=0; i<libConfig.size(); i++) {
1873                mSharedLibraries.put(libConfig.keyAt(i),
1874                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1875            }
1876
1877            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1878
1879            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1880                    mSdkVersion, mOnlyCore);
1881
1882            String customResolverActivity = Resources.getSystem().getString(
1883                    R.string.config_customResolverActivity);
1884            if (TextUtils.isEmpty(customResolverActivity)) {
1885                customResolverActivity = null;
1886            } else {
1887                mCustomResolverComponentName = ComponentName.unflattenFromString(
1888                        customResolverActivity);
1889            }
1890
1891            long startTime = SystemClock.uptimeMillis();
1892
1893            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1894                    startTime);
1895
1896            // Set flag to monitor and not change apk file paths when
1897            // scanning install directories.
1898            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1899
1900            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1901
1902            /**
1903             * Add everything in the in the boot class path to the
1904             * list of process files because dexopt will have been run
1905             * if necessary during zygote startup.
1906             */
1907            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1908            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1909
1910            if (bootClassPath != null) {
1911                String[] bootClassPathElements = splitString(bootClassPath, ':');
1912                for (String element : bootClassPathElements) {
1913                    alreadyDexOpted.add(element);
1914                }
1915            } else {
1916                Slog.w(TAG, "No BOOTCLASSPATH found!");
1917            }
1918
1919            if (systemServerClassPath != null) {
1920                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1921                for (String element : systemServerClassPathElements) {
1922                    alreadyDexOpted.add(element);
1923                }
1924            } else {
1925                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1926            }
1927
1928            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1929            final String[] dexCodeInstructionSets =
1930                    getDexCodeInstructionSets(
1931                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1932
1933            /**
1934             * Ensure all external libraries have had dexopt run on them.
1935             */
1936            if (mSharedLibraries.size() > 0) {
1937                // NOTE: For now, we're compiling these system "shared libraries"
1938                // (and framework jars) into all available architectures. It's possible
1939                // to compile them only when we come across an app that uses them (there's
1940                // already logic for that in scanPackageLI) but that adds some complexity.
1941                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1942                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1943                        final String lib = libEntry.path;
1944                        if (lib == null) {
1945                            continue;
1946                        }
1947
1948                        try {
1949                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1950                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1951                                alreadyDexOpted.add(lib);
1952                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1953                            }
1954                        } catch (FileNotFoundException e) {
1955                            Slog.w(TAG, "Library not found: " + lib);
1956                        } catch (IOException e) {
1957                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1958                                    + e.getMessage());
1959                        }
1960                    }
1961                }
1962            }
1963
1964            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1965
1966            // Gross hack for now: we know this file doesn't contain any
1967            // code, so don't dexopt it to avoid the resulting log spew.
1968            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1969
1970            // Gross hack for now: we know this file is only part of
1971            // the boot class path for art, so don't dexopt it to
1972            // avoid the resulting log spew.
1973            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1974
1975            /**
1976             * There are a number of commands implemented in Java, which
1977             * we currently need to do the dexopt on so that they can be
1978             * run from a non-root shell.
1979             */
1980            String[] frameworkFiles = frameworkDir.list();
1981            if (frameworkFiles != null) {
1982                // TODO: We could compile these only for the most preferred ABI. We should
1983                // first double check that the dex files for these commands are not referenced
1984                // by other system apps.
1985                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1986                    for (int i=0; i<frameworkFiles.length; i++) {
1987                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1988                        String path = libPath.getPath();
1989                        // Skip the file if we already did it.
1990                        if (alreadyDexOpted.contains(path)) {
1991                            continue;
1992                        }
1993                        // Skip the file if it is not a type we want to dexopt.
1994                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1995                            continue;
1996                        }
1997                        try {
1998                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1999                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2000                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2001                            }
2002                        } catch (FileNotFoundException e) {
2003                            Slog.w(TAG, "Jar not found: " + path);
2004                        } catch (IOException e) {
2005                            Slog.w(TAG, "Exception reading jar: " + path, e);
2006                        }
2007                    }
2008                }
2009            }
2010
2011            // Collect vendor overlay packages.
2012            // (Do this before scanning any apps.)
2013            // For security and version matching reason, only consider
2014            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2015            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2016            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2017                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2018
2019            // Find base frameworks (resource packages without code).
2020            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2021                    | PackageParser.PARSE_IS_SYSTEM_DIR
2022                    | PackageParser.PARSE_IS_PRIVILEGED,
2023                    scanFlags | SCAN_NO_DEX, 0);
2024
2025            // Collected privileged system packages.
2026            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2027            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2028                    | PackageParser.PARSE_IS_SYSTEM_DIR
2029                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2030
2031            // Collect ordinary system packages.
2032            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2033            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2034                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2035
2036            // Collect all vendor packages.
2037            File vendorAppDir = new File("/vendor/app");
2038            try {
2039                vendorAppDir = vendorAppDir.getCanonicalFile();
2040            } catch (IOException e) {
2041                // failed to look up canonical path, continue with original one
2042            }
2043            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2044                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2045
2046            // Collect all OEM packages.
2047            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2048            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2049                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2050
2051            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2052            mInstaller.moveFiles();
2053
2054            // Prune any system packages that no longer exist.
2055            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2056            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2057            if (!mOnlyCore) {
2058                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2059                while (psit.hasNext()) {
2060                    PackageSetting ps = psit.next();
2061
2062                    /*
2063                     * If this is not a system app, it can't be a
2064                     * disable system app.
2065                     */
2066                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2067                        continue;
2068                    }
2069
2070                    /*
2071                     * If the package is scanned, it's not erased.
2072                     */
2073                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2074                    if (scannedPkg != null) {
2075                        /*
2076                         * If the system app is both scanned and in the
2077                         * disabled packages list, then it must have been
2078                         * added via OTA. Remove it from the currently
2079                         * scanned package so the previously user-installed
2080                         * application can be scanned.
2081                         */
2082                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2083                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2084                                    + ps.name + "; removing system app.  Last known codePath="
2085                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2086                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2087                                    + scannedPkg.mVersionCode);
2088                            removePackageLI(ps, true);
2089                            expectingBetter.put(ps.name, ps.codePath);
2090                        }
2091
2092                        continue;
2093                    }
2094
2095                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2096                        psit.remove();
2097                        logCriticalInfo(Log.WARN, "System package " + ps.name
2098                                + " no longer exists; wiping its data");
2099                        removeDataDirsLI(null, ps.name);
2100                    } else {
2101                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2102                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2103                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2104                        }
2105                    }
2106                }
2107            }
2108
2109            //look for any incomplete package installations
2110            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2111            //clean up list
2112            for(int i = 0; i < deletePkgsList.size(); i++) {
2113                //clean up here
2114                cleanupInstallFailedPackage(deletePkgsList.get(i));
2115            }
2116            //delete tmp files
2117            deleteTempPackageFiles();
2118
2119            // Remove any shared userIDs that have no associated packages
2120            mSettings.pruneSharedUsersLPw();
2121
2122            if (!mOnlyCore) {
2123                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2124                        SystemClock.uptimeMillis());
2125                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2126
2127                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2128                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2129
2130                /**
2131                 * Remove disable package settings for any updated system
2132                 * apps that were removed via an OTA. If they're not a
2133                 * previously-updated app, remove them completely.
2134                 * Otherwise, just revoke their system-level permissions.
2135                 */
2136                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2137                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2138                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2139
2140                    String msg;
2141                    if (deletedPkg == null) {
2142                        msg = "Updated system package " + deletedAppName
2143                                + " no longer exists; wiping its data";
2144                        removeDataDirsLI(null, deletedAppName);
2145                    } else {
2146                        msg = "Updated system app + " + deletedAppName
2147                                + " no longer present; removing system privileges for "
2148                                + deletedAppName;
2149
2150                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2151
2152                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2153                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2154                    }
2155                    logCriticalInfo(Log.WARN, msg);
2156                }
2157
2158                /**
2159                 * Make sure all system apps that we expected to appear on
2160                 * the userdata partition actually showed up. If they never
2161                 * appeared, crawl back and revive the system version.
2162                 */
2163                for (int i = 0; i < expectingBetter.size(); i++) {
2164                    final String packageName = expectingBetter.keyAt(i);
2165                    if (!mPackages.containsKey(packageName)) {
2166                        final File scanFile = expectingBetter.valueAt(i);
2167
2168                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2169                                + " but never showed up; reverting to system");
2170
2171                        final int reparseFlags;
2172                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2173                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2174                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2175                                    | PackageParser.PARSE_IS_PRIVILEGED;
2176                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2177                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2178                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2179                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2180                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2181                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2182                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2183                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2184                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2185                        } else {
2186                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2187                            continue;
2188                        }
2189
2190                        mSettings.enableSystemPackageLPw(packageName);
2191
2192                        try {
2193                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2194                        } catch (PackageManagerException e) {
2195                            Slog.e(TAG, "Failed to parse original system package: "
2196                                    + e.getMessage());
2197                        }
2198                    }
2199                }
2200            }
2201
2202            // Now that we know all of the shared libraries, update all clients to have
2203            // the correct library paths.
2204            updateAllSharedLibrariesLPw();
2205
2206            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2207                // NOTE: We ignore potential failures here during a system scan (like
2208                // the rest of the commands above) because there's precious little we
2209                // can do about it. A settings error is reported, though.
2210                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2211                        false /* force dexopt */, false /* defer dexopt */);
2212            }
2213
2214            // Now that we know all the packages we are keeping,
2215            // read and update their last usage times.
2216            mPackageUsage.readLP();
2217
2218            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2219                    SystemClock.uptimeMillis());
2220            Slog.i(TAG, "Time to scan packages: "
2221                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2222                    + " seconds");
2223
2224            // If the platform SDK has changed since the last time we booted,
2225            // we need to re-grant app permission to catch any new ones that
2226            // appear.  This is really a hack, and means that apps can in some
2227            // cases get permissions that the user didn't initially explicitly
2228            // allow...  it would be nice to have some better way to handle
2229            // this situation.
2230            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2231                    != mSdkVersion;
2232            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2233                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2234                    + "; regranting permissions for internal storage");
2235            mSettings.mInternalSdkPlatform = mSdkVersion;
2236
2237            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2238                    | (regrantPermissions
2239                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2240                            : 0));
2241
2242            // If this is the first boot, and it is a normal boot, then
2243            // we need to initialize the default preferred apps.
2244            if (!mRestoredSettings && !onlyCore) {
2245                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2246                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2247                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2248            }
2249
2250            // If this is first boot after an OTA, and a normal boot, then
2251            // we need to clear code cache directories.
2252            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2253            if (mIsUpgrade && !onlyCore) {
2254                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2255                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2256                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2257                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2258                }
2259                mSettings.mFingerprint = Build.FINGERPRINT;
2260            }
2261
2262            checkDefaultBrowser();
2263
2264            // All the changes are done during package scanning.
2265            mSettings.updateInternalDatabaseVersion();
2266
2267            // can downgrade to reader
2268            mSettings.writeLPr();
2269
2270            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2271                    SystemClock.uptimeMillis());
2272
2273            mRequiredVerifierPackage = getRequiredVerifierLPr();
2274            mRequiredInstallerPackage = getRequiredInstallerLPr();
2275
2276            mInstallerService = new PackageInstallerService(context, this);
2277
2278            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2279            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2280                    mIntentFilterVerifierComponent);
2281
2282        } // synchronized (mPackages)
2283        } // synchronized (mInstallLock)
2284
2285        // Now after opening every single application zip, make sure they
2286        // are all flushed.  Not really needed, but keeps things nice and
2287        // tidy.
2288        Runtime.getRuntime().gc();
2289
2290        // Expose private service for system components to use.
2291        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2292    }
2293
2294    @Override
2295    public boolean isFirstBoot() {
2296        return !mRestoredSettings;
2297    }
2298
2299    @Override
2300    public boolean isOnlyCoreApps() {
2301        return mOnlyCore;
2302    }
2303
2304    @Override
2305    public boolean isUpgrade() {
2306        return mIsUpgrade;
2307    }
2308
2309    private String getRequiredVerifierLPr() {
2310        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2311        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2312                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2313
2314        String requiredVerifier = null;
2315
2316        final int N = receivers.size();
2317        for (int i = 0; i < N; i++) {
2318            final ResolveInfo info = receivers.get(i);
2319
2320            if (info.activityInfo == null) {
2321                continue;
2322            }
2323
2324            final String packageName = info.activityInfo.packageName;
2325
2326            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2327                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2328                continue;
2329            }
2330
2331            if (requiredVerifier != null) {
2332                throw new RuntimeException("There can be only one required verifier");
2333            }
2334
2335            requiredVerifier = packageName;
2336        }
2337
2338        return requiredVerifier;
2339    }
2340
2341    private String getRequiredInstallerLPr() {
2342        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2343        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2344        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2345
2346        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2347                PACKAGE_MIME_TYPE, 0, 0);
2348
2349        String requiredInstaller = null;
2350
2351        final int N = installers.size();
2352        for (int i = 0; i < N; i++) {
2353            final ResolveInfo info = installers.get(i);
2354            final String packageName = info.activityInfo.packageName;
2355
2356            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2357                continue;
2358            }
2359
2360            if (requiredInstaller != null) {
2361                throw new RuntimeException("There must be one required installer");
2362            }
2363
2364            requiredInstaller = packageName;
2365        }
2366
2367        if (requiredInstaller == null) {
2368            throw new RuntimeException("There must be one required installer");
2369        }
2370
2371        return requiredInstaller;
2372    }
2373
2374    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2375        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2376        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2377                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2378
2379        ComponentName verifierComponentName = null;
2380
2381        int priority = -1000;
2382        final int N = receivers.size();
2383        for (int i = 0; i < N; i++) {
2384            final ResolveInfo info = receivers.get(i);
2385
2386            if (info.activityInfo == null) {
2387                continue;
2388            }
2389
2390            final String packageName = info.activityInfo.packageName;
2391
2392            final PackageSetting ps = mSettings.mPackages.get(packageName);
2393            if (ps == null) {
2394                continue;
2395            }
2396
2397            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2398                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2399                continue;
2400            }
2401
2402            // Select the IntentFilterVerifier with the highest priority
2403            if (priority < info.priority) {
2404                priority = info.priority;
2405                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2406                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2407                        + verifierComponentName + " with priority: " + info.priority);
2408            }
2409        }
2410
2411        return verifierComponentName;
2412    }
2413
2414    private void primeDomainVerificationsLPw(int userId) {
2415        if (DEBUG_DOMAIN_VERIFICATION) {
2416            Slog.d(TAG, "Priming domain verifications in user " + userId);
2417        }
2418
2419        SystemConfig systemConfig = SystemConfig.getInstance();
2420        ArraySet<String> packages = systemConfig.getLinkedApps();
2421        ArraySet<String> domains = new ArraySet<String>();
2422
2423        for (String packageName : packages) {
2424            PackageParser.Package pkg = mPackages.get(packageName);
2425            if (pkg != null) {
2426                if (!pkg.isSystemApp()) {
2427                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2428                    continue;
2429                }
2430
2431                domains.clear();
2432                for (PackageParser.Activity a : pkg.activities) {
2433                    for (ActivityIntentInfo filter : a.intents) {
2434                        if (hasValidDomains(filter)) {
2435                            domains.addAll(filter.getHostsList());
2436                        }
2437                    }
2438                }
2439
2440                if (domains.size() > 0) {
2441                    if (DEBUG_DOMAIN_VERIFICATION) {
2442                        Slog.v(TAG, "      + " + packageName);
2443                    }
2444                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2445                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2446                    // and then 'always' in the per-user state actually used for intent resolution.
2447                    final IntentFilterVerificationInfo ivi;
2448                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2449                            new ArrayList<String>(domains));
2450                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2451                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2452                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2453                } else {
2454                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2455                            + "' does not handle web links");
2456                }
2457            } else {
2458                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2459            }
2460        }
2461
2462        scheduleWritePackageRestrictionsLocked(userId);
2463        scheduleWriteSettingsLocked();
2464    }
2465
2466    private void applyFactoryDefaultBrowserLPw(int userId) {
2467        // The default browser app's package name is stored in a string resource,
2468        // with a product-specific overlay used for vendor customization.
2469        String browserPkg = mContext.getResources().getString(
2470                com.android.internal.R.string.default_browser);
2471        if (!TextUtils.isEmpty(browserPkg)) {
2472            // non-empty string => required to be a known package
2473            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2474            if (ps == null) {
2475                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2476                browserPkg = null;
2477            } else {
2478                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2479            }
2480        }
2481
2482        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2483        // default.  If there's more than one, just leave everything alone.
2484        if (browserPkg == null) {
2485            calculateDefaultBrowserLPw(userId);
2486        }
2487    }
2488
2489    private void calculateDefaultBrowserLPw(int userId) {
2490        List<String> allBrowsers = resolveAllBrowserApps(userId);
2491        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2492        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2493    }
2494
2495    private List<String> resolveAllBrowserApps(int userId) {
2496        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2497        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2498                PackageManager.MATCH_ALL, userId);
2499
2500        final int count = list.size();
2501        List<String> result = new ArrayList<String>(count);
2502        for (int i=0; i<count; i++) {
2503            ResolveInfo info = list.get(i);
2504            if (info.activityInfo == null
2505                    || !info.handleAllWebDataURI
2506                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2507                    || result.contains(info.activityInfo.packageName)) {
2508                continue;
2509            }
2510            result.add(info.activityInfo.packageName);
2511        }
2512
2513        return result;
2514    }
2515
2516    private boolean packageIsBrowser(String packageName, int userId) {
2517        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2518                PackageManager.MATCH_ALL, userId);
2519        final int N = list.size();
2520        for (int i = 0; i < N; i++) {
2521            ResolveInfo info = list.get(i);
2522            if (packageName.equals(info.activityInfo.packageName)) {
2523                return true;
2524            }
2525        }
2526        return false;
2527    }
2528
2529    private void checkDefaultBrowser() {
2530        final int myUserId = UserHandle.myUserId();
2531        final String packageName = getDefaultBrowserPackageName(myUserId);
2532        if (packageName != null) {
2533            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2534            if (info == null) {
2535                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2536                synchronized (mPackages) {
2537                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2538                }
2539            }
2540        }
2541    }
2542
2543    @Override
2544    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2545            throws RemoteException {
2546        try {
2547            return super.onTransact(code, data, reply, flags);
2548        } catch (RuntimeException e) {
2549            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2550                Slog.wtf(TAG, "Package Manager Crash", e);
2551            }
2552            throw e;
2553        }
2554    }
2555
2556    void cleanupInstallFailedPackage(PackageSetting ps) {
2557        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2558
2559        removeDataDirsLI(ps.volumeUuid, ps.name);
2560        if (ps.codePath != null) {
2561            if (ps.codePath.isDirectory()) {
2562                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2563            } else {
2564                ps.codePath.delete();
2565            }
2566        }
2567        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2568            if (ps.resourcePath.isDirectory()) {
2569                FileUtils.deleteContents(ps.resourcePath);
2570            }
2571            ps.resourcePath.delete();
2572        }
2573        mSettings.removePackageLPw(ps.name);
2574    }
2575
2576    static int[] appendInts(int[] cur, int[] add) {
2577        if (add == null) return cur;
2578        if (cur == null) return add;
2579        final int N = add.length;
2580        for (int i=0; i<N; i++) {
2581            cur = appendInt(cur, add[i]);
2582        }
2583        return cur;
2584    }
2585
2586    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2587        if (!sUserManager.exists(userId)) return null;
2588        final PackageSetting ps = (PackageSetting) p.mExtras;
2589        if (ps == null) {
2590            return null;
2591        }
2592
2593        final PermissionsState permissionsState = ps.getPermissionsState();
2594
2595        final int[] gids = permissionsState.computeGids(userId);
2596        final Set<String> permissions = permissionsState.getPermissions(userId);
2597        final PackageUserState state = ps.readUserState(userId);
2598
2599        return PackageParser.generatePackageInfo(p, gids, flags,
2600                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2601    }
2602
2603    @Override
2604    public boolean isPackageFrozen(String packageName) {
2605        synchronized (mPackages) {
2606            final PackageSetting ps = mSettings.mPackages.get(packageName);
2607            if (ps != null) {
2608                return ps.frozen;
2609            }
2610        }
2611        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2612        return true;
2613    }
2614
2615    @Override
2616    public boolean isPackageAvailable(String packageName, int userId) {
2617        if (!sUserManager.exists(userId)) return false;
2618        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2619        synchronized (mPackages) {
2620            PackageParser.Package p = mPackages.get(packageName);
2621            if (p != null) {
2622                final PackageSetting ps = (PackageSetting) p.mExtras;
2623                if (ps != null) {
2624                    final PackageUserState state = ps.readUserState(userId);
2625                    if (state != null) {
2626                        return PackageParser.isAvailable(state);
2627                    }
2628                }
2629            }
2630        }
2631        return false;
2632    }
2633
2634    @Override
2635    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2636        if (!sUserManager.exists(userId)) return null;
2637        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2638        // reader
2639        synchronized (mPackages) {
2640            PackageParser.Package p = mPackages.get(packageName);
2641            if (DEBUG_PACKAGE_INFO)
2642                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2643            if (p != null) {
2644                return generatePackageInfo(p, flags, userId);
2645            }
2646            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2647                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2648            }
2649        }
2650        return null;
2651    }
2652
2653    @Override
2654    public String[] currentToCanonicalPackageNames(String[] names) {
2655        String[] out = new String[names.length];
2656        // reader
2657        synchronized (mPackages) {
2658            for (int i=names.length-1; i>=0; i--) {
2659                PackageSetting ps = mSettings.mPackages.get(names[i]);
2660                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2661            }
2662        }
2663        return out;
2664    }
2665
2666    @Override
2667    public String[] canonicalToCurrentPackageNames(String[] names) {
2668        String[] out = new String[names.length];
2669        // reader
2670        synchronized (mPackages) {
2671            for (int i=names.length-1; i>=0; i--) {
2672                String cur = mSettings.mRenamedPackages.get(names[i]);
2673                out[i] = cur != null ? cur : names[i];
2674            }
2675        }
2676        return out;
2677    }
2678
2679    @Override
2680    public int getPackageUid(String packageName, int userId) {
2681        if (!sUserManager.exists(userId)) return -1;
2682        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2683
2684        // reader
2685        synchronized (mPackages) {
2686            PackageParser.Package p = mPackages.get(packageName);
2687            if(p != null) {
2688                return UserHandle.getUid(userId, p.applicationInfo.uid);
2689            }
2690            PackageSetting ps = mSettings.mPackages.get(packageName);
2691            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2692                return -1;
2693            }
2694            p = ps.pkg;
2695            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2696        }
2697    }
2698
2699    @Override
2700    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2701        if (!sUserManager.exists(userId)) {
2702            return null;
2703        }
2704
2705        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2706                "getPackageGids");
2707
2708        // reader
2709        synchronized (mPackages) {
2710            PackageParser.Package p = mPackages.get(packageName);
2711            if (DEBUG_PACKAGE_INFO) {
2712                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2713            }
2714            if (p != null) {
2715                PackageSetting ps = (PackageSetting) p.mExtras;
2716                return ps.getPermissionsState().computeGids(userId);
2717            }
2718        }
2719
2720        return null;
2721    }
2722
2723    @Override
2724    public int getMountExternalMode(int uid) {
2725        if (Process.isIsolated(uid)) {
2726            return Zygote.MOUNT_EXTERNAL_NONE;
2727        } else {
2728            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2729                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2730            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2731                return Zygote.MOUNT_EXTERNAL_WRITE;
2732            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2733                return Zygote.MOUNT_EXTERNAL_READ;
2734            } else {
2735                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2736            }
2737        }
2738    }
2739
2740    static PermissionInfo generatePermissionInfo(
2741            BasePermission bp, int flags) {
2742        if (bp.perm != null) {
2743            return PackageParser.generatePermissionInfo(bp.perm, flags);
2744        }
2745        PermissionInfo pi = new PermissionInfo();
2746        pi.name = bp.name;
2747        pi.packageName = bp.sourcePackage;
2748        pi.nonLocalizedLabel = bp.name;
2749        pi.protectionLevel = bp.protectionLevel;
2750        return pi;
2751    }
2752
2753    @Override
2754    public PermissionInfo getPermissionInfo(String name, int flags) {
2755        // reader
2756        synchronized (mPackages) {
2757            final BasePermission p = mSettings.mPermissions.get(name);
2758            if (p != null) {
2759                return generatePermissionInfo(p, flags);
2760            }
2761            return null;
2762        }
2763    }
2764
2765    @Override
2766    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2767        // reader
2768        synchronized (mPackages) {
2769            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2770            for (BasePermission p : mSettings.mPermissions.values()) {
2771                if (group == null) {
2772                    if (p.perm == null || p.perm.info.group == null) {
2773                        out.add(generatePermissionInfo(p, flags));
2774                    }
2775                } else {
2776                    if (p.perm != null && group.equals(p.perm.info.group)) {
2777                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2778                    }
2779                }
2780            }
2781
2782            if (out.size() > 0) {
2783                return out;
2784            }
2785            return mPermissionGroups.containsKey(group) ? out : null;
2786        }
2787    }
2788
2789    @Override
2790    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2791        // reader
2792        synchronized (mPackages) {
2793            return PackageParser.generatePermissionGroupInfo(
2794                    mPermissionGroups.get(name), flags);
2795        }
2796    }
2797
2798    @Override
2799    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2800        // reader
2801        synchronized (mPackages) {
2802            final int N = mPermissionGroups.size();
2803            ArrayList<PermissionGroupInfo> out
2804                    = new ArrayList<PermissionGroupInfo>(N);
2805            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2806                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2807            }
2808            return out;
2809        }
2810    }
2811
2812    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2813            int userId) {
2814        if (!sUserManager.exists(userId)) return null;
2815        PackageSetting ps = mSettings.mPackages.get(packageName);
2816        if (ps != null) {
2817            if (ps.pkg == null) {
2818                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2819                        flags, userId);
2820                if (pInfo != null) {
2821                    return pInfo.applicationInfo;
2822                }
2823                return null;
2824            }
2825            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2826                    ps.readUserState(userId), userId);
2827        }
2828        return null;
2829    }
2830
2831    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2832            int userId) {
2833        if (!sUserManager.exists(userId)) return null;
2834        PackageSetting ps = mSettings.mPackages.get(packageName);
2835        if (ps != null) {
2836            PackageParser.Package pkg = ps.pkg;
2837            if (pkg == null) {
2838                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2839                    return null;
2840                }
2841                // Only data remains, so we aren't worried about code paths
2842                pkg = new PackageParser.Package(packageName);
2843                pkg.applicationInfo.packageName = packageName;
2844                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2845                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2846                pkg.applicationInfo.dataDir = Environment
2847                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2848                        .getAbsolutePath();
2849                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2850                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2851            }
2852            return generatePackageInfo(pkg, flags, userId);
2853        }
2854        return null;
2855    }
2856
2857    @Override
2858    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2859        if (!sUserManager.exists(userId)) return null;
2860        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2861        // writer
2862        synchronized (mPackages) {
2863            PackageParser.Package p = mPackages.get(packageName);
2864            if (DEBUG_PACKAGE_INFO) Log.v(
2865                    TAG, "getApplicationInfo " + packageName
2866                    + ": " + p);
2867            if (p != null) {
2868                PackageSetting ps = mSettings.mPackages.get(packageName);
2869                if (ps == null) return null;
2870                // Note: isEnabledLP() does not apply here - always return info
2871                return PackageParser.generateApplicationInfo(
2872                        p, flags, ps.readUserState(userId), userId);
2873            }
2874            if ("android".equals(packageName)||"system".equals(packageName)) {
2875                return mAndroidApplication;
2876            }
2877            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2878                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2879            }
2880        }
2881        return null;
2882    }
2883
2884    @Override
2885    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2886            final IPackageDataObserver observer) {
2887        mContext.enforceCallingOrSelfPermission(
2888                android.Manifest.permission.CLEAR_APP_CACHE, null);
2889        // Queue up an async operation since clearing cache may take a little while.
2890        mHandler.post(new Runnable() {
2891            public void run() {
2892                mHandler.removeCallbacks(this);
2893                int retCode = -1;
2894                synchronized (mInstallLock) {
2895                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2896                    if (retCode < 0) {
2897                        Slog.w(TAG, "Couldn't clear application caches");
2898                    }
2899                }
2900                if (observer != null) {
2901                    try {
2902                        observer.onRemoveCompleted(null, (retCode >= 0));
2903                    } catch (RemoteException e) {
2904                        Slog.w(TAG, "RemoveException when invoking call back");
2905                    }
2906                }
2907            }
2908        });
2909    }
2910
2911    @Override
2912    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2913            final IntentSender pi) {
2914        mContext.enforceCallingOrSelfPermission(
2915                android.Manifest.permission.CLEAR_APP_CACHE, null);
2916        // Queue up an async operation since clearing cache may take a little while.
2917        mHandler.post(new Runnable() {
2918            public void run() {
2919                mHandler.removeCallbacks(this);
2920                int retCode = -1;
2921                synchronized (mInstallLock) {
2922                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2923                    if (retCode < 0) {
2924                        Slog.w(TAG, "Couldn't clear application caches");
2925                    }
2926                }
2927                if(pi != null) {
2928                    try {
2929                        // Callback via pending intent
2930                        int code = (retCode >= 0) ? 1 : 0;
2931                        pi.sendIntent(null, code, null,
2932                                null, null);
2933                    } catch (SendIntentException e1) {
2934                        Slog.i(TAG, "Failed to send pending intent");
2935                    }
2936                }
2937            }
2938        });
2939    }
2940
2941    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2942        synchronized (mInstallLock) {
2943            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2944                throw new IOException("Failed to free enough space");
2945            }
2946        }
2947    }
2948
2949    @Override
2950    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2951        if (!sUserManager.exists(userId)) return null;
2952        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2953        synchronized (mPackages) {
2954            PackageParser.Activity a = mActivities.mActivities.get(component);
2955
2956            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2957            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2958                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2959                if (ps == null) return null;
2960                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2961                        userId);
2962            }
2963            if (mResolveComponentName.equals(component)) {
2964                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2965                        new PackageUserState(), userId);
2966            }
2967        }
2968        return null;
2969    }
2970
2971    @Override
2972    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2973            String resolvedType) {
2974        synchronized (mPackages) {
2975            PackageParser.Activity a = mActivities.mActivities.get(component);
2976            if (a == null) {
2977                return false;
2978            }
2979            for (int i=0; i<a.intents.size(); i++) {
2980                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2981                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2982                    return true;
2983                }
2984            }
2985            return false;
2986        }
2987    }
2988
2989    @Override
2990    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2991        if (!sUserManager.exists(userId)) return null;
2992        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2993        synchronized (mPackages) {
2994            PackageParser.Activity a = mReceivers.mActivities.get(component);
2995            if (DEBUG_PACKAGE_INFO) Log.v(
2996                TAG, "getReceiverInfo " + 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        }
3004        return null;
3005    }
3006
3007    @Override
3008    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3009        if (!sUserManager.exists(userId)) return null;
3010        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3011        synchronized (mPackages) {
3012            PackageParser.Service s = mServices.mServices.get(component);
3013            if (DEBUG_PACKAGE_INFO) Log.v(
3014                TAG, "getServiceInfo " + component + ": " + s);
3015            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3016                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3017                if (ps == null) return null;
3018                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3019                        userId);
3020            }
3021        }
3022        return null;
3023    }
3024
3025    @Override
3026    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3027        if (!sUserManager.exists(userId)) return null;
3028        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3029        synchronized (mPackages) {
3030            PackageParser.Provider p = mProviders.mProviders.get(component);
3031            if (DEBUG_PACKAGE_INFO) Log.v(
3032                TAG, "getProviderInfo " + component + ": " + p);
3033            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3035                if (ps == null) return null;
3036                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3037                        userId);
3038            }
3039        }
3040        return null;
3041    }
3042
3043    @Override
3044    public String[] getSystemSharedLibraryNames() {
3045        Set<String> libSet;
3046        synchronized (mPackages) {
3047            libSet = mSharedLibraries.keySet();
3048            int size = libSet.size();
3049            if (size > 0) {
3050                String[] libs = new String[size];
3051                libSet.toArray(libs);
3052                return libs;
3053            }
3054        }
3055        return null;
3056    }
3057
3058    /**
3059     * @hide
3060     */
3061    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3062        synchronized (mPackages) {
3063            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3064            if (lib != null && lib.apk != null) {
3065                return mPackages.get(lib.apk);
3066            }
3067        }
3068        return null;
3069    }
3070
3071    @Override
3072    public FeatureInfo[] getSystemAvailableFeatures() {
3073        Collection<FeatureInfo> featSet;
3074        synchronized (mPackages) {
3075            featSet = mAvailableFeatures.values();
3076            int size = featSet.size();
3077            if (size > 0) {
3078                FeatureInfo[] features = new FeatureInfo[size+1];
3079                featSet.toArray(features);
3080                FeatureInfo fi = new FeatureInfo();
3081                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3082                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3083                features[size] = fi;
3084                return features;
3085            }
3086        }
3087        return null;
3088    }
3089
3090    @Override
3091    public boolean hasSystemFeature(String name) {
3092        synchronized (mPackages) {
3093            return mAvailableFeatures.containsKey(name);
3094        }
3095    }
3096
3097    private void checkValidCaller(int uid, int userId) {
3098        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3099            return;
3100
3101        throw new SecurityException("Caller uid=" + uid
3102                + " is not privileged to communicate with user=" + userId);
3103    }
3104
3105    @Override
3106    public int checkPermission(String permName, String pkgName, int userId) {
3107        if (!sUserManager.exists(userId)) {
3108            return PackageManager.PERMISSION_DENIED;
3109        }
3110
3111        synchronized (mPackages) {
3112            final PackageParser.Package p = mPackages.get(pkgName);
3113            if (p != null && p.mExtras != null) {
3114                final PackageSetting ps = (PackageSetting) p.mExtras;
3115                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3116                    return PackageManager.PERMISSION_GRANTED;
3117                }
3118            }
3119        }
3120
3121        return PackageManager.PERMISSION_DENIED;
3122    }
3123
3124    @Override
3125    public int checkUidPermission(String permName, int uid) {
3126        final int userId = UserHandle.getUserId(uid);
3127
3128        if (!sUserManager.exists(userId)) {
3129            return PackageManager.PERMISSION_DENIED;
3130        }
3131
3132        synchronized (mPackages) {
3133            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3134            if (obj != null) {
3135                final SettingBase ps = (SettingBase) obj;
3136                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3137                    return PackageManager.PERMISSION_GRANTED;
3138                }
3139            } else {
3140                ArraySet<String> perms = mSystemPermissions.get(uid);
3141                if (perms != null && perms.contains(permName)) {
3142                    return PackageManager.PERMISSION_GRANTED;
3143                }
3144            }
3145        }
3146
3147        return PackageManager.PERMISSION_DENIED;
3148    }
3149
3150    /**
3151     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3152     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3153     * @param checkShell TODO(yamasani):
3154     * @param message the message to log on security exception
3155     */
3156    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3157            boolean checkShell, String message) {
3158        if (userId < 0) {
3159            throw new IllegalArgumentException("Invalid userId " + userId);
3160        }
3161        if (checkShell) {
3162            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3163        }
3164        if (userId == UserHandle.getUserId(callingUid)) return;
3165        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3166            if (requireFullPermission) {
3167                mContext.enforceCallingOrSelfPermission(
3168                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3169            } else {
3170                try {
3171                    mContext.enforceCallingOrSelfPermission(
3172                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3173                } catch (SecurityException se) {
3174                    mContext.enforceCallingOrSelfPermission(
3175                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3176                }
3177            }
3178        }
3179    }
3180
3181    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3182        if (callingUid == Process.SHELL_UID) {
3183            if (userHandle >= 0
3184                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3185                throw new SecurityException("Shell does not have permission to access user "
3186                        + userHandle);
3187            } else if (userHandle < 0) {
3188                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3189                        + Debug.getCallers(3));
3190            }
3191        }
3192    }
3193
3194    private BasePermission findPermissionTreeLP(String permName) {
3195        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3196            if (permName.startsWith(bp.name) &&
3197                    permName.length() > bp.name.length() &&
3198                    permName.charAt(bp.name.length()) == '.') {
3199                return bp;
3200            }
3201        }
3202        return null;
3203    }
3204
3205    private BasePermission checkPermissionTreeLP(String permName) {
3206        if (permName != null) {
3207            BasePermission bp = findPermissionTreeLP(permName);
3208            if (bp != null) {
3209                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3210                    return bp;
3211                }
3212                throw new SecurityException("Calling uid "
3213                        + Binder.getCallingUid()
3214                        + " is not allowed to add to permission tree "
3215                        + bp.name + " owned by uid " + bp.uid);
3216            }
3217        }
3218        throw new SecurityException("No permission tree found for " + permName);
3219    }
3220
3221    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3222        if (s1 == null) {
3223            return s2 == null;
3224        }
3225        if (s2 == null) {
3226            return false;
3227        }
3228        if (s1.getClass() != s2.getClass()) {
3229            return false;
3230        }
3231        return s1.equals(s2);
3232    }
3233
3234    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3235        if (pi1.icon != pi2.icon) return false;
3236        if (pi1.logo != pi2.logo) return false;
3237        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3238        if (!compareStrings(pi1.name, pi2.name)) return false;
3239        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3240        // We'll take care of setting this one.
3241        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3242        // These are not currently stored in settings.
3243        //if (!compareStrings(pi1.group, pi2.group)) return false;
3244        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3245        //if (pi1.labelRes != pi2.labelRes) return false;
3246        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3247        return true;
3248    }
3249
3250    int permissionInfoFootprint(PermissionInfo info) {
3251        int size = info.name.length();
3252        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3253        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3254        return size;
3255    }
3256
3257    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3258        int size = 0;
3259        for (BasePermission perm : mSettings.mPermissions.values()) {
3260            if (perm.uid == tree.uid) {
3261                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3262            }
3263        }
3264        return size;
3265    }
3266
3267    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3268        // We calculate the max size of permissions defined by this uid and throw
3269        // if that plus the size of 'info' would exceed our stated maximum.
3270        if (tree.uid != Process.SYSTEM_UID) {
3271            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3272            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3273                throw new SecurityException("Permission tree size cap exceeded");
3274            }
3275        }
3276    }
3277
3278    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3279        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3280            throw new SecurityException("Label must be specified in permission");
3281        }
3282        BasePermission tree = checkPermissionTreeLP(info.name);
3283        BasePermission bp = mSettings.mPermissions.get(info.name);
3284        boolean added = bp == null;
3285        boolean changed = true;
3286        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3287        if (added) {
3288            enforcePermissionCapLocked(info, tree);
3289            bp = new BasePermission(info.name, tree.sourcePackage,
3290                    BasePermission.TYPE_DYNAMIC);
3291        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3292            throw new SecurityException(
3293                    "Not allowed to modify non-dynamic permission "
3294                    + info.name);
3295        } else {
3296            if (bp.protectionLevel == fixedLevel
3297                    && bp.perm.owner.equals(tree.perm.owner)
3298                    && bp.uid == tree.uid
3299                    && comparePermissionInfos(bp.perm.info, info)) {
3300                changed = false;
3301            }
3302        }
3303        bp.protectionLevel = fixedLevel;
3304        info = new PermissionInfo(info);
3305        info.protectionLevel = fixedLevel;
3306        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3307        bp.perm.info.packageName = tree.perm.info.packageName;
3308        bp.uid = tree.uid;
3309        if (added) {
3310            mSettings.mPermissions.put(info.name, bp);
3311        }
3312        if (changed) {
3313            if (!async) {
3314                mSettings.writeLPr();
3315            } else {
3316                scheduleWriteSettingsLocked();
3317            }
3318        }
3319        return added;
3320    }
3321
3322    @Override
3323    public boolean addPermission(PermissionInfo info) {
3324        synchronized (mPackages) {
3325            return addPermissionLocked(info, false);
3326        }
3327    }
3328
3329    @Override
3330    public boolean addPermissionAsync(PermissionInfo info) {
3331        synchronized (mPackages) {
3332            return addPermissionLocked(info, true);
3333        }
3334    }
3335
3336    @Override
3337    public void removePermission(String name) {
3338        synchronized (mPackages) {
3339            checkPermissionTreeLP(name);
3340            BasePermission bp = mSettings.mPermissions.get(name);
3341            if (bp != null) {
3342                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3343                    throw new SecurityException(
3344                            "Not allowed to modify non-dynamic permission "
3345                            + name);
3346                }
3347                mSettings.mPermissions.remove(name);
3348                mSettings.writeLPr();
3349            }
3350        }
3351    }
3352
3353    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3354            BasePermission bp) {
3355        int index = pkg.requestedPermissions.indexOf(bp.name);
3356        if (index == -1) {
3357            throw new SecurityException("Package " + pkg.packageName
3358                    + " has not requested permission " + bp.name);
3359        }
3360        if (!bp.isRuntime()) {
3361            throw new SecurityException("Permission " + bp.name
3362                    + " is not a changeable permission type");
3363        }
3364    }
3365
3366    @Override
3367    public void grantRuntimePermission(String packageName, String name, final int userId) {
3368        if (!sUserManager.exists(userId)) {
3369            Log.e(TAG, "No such user:" + userId);
3370            return;
3371        }
3372
3373        mContext.enforceCallingOrSelfPermission(
3374                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3375                "grantRuntimePermission");
3376
3377        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3378                "grantRuntimePermission");
3379
3380        final int uid;
3381        final SettingBase sb;
3382
3383        synchronized (mPackages) {
3384            final PackageParser.Package pkg = mPackages.get(packageName);
3385            if (pkg == null) {
3386                throw new IllegalArgumentException("Unknown package: " + packageName);
3387            }
3388
3389            final BasePermission bp = mSettings.mPermissions.get(name);
3390            if (bp == null) {
3391                throw new IllegalArgumentException("Unknown permission: " + name);
3392            }
3393
3394            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3395
3396            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3397            sb = (SettingBase) pkg.mExtras;
3398            if (sb == null) {
3399                throw new IllegalArgumentException("Unknown package: " + packageName);
3400            }
3401
3402            final PermissionsState permissionsState = sb.getPermissionsState();
3403
3404            final int flags = permissionsState.getPermissionFlags(name, userId);
3405            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3406                throw new SecurityException("Cannot grant system fixed permission: "
3407                        + name + " for package: " + packageName);
3408            }
3409
3410            final int result = permissionsState.grantRuntimePermission(bp, userId);
3411            switch (result) {
3412                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3413                    return;
3414                }
3415
3416                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3417                    mHandler.post(new Runnable() {
3418                        @Override
3419                        public void run() {
3420                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3421                        }
3422                    });
3423                } break;
3424            }
3425
3426            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3427
3428            // Not critical if that is lost - app has to request again.
3429            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3430        }
3431
3432        // Only need to do this if user is initialized. Otherwise it's a new user
3433        // and there are no processes running as the user yet and there's no need
3434        // to make an expensive call to remount processes for the changed permissions.
3435        if ((READ_EXTERNAL_STORAGE.equals(name)
3436                || WRITE_EXTERNAL_STORAGE.equals(name))
3437                && sUserManager.isInitialized(userId)) {
3438            final long token = Binder.clearCallingIdentity();
3439            try {
3440                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3441                storage.remountUid(uid);
3442            } finally {
3443                Binder.restoreCallingIdentity(token);
3444            }
3445        }
3446    }
3447
3448    @Override
3449    public void revokeRuntimePermission(String packageName, String name, int userId) {
3450        if (!sUserManager.exists(userId)) {
3451            Log.e(TAG, "No such user:" + userId);
3452            return;
3453        }
3454
3455        mContext.enforceCallingOrSelfPermission(
3456                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3457                "revokeRuntimePermission");
3458
3459        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3460                "revokeRuntimePermission");
3461
3462        final SettingBase sb;
3463
3464        synchronized (mPackages) {
3465            final PackageParser.Package pkg = mPackages.get(packageName);
3466            if (pkg == null) {
3467                throw new IllegalArgumentException("Unknown package: " + packageName);
3468            }
3469
3470            final BasePermission bp = mSettings.mPermissions.get(name);
3471            if (bp == null) {
3472                throw new IllegalArgumentException("Unknown permission: " + name);
3473            }
3474
3475            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3476
3477            sb = (SettingBase) pkg.mExtras;
3478            if (sb == null) {
3479                throw new IllegalArgumentException("Unknown package: " + packageName);
3480            }
3481
3482            final PermissionsState permissionsState = sb.getPermissionsState();
3483
3484            final int flags = permissionsState.getPermissionFlags(name, userId);
3485            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3486                throw new SecurityException("Cannot revoke system fixed permission: "
3487                        + name + " for package: " + packageName);
3488            }
3489
3490            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3491                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3492                return;
3493            }
3494
3495            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3496
3497            // Critical, after this call app should never have the permission.
3498            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3499        }
3500
3501        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3502    }
3503
3504    @Override
3505    public void resetRuntimePermissions() {
3506        mContext.enforceCallingOrSelfPermission(
3507                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3508                "revokeRuntimePermission");
3509
3510        int callingUid = Binder.getCallingUid();
3511        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3512            mContext.enforceCallingOrSelfPermission(
3513                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3514                    "resetRuntimePermissions");
3515        }
3516
3517        final int[] userIds;
3518
3519        synchronized (mPackages) {
3520            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3521            final int userCount = UserManagerService.getInstance().getUserIds().length;
3522            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3523        }
3524
3525        for (int userId : userIds) {
3526            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3527        }
3528    }
3529
3530    @Override
3531    public int getPermissionFlags(String name, String packageName, int userId) {
3532        if (!sUserManager.exists(userId)) {
3533            return 0;
3534        }
3535
3536        mContext.enforceCallingOrSelfPermission(
3537                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3538                "getPermissionFlags");
3539
3540        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3541                "getPermissionFlags");
3542
3543        synchronized (mPackages) {
3544            final PackageParser.Package pkg = mPackages.get(packageName);
3545            if (pkg == null) {
3546                throw new IllegalArgumentException("Unknown package: " + packageName);
3547            }
3548
3549            final BasePermission bp = mSettings.mPermissions.get(name);
3550            if (bp == null) {
3551                throw new IllegalArgumentException("Unknown permission: " + name);
3552            }
3553
3554            SettingBase sb = (SettingBase) pkg.mExtras;
3555            if (sb == null) {
3556                throw new IllegalArgumentException("Unknown package: " + packageName);
3557            }
3558
3559            PermissionsState permissionsState = sb.getPermissionsState();
3560            return permissionsState.getPermissionFlags(name, userId);
3561        }
3562    }
3563
3564    @Override
3565    public void updatePermissionFlags(String name, String packageName, int flagMask,
3566            int flagValues, int userId) {
3567        if (!sUserManager.exists(userId)) {
3568            return;
3569        }
3570
3571        mContext.enforceCallingOrSelfPermission(
3572                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3573                "updatePermissionFlags");
3574
3575        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3576                "updatePermissionFlags");
3577
3578        // Only the system can change system fixed flags.
3579        if (getCallingUid() != Process.SYSTEM_UID) {
3580            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3581            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3582        }
3583
3584        synchronized (mPackages) {
3585            final PackageParser.Package pkg = mPackages.get(packageName);
3586            if (pkg == null) {
3587                throw new IllegalArgumentException("Unknown package: " + packageName);
3588            }
3589
3590            final BasePermission bp = mSettings.mPermissions.get(name);
3591            if (bp == null) {
3592                throw new IllegalArgumentException("Unknown permission: " + name);
3593            }
3594
3595            SettingBase sb = (SettingBase) pkg.mExtras;
3596            if (sb == null) {
3597                throw new IllegalArgumentException("Unknown package: " + packageName);
3598            }
3599
3600            PermissionsState permissionsState = sb.getPermissionsState();
3601
3602            // Only the package manager can change flags for system component permissions.
3603            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3604            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3605                return;
3606            }
3607
3608            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3609
3610            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3611                // Install and runtime permissions are stored in different places,
3612                // so figure out what permission changed and persist the change.
3613                if (permissionsState.getInstallPermissionState(name) != null) {
3614                    scheduleWriteSettingsLocked();
3615                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3616                        || hadState) {
3617                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3618                }
3619            }
3620        }
3621    }
3622
3623    /**
3624     * Update the permission flags for all packages and runtime permissions of a user in order
3625     * to allow device or profile owner to remove POLICY_FIXED.
3626     */
3627    @Override
3628    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3629        if (!sUserManager.exists(userId)) {
3630            return;
3631        }
3632
3633        mContext.enforceCallingOrSelfPermission(
3634                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3635                "updatePermissionFlagsForAllApps");
3636
3637        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3638                "updatePermissionFlagsForAllApps");
3639
3640        // Only the system can change system fixed flags.
3641        if (getCallingUid() != Process.SYSTEM_UID) {
3642            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3643            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3644        }
3645
3646        synchronized (mPackages) {
3647            boolean changed = false;
3648            final int packageCount = mPackages.size();
3649            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3650                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3651                SettingBase sb = (SettingBase) pkg.mExtras;
3652                if (sb == null) {
3653                    continue;
3654                }
3655                PermissionsState permissionsState = sb.getPermissionsState();
3656                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3657                        userId, flagMask, flagValues);
3658            }
3659            if (changed) {
3660                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3661            }
3662        }
3663    }
3664
3665    @Override
3666    public boolean shouldShowRequestPermissionRationale(String permissionName,
3667            String packageName, int userId) {
3668        if (UserHandle.getCallingUserId() != userId) {
3669            mContext.enforceCallingPermission(
3670                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3671                    "canShowRequestPermissionRationale for user " + userId);
3672        }
3673
3674        final int uid = getPackageUid(packageName, userId);
3675        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3676            return false;
3677        }
3678
3679        if (checkPermission(permissionName, packageName, userId)
3680                == PackageManager.PERMISSION_GRANTED) {
3681            return false;
3682        }
3683
3684        final int flags;
3685
3686        final long identity = Binder.clearCallingIdentity();
3687        try {
3688            flags = getPermissionFlags(permissionName,
3689                    packageName, userId);
3690        } finally {
3691            Binder.restoreCallingIdentity(identity);
3692        }
3693
3694        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3695                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3696                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3697
3698        if ((flags & fixedFlags) != 0) {
3699            return false;
3700        }
3701
3702        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3703    }
3704
3705    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3706        BasePermission bp = mSettings.mPermissions.get(permission);
3707        if (bp == null) {
3708            throw new SecurityException("Missing " + permission + " permission");
3709        }
3710
3711        SettingBase sb = (SettingBase) pkg.mExtras;
3712        PermissionsState permissionsState = sb.getPermissionsState();
3713
3714        if (permissionsState.grantInstallPermission(bp) !=
3715                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3716            scheduleWriteSettingsLocked();
3717        }
3718    }
3719
3720    @Override
3721    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3722        mContext.enforceCallingOrSelfPermission(
3723                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3724                "addOnPermissionsChangeListener");
3725
3726        synchronized (mPackages) {
3727            mOnPermissionChangeListeners.addListenerLocked(listener);
3728        }
3729    }
3730
3731    @Override
3732    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3733        synchronized (mPackages) {
3734            mOnPermissionChangeListeners.removeListenerLocked(listener);
3735        }
3736    }
3737
3738    @Override
3739    public boolean isProtectedBroadcast(String actionName) {
3740        synchronized (mPackages) {
3741            return mProtectedBroadcasts.contains(actionName);
3742        }
3743    }
3744
3745    @Override
3746    public int checkSignatures(String pkg1, String pkg2) {
3747        synchronized (mPackages) {
3748            final PackageParser.Package p1 = mPackages.get(pkg1);
3749            final PackageParser.Package p2 = mPackages.get(pkg2);
3750            if (p1 == null || p1.mExtras == null
3751                    || p2 == null || p2.mExtras == null) {
3752                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3753            }
3754            return compareSignatures(p1.mSignatures, p2.mSignatures);
3755        }
3756    }
3757
3758    @Override
3759    public int checkUidSignatures(int uid1, int uid2) {
3760        // Map to base uids.
3761        uid1 = UserHandle.getAppId(uid1);
3762        uid2 = UserHandle.getAppId(uid2);
3763        // reader
3764        synchronized (mPackages) {
3765            Signature[] s1;
3766            Signature[] s2;
3767            Object obj = mSettings.getUserIdLPr(uid1);
3768            if (obj != null) {
3769                if (obj instanceof SharedUserSetting) {
3770                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3771                } else if (obj instanceof PackageSetting) {
3772                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3773                } else {
3774                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3775                }
3776            } else {
3777                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3778            }
3779            obj = mSettings.getUserIdLPr(uid2);
3780            if (obj != null) {
3781                if (obj instanceof SharedUserSetting) {
3782                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3783                } else if (obj instanceof PackageSetting) {
3784                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3785                } else {
3786                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3787                }
3788            } else {
3789                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3790            }
3791            return compareSignatures(s1, s2);
3792        }
3793    }
3794
3795    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3796        final long identity = Binder.clearCallingIdentity();
3797        try {
3798            if (sb instanceof SharedUserSetting) {
3799                SharedUserSetting sus = (SharedUserSetting) sb;
3800                final int packageCount = sus.packages.size();
3801                for (int i = 0; i < packageCount; i++) {
3802                    PackageSetting susPs = sus.packages.valueAt(i);
3803                    if (userId == UserHandle.USER_ALL) {
3804                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3805                    } else {
3806                        final int uid = UserHandle.getUid(userId, susPs.appId);
3807                        killUid(uid, reason);
3808                    }
3809                }
3810            } else if (sb instanceof PackageSetting) {
3811                PackageSetting ps = (PackageSetting) sb;
3812                if (userId == UserHandle.USER_ALL) {
3813                    killApplication(ps.pkg.packageName, ps.appId, reason);
3814                } else {
3815                    final int uid = UserHandle.getUid(userId, ps.appId);
3816                    killUid(uid, reason);
3817                }
3818            }
3819        } finally {
3820            Binder.restoreCallingIdentity(identity);
3821        }
3822    }
3823
3824    private static void killUid(int uid, String reason) {
3825        IActivityManager am = ActivityManagerNative.getDefault();
3826        if (am != null) {
3827            try {
3828                am.killUid(uid, reason);
3829            } catch (RemoteException e) {
3830                /* ignore - same process */
3831            }
3832        }
3833    }
3834
3835    /**
3836     * Compares two sets of signatures. Returns:
3837     * <br />
3838     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3839     * <br />
3840     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3841     * <br />
3842     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3843     * <br />
3844     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3845     * <br />
3846     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3847     */
3848    static int compareSignatures(Signature[] s1, Signature[] s2) {
3849        if (s1 == null) {
3850            return s2 == null
3851                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3852                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3853        }
3854
3855        if (s2 == null) {
3856            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3857        }
3858
3859        if (s1.length != s2.length) {
3860            return PackageManager.SIGNATURE_NO_MATCH;
3861        }
3862
3863        // Since both signature sets are of size 1, we can compare without HashSets.
3864        if (s1.length == 1) {
3865            return s1[0].equals(s2[0]) ?
3866                    PackageManager.SIGNATURE_MATCH :
3867                    PackageManager.SIGNATURE_NO_MATCH;
3868        }
3869
3870        ArraySet<Signature> set1 = new ArraySet<Signature>();
3871        for (Signature sig : s1) {
3872            set1.add(sig);
3873        }
3874        ArraySet<Signature> set2 = new ArraySet<Signature>();
3875        for (Signature sig : s2) {
3876            set2.add(sig);
3877        }
3878        // Make sure s2 contains all signatures in s1.
3879        if (set1.equals(set2)) {
3880            return PackageManager.SIGNATURE_MATCH;
3881        }
3882        return PackageManager.SIGNATURE_NO_MATCH;
3883    }
3884
3885    /**
3886     * If the database version for this type of package (internal storage or
3887     * external storage) is less than the version where package signatures
3888     * were updated, return true.
3889     */
3890    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3891        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3892                DatabaseVersion.SIGNATURE_END_ENTITY))
3893                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3894                        DatabaseVersion.SIGNATURE_END_ENTITY));
3895    }
3896
3897    /**
3898     * Used for backward compatibility to make sure any packages with
3899     * certificate chains get upgraded to the new style. {@code existingSigs}
3900     * will be in the old format (since they were stored on disk from before the
3901     * system upgrade) and {@code scannedSigs} will be in the newer format.
3902     */
3903    private int compareSignaturesCompat(PackageSignatures existingSigs,
3904            PackageParser.Package scannedPkg) {
3905        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3906            return PackageManager.SIGNATURE_NO_MATCH;
3907        }
3908
3909        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3910        for (Signature sig : existingSigs.mSignatures) {
3911            existingSet.add(sig);
3912        }
3913        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3914        for (Signature sig : scannedPkg.mSignatures) {
3915            try {
3916                Signature[] chainSignatures = sig.getChainSignatures();
3917                for (Signature chainSig : chainSignatures) {
3918                    scannedCompatSet.add(chainSig);
3919                }
3920            } catch (CertificateEncodingException e) {
3921                scannedCompatSet.add(sig);
3922            }
3923        }
3924        /*
3925         * Make sure the expanded scanned set contains all signatures in the
3926         * existing one.
3927         */
3928        if (scannedCompatSet.equals(existingSet)) {
3929            // Migrate the old signatures to the new scheme.
3930            existingSigs.assignSignatures(scannedPkg.mSignatures);
3931            // The new KeySets will be re-added later in the scanning process.
3932            synchronized (mPackages) {
3933                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3934            }
3935            return PackageManager.SIGNATURE_MATCH;
3936        }
3937        return PackageManager.SIGNATURE_NO_MATCH;
3938    }
3939
3940    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3941        if (isExternal(scannedPkg)) {
3942            return mSettings.isExternalDatabaseVersionOlderThan(
3943                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3944        } else {
3945            return mSettings.isInternalDatabaseVersionOlderThan(
3946                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3947        }
3948    }
3949
3950    private int compareSignaturesRecover(PackageSignatures existingSigs,
3951            PackageParser.Package scannedPkg) {
3952        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3953            return PackageManager.SIGNATURE_NO_MATCH;
3954        }
3955
3956        String msg = null;
3957        try {
3958            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3959                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3960                        + scannedPkg.packageName);
3961                return PackageManager.SIGNATURE_MATCH;
3962            }
3963        } catch (CertificateException e) {
3964            msg = e.getMessage();
3965        }
3966
3967        logCriticalInfo(Log.INFO,
3968                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3969        return PackageManager.SIGNATURE_NO_MATCH;
3970    }
3971
3972    @Override
3973    public String[] getPackagesForUid(int uid) {
3974        uid = UserHandle.getAppId(uid);
3975        // reader
3976        synchronized (mPackages) {
3977            Object obj = mSettings.getUserIdLPr(uid);
3978            if (obj instanceof SharedUserSetting) {
3979                final SharedUserSetting sus = (SharedUserSetting) obj;
3980                final int N = sus.packages.size();
3981                final String[] res = new String[N];
3982                final Iterator<PackageSetting> it = sus.packages.iterator();
3983                int i = 0;
3984                while (it.hasNext()) {
3985                    res[i++] = it.next().name;
3986                }
3987                return res;
3988            } else if (obj instanceof PackageSetting) {
3989                final PackageSetting ps = (PackageSetting) obj;
3990                return new String[] { ps.name };
3991            }
3992        }
3993        return null;
3994    }
3995
3996    @Override
3997    public String getNameForUid(int uid) {
3998        // reader
3999        synchronized (mPackages) {
4000            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4001            if (obj instanceof SharedUserSetting) {
4002                final SharedUserSetting sus = (SharedUserSetting) obj;
4003                return sus.name + ":" + sus.userId;
4004            } else if (obj instanceof PackageSetting) {
4005                final PackageSetting ps = (PackageSetting) obj;
4006                return ps.name;
4007            }
4008        }
4009        return null;
4010    }
4011
4012    @Override
4013    public int getUidForSharedUser(String sharedUserName) {
4014        if(sharedUserName == null) {
4015            return -1;
4016        }
4017        // reader
4018        synchronized (mPackages) {
4019            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4020            if (suid == null) {
4021                return -1;
4022            }
4023            return suid.userId;
4024        }
4025    }
4026
4027    @Override
4028    public int getFlagsForUid(int uid) {
4029        synchronized (mPackages) {
4030            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4031            if (obj instanceof SharedUserSetting) {
4032                final SharedUserSetting sus = (SharedUserSetting) obj;
4033                return sus.pkgFlags;
4034            } else if (obj instanceof PackageSetting) {
4035                final PackageSetting ps = (PackageSetting) obj;
4036                return ps.pkgFlags;
4037            }
4038        }
4039        return 0;
4040    }
4041
4042    @Override
4043    public int getPrivateFlagsForUid(int uid) {
4044        synchronized (mPackages) {
4045            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4046            if (obj instanceof SharedUserSetting) {
4047                final SharedUserSetting sus = (SharedUserSetting) obj;
4048                return sus.pkgPrivateFlags;
4049            } else if (obj instanceof PackageSetting) {
4050                final PackageSetting ps = (PackageSetting) obj;
4051                return ps.pkgPrivateFlags;
4052            }
4053        }
4054        return 0;
4055    }
4056
4057    @Override
4058    public boolean isUidPrivileged(int uid) {
4059        uid = UserHandle.getAppId(uid);
4060        // reader
4061        synchronized (mPackages) {
4062            Object obj = mSettings.getUserIdLPr(uid);
4063            if (obj instanceof SharedUserSetting) {
4064                final SharedUserSetting sus = (SharedUserSetting) obj;
4065                final Iterator<PackageSetting> it = sus.packages.iterator();
4066                while (it.hasNext()) {
4067                    if (it.next().isPrivileged()) {
4068                        return true;
4069                    }
4070                }
4071            } else if (obj instanceof PackageSetting) {
4072                final PackageSetting ps = (PackageSetting) obj;
4073                return ps.isPrivileged();
4074            }
4075        }
4076        return false;
4077    }
4078
4079    @Override
4080    public String[] getAppOpPermissionPackages(String permissionName) {
4081        synchronized (mPackages) {
4082            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4083            if (pkgs == null) {
4084                return null;
4085            }
4086            return pkgs.toArray(new String[pkgs.size()]);
4087        }
4088    }
4089
4090    @Override
4091    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4092            int flags, int userId) {
4093        if (!sUserManager.exists(userId)) return null;
4094        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4095        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4096        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4097    }
4098
4099    @Override
4100    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4101            IntentFilter filter, int match, ComponentName activity) {
4102        final int userId = UserHandle.getCallingUserId();
4103        if (DEBUG_PREFERRED) {
4104            Log.v(TAG, "setLastChosenActivity intent=" + intent
4105                + " resolvedType=" + resolvedType
4106                + " flags=" + flags
4107                + " filter=" + filter
4108                + " match=" + match
4109                + " activity=" + activity);
4110            filter.dump(new PrintStreamPrinter(System.out), "    ");
4111        }
4112        intent.setComponent(null);
4113        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4114        // Find any earlier preferred or last chosen entries and nuke them
4115        findPreferredActivity(intent, resolvedType,
4116                flags, query, 0, false, true, false, userId);
4117        // Add the new activity as the last chosen for this filter
4118        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4119                "Setting last chosen");
4120    }
4121
4122    @Override
4123    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4124        final int userId = UserHandle.getCallingUserId();
4125        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4126        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4127        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4128                false, false, false, userId);
4129    }
4130
4131    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4132            int flags, List<ResolveInfo> query, int userId) {
4133        if (query != null) {
4134            final int N = query.size();
4135            if (N == 1) {
4136                return query.get(0);
4137            } else if (N > 1) {
4138                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4139                // If there is more than one activity with the same priority,
4140                // then let the user decide between them.
4141                ResolveInfo r0 = query.get(0);
4142                ResolveInfo r1 = query.get(1);
4143                if (DEBUG_INTENT_MATCHING || debug) {
4144                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4145                            + r1.activityInfo.name + "=" + r1.priority);
4146                }
4147                // If the first activity has a higher priority, or a different
4148                // default, then it is always desireable to pick it.
4149                if (r0.priority != r1.priority
4150                        || r0.preferredOrder != r1.preferredOrder
4151                        || r0.isDefault != r1.isDefault) {
4152                    return query.get(0);
4153                }
4154                // If we have saved a preference for a preferred activity for
4155                // this Intent, use that.
4156                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4157                        flags, query, r0.priority, true, false, debug, userId);
4158                if (ri != null) {
4159                    return ri;
4160                }
4161                if (userId != 0) {
4162                    ri = new ResolveInfo(mResolveInfo);
4163                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4164                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4165                            ri.activityInfo.applicationInfo);
4166                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4167                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4168                    return ri;
4169                }
4170                return mResolveInfo;
4171            }
4172        }
4173        return null;
4174    }
4175
4176    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4177            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4178        final int N = query.size();
4179        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4180                .get(userId);
4181        // Get the list of persistent preferred activities that handle the intent
4182        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4183        List<PersistentPreferredActivity> pprefs = ppir != null
4184                ? ppir.queryIntent(intent, resolvedType,
4185                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4186                : null;
4187        if (pprefs != null && pprefs.size() > 0) {
4188            final int M = pprefs.size();
4189            for (int i=0; i<M; i++) {
4190                final PersistentPreferredActivity ppa = pprefs.get(i);
4191                if (DEBUG_PREFERRED || debug) {
4192                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4193                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4194                            + "\n  component=" + ppa.mComponent);
4195                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4196                }
4197                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4198                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4199                if (DEBUG_PREFERRED || debug) {
4200                    Slog.v(TAG, "Found persistent preferred activity:");
4201                    if (ai != null) {
4202                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4203                    } else {
4204                        Slog.v(TAG, "  null");
4205                    }
4206                }
4207                if (ai == null) {
4208                    // This previously registered persistent preferred activity
4209                    // component is no longer known. Ignore it and do NOT remove it.
4210                    continue;
4211                }
4212                for (int j=0; j<N; j++) {
4213                    final ResolveInfo ri = query.get(j);
4214                    if (!ri.activityInfo.applicationInfo.packageName
4215                            .equals(ai.applicationInfo.packageName)) {
4216                        continue;
4217                    }
4218                    if (!ri.activityInfo.name.equals(ai.name)) {
4219                        continue;
4220                    }
4221                    //  Found a persistent preference that can handle the intent.
4222                    if (DEBUG_PREFERRED || debug) {
4223                        Slog.v(TAG, "Returning persistent preferred activity: " +
4224                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4225                    }
4226                    return ri;
4227                }
4228            }
4229        }
4230        return null;
4231    }
4232
4233    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4234            List<ResolveInfo> query, int priority, boolean always,
4235            boolean removeMatches, boolean debug, int userId) {
4236        if (!sUserManager.exists(userId)) return null;
4237        // writer
4238        synchronized (mPackages) {
4239            if (intent.getSelector() != null) {
4240                intent = intent.getSelector();
4241            }
4242            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4243
4244            // Try to find a matching persistent preferred activity.
4245            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4246                    debug, userId);
4247
4248            // If a persistent preferred activity matched, use it.
4249            if (pri != null) {
4250                return pri;
4251            }
4252
4253            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4254            // Get the list of preferred activities that handle the intent
4255            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4256            List<PreferredActivity> prefs = pir != null
4257                    ? pir.queryIntent(intent, resolvedType,
4258                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4259                    : null;
4260            if (prefs != null && prefs.size() > 0) {
4261                boolean changed = false;
4262                try {
4263                    // First figure out how good the original match set is.
4264                    // We will only allow preferred activities that came
4265                    // from the same match quality.
4266                    int match = 0;
4267
4268                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4269
4270                    final int N = query.size();
4271                    for (int j=0; j<N; j++) {
4272                        final ResolveInfo ri = query.get(j);
4273                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4274                                + ": 0x" + Integer.toHexString(match));
4275                        if (ri.match > match) {
4276                            match = ri.match;
4277                        }
4278                    }
4279
4280                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4281                            + Integer.toHexString(match));
4282
4283                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4284                    final int M = prefs.size();
4285                    for (int i=0; i<M; i++) {
4286                        final PreferredActivity pa = prefs.get(i);
4287                        if (DEBUG_PREFERRED || debug) {
4288                            Slog.v(TAG, "Checking PreferredActivity ds="
4289                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4290                                    + "\n  component=" + pa.mPref.mComponent);
4291                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4292                        }
4293                        if (pa.mPref.mMatch != match) {
4294                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4295                                    + Integer.toHexString(pa.mPref.mMatch));
4296                            continue;
4297                        }
4298                        // If it's not an "always" type preferred activity and that's what we're
4299                        // looking for, skip it.
4300                        if (always && !pa.mPref.mAlways) {
4301                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4302                            continue;
4303                        }
4304                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4305                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4306                        if (DEBUG_PREFERRED || debug) {
4307                            Slog.v(TAG, "Found preferred activity:");
4308                            if (ai != null) {
4309                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4310                            } else {
4311                                Slog.v(TAG, "  null");
4312                            }
4313                        }
4314                        if (ai == null) {
4315                            // This previously registered preferred activity
4316                            // component is no longer known.  Most likely an update
4317                            // to the app was installed and in the new version this
4318                            // component no longer exists.  Clean it up by removing
4319                            // it from the preferred activities list, and skip it.
4320                            Slog.w(TAG, "Removing dangling preferred activity: "
4321                                    + pa.mPref.mComponent);
4322                            pir.removeFilter(pa);
4323                            changed = true;
4324                            continue;
4325                        }
4326                        for (int j=0; j<N; j++) {
4327                            final ResolveInfo ri = query.get(j);
4328                            if (!ri.activityInfo.applicationInfo.packageName
4329                                    .equals(ai.applicationInfo.packageName)) {
4330                                continue;
4331                            }
4332                            if (!ri.activityInfo.name.equals(ai.name)) {
4333                                continue;
4334                            }
4335
4336                            if (removeMatches) {
4337                                pir.removeFilter(pa);
4338                                changed = true;
4339                                if (DEBUG_PREFERRED) {
4340                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4341                                }
4342                                break;
4343                            }
4344
4345                            // Okay we found a previously set preferred or last chosen app.
4346                            // If the result set is different from when this
4347                            // was created, we need to clear it and re-ask the
4348                            // user their preference, if we're looking for an "always" type entry.
4349                            if (always && !pa.mPref.sameSet(query)) {
4350                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4351                                        + intent + " type " + resolvedType);
4352                                if (DEBUG_PREFERRED) {
4353                                    Slog.v(TAG, "Removing preferred activity since set changed "
4354                                            + pa.mPref.mComponent);
4355                                }
4356                                pir.removeFilter(pa);
4357                                // Re-add the filter as a "last chosen" entry (!always)
4358                                PreferredActivity lastChosen = new PreferredActivity(
4359                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4360                                pir.addFilter(lastChosen);
4361                                changed = true;
4362                                return null;
4363                            }
4364
4365                            // Yay! Either the set matched or we're looking for the last chosen
4366                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4367                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4368                            return ri;
4369                        }
4370                    }
4371                } finally {
4372                    if (changed) {
4373                        if (DEBUG_PREFERRED) {
4374                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4375                        }
4376                        scheduleWritePackageRestrictionsLocked(userId);
4377                    }
4378                }
4379            }
4380        }
4381        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4382        return null;
4383    }
4384
4385    /*
4386     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4387     */
4388    @Override
4389    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4390            int targetUserId) {
4391        mContext.enforceCallingOrSelfPermission(
4392                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4393        List<CrossProfileIntentFilter> matches =
4394                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4395        if (matches != null) {
4396            int size = matches.size();
4397            for (int i = 0; i < size; i++) {
4398                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4399            }
4400        }
4401        if (hasWebURI(intent)) {
4402            // cross-profile app linking works only towards the parent.
4403            final UserInfo parent = getProfileParent(sourceUserId);
4404            synchronized(mPackages) {
4405                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4406                        parent.id) != null;
4407            }
4408        }
4409        return false;
4410    }
4411
4412    private UserInfo getProfileParent(int userId) {
4413        final long identity = Binder.clearCallingIdentity();
4414        try {
4415            return sUserManager.getProfileParent(userId);
4416        } finally {
4417            Binder.restoreCallingIdentity(identity);
4418        }
4419    }
4420
4421    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4422            String resolvedType, int userId) {
4423        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4424        if (resolver != null) {
4425            return resolver.queryIntent(intent, resolvedType, false, userId);
4426        }
4427        return null;
4428    }
4429
4430    @Override
4431    public List<ResolveInfo> queryIntentActivities(Intent intent,
4432            String resolvedType, int flags, int userId) {
4433        if (!sUserManager.exists(userId)) return Collections.emptyList();
4434        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4435        ComponentName comp = intent.getComponent();
4436        if (comp == null) {
4437            if (intent.getSelector() != null) {
4438                intent = intent.getSelector();
4439                comp = intent.getComponent();
4440            }
4441        }
4442
4443        if (comp != null) {
4444            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4445            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4446            if (ai != null) {
4447                final ResolveInfo ri = new ResolveInfo();
4448                ri.activityInfo = ai;
4449                list.add(ri);
4450            }
4451            return list;
4452        }
4453
4454        // reader
4455        synchronized (mPackages) {
4456            final String pkgName = intent.getPackage();
4457            if (pkgName == null) {
4458                List<CrossProfileIntentFilter> matchingFilters =
4459                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4460                // Check for results that need to skip the current profile.
4461                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4462                        resolvedType, flags, userId);
4463                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4464                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4465                    result.add(xpResolveInfo);
4466                    return filterIfNotPrimaryUser(result, userId);
4467                }
4468
4469                // Check for results in the current profile.
4470                List<ResolveInfo> result = mActivities.queryIntent(
4471                        intent, resolvedType, flags, userId);
4472
4473                // Check for cross profile results.
4474                xpResolveInfo = queryCrossProfileIntents(
4475                        matchingFilters, intent, resolvedType, flags, userId);
4476                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4477                    result.add(xpResolveInfo);
4478                    Collections.sort(result, mResolvePrioritySorter);
4479                }
4480                result = filterIfNotPrimaryUser(result, userId);
4481                if (hasWebURI(intent)) {
4482                    CrossProfileDomainInfo xpDomainInfo = null;
4483                    final UserInfo parent = getProfileParent(userId);
4484                    if (parent != null) {
4485                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4486                                flags, userId, parent.id);
4487                    }
4488                    if (xpDomainInfo != null) {
4489                        if (xpResolveInfo != null) {
4490                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4491                            // in the result.
4492                            result.remove(xpResolveInfo);
4493                        }
4494                        if (result.size() == 0) {
4495                            result.add(xpDomainInfo.resolveInfo);
4496                            return result;
4497                        }
4498                    } else if (result.size() <= 1) {
4499                        return result;
4500                    }
4501                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4502                            xpDomainInfo);
4503                    Collections.sort(result, mResolvePrioritySorter);
4504                }
4505                return result;
4506            }
4507            final PackageParser.Package pkg = mPackages.get(pkgName);
4508            if (pkg != null) {
4509                return filterIfNotPrimaryUser(
4510                        mActivities.queryIntentForPackage(
4511                                intent, resolvedType, flags, pkg.activities, userId),
4512                        userId);
4513            }
4514            return new ArrayList<ResolveInfo>();
4515        }
4516    }
4517
4518    private static class CrossProfileDomainInfo {
4519        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4520        ResolveInfo resolveInfo;
4521        /* Best domain verification status of the activities found in the other profile */
4522        int bestDomainVerificationStatus;
4523    }
4524
4525    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4526            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4527        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4528                sourceUserId)) {
4529            return null;
4530        }
4531        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4532                resolvedType, flags, parentUserId);
4533
4534        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4535            return null;
4536        }
4537        CrossProfileDomainInfo result = null;
4538        int size = resultTargetUser.size();
4539        for (int i = 0; i < size; i++) {
4540            ResolveInfo riTargetUser = resultTargetUser.get(i);
4541            // Intent filter verification is only for filters that specify a host. So don't return
4542            // those that handle all web uris.
4543            if (riTargetUser.handleAllWebDataURI) {
4544                continue;
4545            }
4546            String packageName = riTargetUser.activityInfo.packageName;
4547            PackageSetting ps = mSettings.mPackages.get(packageName);
4548            if (ps == null) {
4549                continue;
4550            }
4551            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4552            if (result == null) {
4553                result = new CrossProfileDomainInfo();
4554                result.resolveInfo =
4555                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4556                result.bestDomainVerificationStatus = status;
4557            } else {
4558                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4559                        result.bestDomainVerificationStatus);
4560            }
4561        }
4562        return result;
4563    }
4564
4565    /**
4566     * Verification statuses are ordered from the worse to the best, except for
4567     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4568     */
4569    private int bestDomainVerificationStatus(int status1, int status2) {
4570        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4571            return status2;
4572        }
4573        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4574            return status1;
4575        }
4576        return (int) MathUtils.max(status1, status2);
4577    }
4578
4579    private boolean isUserEnabled(int userId) {
4580        long callingId = Binder.clearCallingIdentity();
4581        try {
4582            UserInfo userInfo = sUserManager.getUserInfo(userId);
4583            return userInfo != null && userInfo.isEnabled();
4584        } finally {
4585            Binder.restoreCallingIdentity(callingId);
4586        }
4587    }
4588
4589    /**
4590     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4591     *
4592     * @return filtered list
4593     */
4594    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4595        if (userId == UserHandle.USER_OWNER) {
4596            return resolveInfos;
4597        }
4598        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4599            ResolveInfo info = resolveInfos.get(i);
4600            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4601                resolveInfos.remove(i);
4602            }
4603        }
4604        return resolveInfos;
4605    }
4606
4607    private static boolean hasWebURI(Intent intent) {
4608        if (intent.getData() == null) {
4609            return false;
4610        }
4611        final String scheme = intent.getScheme();
4612        if (TextUtils.isEmpty(scheme)) {
4613            return false;
4614        }
4615        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4616    }
4617
4618    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4619            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4620        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4621            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4622                    candidates.size());
4623        }
4624
4625        final int userId = UserHandle.getCallingUserId();
4626        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4627        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4628        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4629        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4630        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4631
4632        synchronized (mPackages) {
4633            final int count = candidates.size();
4634            // First, try to use linked apps. Partition the candidates into four lists:
4635            // one for the final results, one for the "do not use ever", one for "undefined status"
4636            // and finally one for "browser app type".
4637            for (int n=0; n<count; n++) {
4638                ResolveInfo info = candidates.get(n);
4639                String packageName = info.activityInfo.packageName;
4640                PackageSetting ps = mSettings.mPackages.get(packageName);
4641                if (ps != null) {
4642                    // Add to the special match all list (Browser use case)
4643                    if (info.handleAllWebDataURI) {
4644                        matchAllList.add(info);
4645                        continue;
4646                    }
4647                    // Try to get the status from User settings first
4648                    int status = getDomainVerificationStatusLPr(ps, userId);
4649                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4650                        if (DEBUG_DOMAIN_VERIFICATION) {
4651                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4652                        }
4653                        alwaysList.add(info);
4654                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4655                        if (DEBUG_DOMAIN_VERIFICATION) {
4656                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4657                        }
4658                        neverList.add(info);
4659                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4660                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4661                        if (DEBUG_DOMAIN_VERIFICATION) {
4662                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4663                        }
4664                        undefinedList.add(info);
4665                    }
4666                }
4667            }
4668            // First try to add the "always" resolution for the current user if there is any
4669            if (alwaysList.size() > 0) {
4670                result.addAll(alwaysList);
4671            // if there is an "always" for the parent user, add it.
4672            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4673                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4674                result.add(xpDomainInfo.resolveInfo);
4675            } else {
4676                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4677                result.addAll(undefinedList);
4678                if (xpDomainInfo != null && (
4679                        xpDomainInfo.bestDomainVerificationStatus
4680                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4681                        || xpDomainInfo.bestDomainVerificationStatus
4682                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4683                    result.add(xpDomainInfo.resolveInfo);
4684                }
4685                // Also add Browsers (all of them or only the default one)
4686                if ((flags & MATCH_ALL) != 0) {
4687                    result.addAll(matchAllList);
4688                } else {
4689                    // Try to add the Default Browser if we can
4690                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4691                            UserHandle.myUserId());
4692                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4693                        boolean defaultBrowserFound = false;
4694                        final int browserCount = matchAllList.size();
4695                        for (int n=0; n<browserCount; n++) {
4696                            ResolveInfo browser = matchAllList.get(n);
4697                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4698                                result.add(browser);
4699                                defaultBrowserFound = true;
4700                                break;
4701                            }
4702                        }
4703                        if (!defaultBrowserFound) {
4704                            result.addAll(matchAllList);
4705                        }
4706                    } else {
4707                        result.addAll(matchAllList);
4708                    }
4709                }
4710
4711                // If there is nothing selected, add all candidates and remove the ones that the user
4712                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4713                if (result.size() == 0) {
4714                    result.addAll(candidates);
4715                    result.removeAll(neverList);
4716                }
4717            }
4718        }
4719        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4720            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4721                    result.size());
4722            for (ResolveInfo info : result) {
4723                Slog.v(TAG, "  + " + info.activityInfo);
4724            }
4725        }
4726        return result;
4727    }
4728
4729    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4730        int status = ps.getDomainVerificationStatusForUser(userId);
4731        // if none available, get the master status
4732        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4733            if (ps.getIntentFilterVerificationInfo() != null) {
4734                status = ps.getIntentFilterVerificationInfo().getStatus();
4735            }
4736        }
4737        return status;
4738    }
4739
4740    private ResolveInfo querySkipCurrentProfileIntents(
4741            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4742            int flags, int sourceUserId) {
4743        if (matchingFilters != null) {
4744            int size = matchingFilters.size();
4745            for (int i = 0; i < size; i ++) {
4746                CrossProfileIntentFilter filter = matchingFilters.get(i);
4747                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4748                    // Checking if there are activities in the target user that can handle the
4749                    // intent.
4750                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4751                            flags, sourceUserId);
4752                    if (resolveInfo != null) {
4753                        return resolveInfo;
4754                    }
4755                }
4756            }
4757        }
4758        return null;
4759    }
4760
4761    // Return matching ResolveInfo if any for skip current profile intent filters.
4762    private ResolveInfo queryCrossProfileIntents(
4763            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4764            int flags, int sourceUserId) {
4765        if (matchingFilters != null) {
4766            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4767            // match the same intent. For performance reasons, it is better not to
4768            // run queryIntent twice for the same userId
4769            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4770            int size = matchingFilters.size();
4771            for (int i = 0; i < size; i++) {
4772                CrossProfileIntentFilter filter = matchingFilters.get(i);
4773                int targetUserId = filter.getTargetUserId();
4774                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4775                        && !alreadyTriedUserIds.get(targetUserId)) {
4776                    // Checking if there are activities in the target user that can handle the
4777                    // intent.
4778                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4779                            flags, sourceUserId);
4780                    if (resolveInfo != null) return resolveInfo;
4781                    alreadyTriedUserIds.put(targetUserId, true);
4782                }
4783            }
4784        }
4785        return null;
4786    }
4787
4788    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4789            String resolvedType, int flags, int sourceUserId) {
4790        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4791                resolvedType, flags, filter.getTargetUserId());
4792        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4793            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4794        }
4795        return null;
4796    }
4797
4798    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4799            int sourceUserId, int targetUserId) {
4800        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4801        String className;
4802        if (targetUserId == UserHandle.USER_OWNER) {
4803            className = FORWARD_INTENT_TO_USER_OWNER;
4804        } else {
4805            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4806        }
4807        ComponentName forwardingActivityComponentName = new ComponentName(
4808                mAndroidApplication.packageName, className);
4809        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4810                sourceUserId);
4811        if (targetUserId == UserHandle.USER_OWNER) {
4812            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4813            forwardingResolveInfo.noResourceId = true;
4814        }
4815        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4816        forwardingResolveInfo.priority = 0;
4817        forwardingResolveInfo.preferredOrder = 0;
4818        forwardingResolveInfo.match = 0;
4819        forwardingResolveInfo.isDefault = true;
4820        forwardingResolveInfo.filter = filter;
4821        forwardingResolveInfo.targetUserId = targetUserId;
4822        return forwardingResolveInfo;
4823    }
4824
4825    @Override
4826    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4827            Intent[] specifics, String[] specificTypes, Intent intent,
4828            String resolvedType, int flags, int userId) {
4829        if (!sUserManager.exists(userId)) return Collections.emptyList();
4830        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4831                false, "query intent activity options");
4832        final String resultsAction = intent.getAction();
4833
4834        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4835                | PackageManager.GET_RESOLVED_FILTER, userId);
4836
4837        if (DEBUG_INTENT_MATCHING) {
4838            Log.v(TAG, "Query " + intent + ": " + results);
4839        }
4840
4841        int specificsPos = 0;
4842        int N;
4843
4844        // todo: note that the algorithm used here is O(N^2).  This
4845        // isn't a problem in our current environment, but if we start running
4846        // into situations where we have more than 5 or 10 matches then this
4847        // should probably be changed to something smarter...
4848
4849        // First we go through and resolve each of the specific items
4850        // that were supplied, taking care of removing any corresponding
4851        // duplicate items in the generic resolve list.
4852        if (specifics != null) {
4853            for (int i=0; i<specifics.length; i++) {
4854                final Intent sintent = specifics[i];
4855                if (sintent == null) {
4856                    continue;
4857                }
4858
4859                if (DEBUG_INTENT_MATCHING) {
4860                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4861                }
4862
4863                String action = sintent.getAction();
4864                if (resultsAction != null && resultsAction.equals(action)) {
4865                    // If this action was explicitly requested, then don't
4866                    // remove things that have it.
4867                    action = null;
4868                }
4869
4870                ResolveInfo ri = null;
4871                ActivityInfo ai = null;
4872
4873                ComponentName comp = sintent.getComponent();
4874                if (comp == null) {
4875                    ri = resolveIntent(
4876                        sintent,
4877                        specificTypes != null ? specificTypes[i] : null,
4878                            flags, userId);
4879                    if (ri == null) {
4880                        continue;
4881                    }
4882                    if (ri == mResolveInfo) {
4883                        // ACK!  Must do something better with this.
4884                    }
4885                    ai = ri.activityInfo;
4886                    comp = new ComponentName(ai.applicationInfo.packageName,
4887                            ai.name);
4888                } else {
4889                    ai = getActivityInfo(comp, flags, userId);
4890                    if (ai == null) {
4891                        continue;
4892                    }
4893                }
4894
4895                // Look for any generic query activities that are duplicates
4896                // of this specific one, and remove them from the results.
4897                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4898                N = results.size();
4899                int j;
4900                for (j=specificsPos; j<N; j++) {
4901                    ResolveInfo sri = results.get(j);
4902                    if ((sri.activityInfo.name.equals(comp.getClassName())
4903                            && sri.activityInfo.applicationInfo.packageName.equals(
4904                                    comp.getPackageName()))
4905                        || (action != null && sri.filter.matchAction(action))) {
4906                        results.remove(j);
4907                        if (DEBUG_INTENT_MATCHING) Log.v(
4908                            TAG, "Removing duplicate item from " + j
4909                            + " due to specific " + specificsPos);
4910                        if (ri == null) {
4911                            ri = sri;
4912                        }
4913                        j--;
4914                        N--;
4915                    }
4916                }
4917
4918                // Add this specific item to its proper place.
4919                if (ri == null) {
4920                    ri = new ResolveInfo();
4921                    ri.activityInfo = ai;
4922                }
4923                results.add(specificsPos, ri);
4924                ri.specificIndex = i;
4925                specificsPos++;
4926            }
4927        }
4928
4929        // Now we go through the remaining generic results and remove any
4930        // duplicate actions that are found here.
4931        N = results.size();
4932        for (int i=specificsPos; i<N-1; i++) {
4933            final ResolveInfo rii = results.get(i);
4934            if (rii.filter == null) {
4935                continue;
4936            }
4937
4938            // Iterate over all of the actions of this result's intent
4939            // filter...  typically this should be just one.
4940            final Iterator<String> it = rii.filter.actionsIterator();
4941            if (it == null) {
4942                continue;
4943            }
4944            while (it.hasNext()) {
4945                final String action = it.next();
4946                if (resultsAction != null && resultsAction.equals(action)) {
4947                    // If this action was explicitly requested, then don't
4948                    // remove things that have it.
4949                    continue;
4950                }
4951                for (int j=i+1; j<N; j++) {
4952                    final ResolveInfo rij = results.get(j);
4953                    if (rij.filter != null && rij.filter.hasAction(action)) {
4954                        results.remove(j);
4955                        if (DEBUG_INTENT_MATCHING) Log.v(
4956                            TAG, "Removing duplicate item from " + j
4957                            + " due to action " + action + " at " + i);
4958                        j--;
4959                        N--;
4960                    }
4961                }
4962            }
4963
4964            // If the caller didn't request filter information, drop it now
4965            // so we don't have to marshall/unmarshall it.
4966            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4967                rii.filter = null;
4968            }
4969        }
4970
4971        // Filter out the caller activity if so requested.
4972        if (caller != null) {
4973            N = results.size();
4974            for (int i=0; i<N; i++) {
4975                ActivityInfo ainfo = results.get(i).activityInfo;
4976                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4977                        && caller.getClassName().equals(ainfo.name)) {
4978                    results.remove(i);
4979                    break;
4980                }
4981            }
4982        }
4983
4984        // If the caller didn't request filter information,
4985        // drop them now so we don't have to
4986        // marshall/unmarshall it.
4987        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4988            N = results.size();
4989            for (int i=0; i<N; i++) {
4990                results.get(i).filter = null;
4991            }
4992        }
4993
4994        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4995        return results;
4996    }
4997
4998    @Override
4999    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5000            int userId) {
5001        if (!sUserManager.exists(userId)) return Collections.emptyList();
5002        ComponentName comp = intent.getComponent();
5003        if (comp == null) {
5004            if (intent.getSelector() != null) {
5005                intent = intent.getSelector();
5006                comp = intent.getComponent();
5007            }
5008        }
5009        if (comp != null) {
5010            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5011            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5012            if (ai != null) {
5013                ResolveInfo ri = new ResolveInfo();
5014                ri.activityInfo = ai;
5015                list.add(ri);
5016            }
5017            return list;
5018        }
5019
5020        // reader
5021        synchronized (mPackages) {
5022            String pkgName = intent.getPackage();
5023            if (pkgName == null) {
5024                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5025            }
5026            final PackageParser.Package pkg = mPackages.get(pkgName);
5027            if (pkg != null) {
5028                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5029                        userId);
5030            }
5031            return null;
5032        }
5033    }
5034
5035    @Override
5036    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5037        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5038        if (!sUserManager.exists(userId)) return null;
5039        if (query != null) {
5040            if (query.size() >= 1) {
5041                // If there is more than one service with the same priority,
5042                // just arbitrarily pick the first one.
5043                return query.get(0);
5044            }
5045        }
5046        return null;
5047    }
5048
5049    @Override
5050    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5051            int userId) {
5052        if (!sUserManager.exists(userId)) return Collections.emptyList();
5053        ComponentName comp = intent.getComponent();
5054        if (comp == null) {
5055            if (intent.getSelector() != null) {
5056                intent = intent.getSelector();
5057                comp = intent.getComponent();
5058            }
5059        }
5060        if (comp != null) {
5061            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5062            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5063            if (si != null) {
5064                final ResolveInfo ri = new ResolveInfo();
5065                ri.serviceInfo = si;
5066                list.add(ri);
5067            }
5068            return list;
5069        }
5070
5071        // reader
5072        synchronized (mPackages) {
5073            String pkgName = intent.getPackage();
5074            if (pkgName == null) {
5075                return mServices.queryIntent(intent, resolvedType, flags, userId);
5076            }
5077            final PackageParser.Package pkg = mPackages.get(pkgName);
5078            if (pkg != null) {
5079                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5080                        userId);
5081            }
5082            return null;
5083        }
5084    }
5085
5086    @Override
5087    public List<ResolveInfo> queryIntentContentProviders(
5088            Intent intent, String resolvedType, int flags, int userId) {
5089        if (!sUserManager.exists(userId)) return Collections.emptyList();
5090        ComponentName comp = intent.getComponent();
5091        if (comp == null) {
5092            if (intent.getSelector() != null) {
5093                intent = intent.getSelector();
5094                comp = intent.getComponent();
5095            }
5096        }
5097        if (comp != null) {
5098            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5099            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5100            if (pi != null) {
5101                final ResolveInfo ri = new ResolveInfo();
5102                ri.providerInfo = pi;
5103                list.add(ri);
5104            }
5105            return list;
5106        }
5107
5108        // reader
5109        synchronized (mPackages) {
5110            String pkgName = intent.getPackage();
5111            if (pkgName == null) {
5112                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5113            }
5114            final PackageParser.Package pkg = mPackages.get(pkgName);
5115            if (pkg != null) {
5116                return mProviders.queryIntentForPackage(
5117                        intent, resolvedType, flags, pkg.providers, userId);
5118            }
5119            return null;
5120        }
5121    }
5122
5123    @Override
5124    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5125        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5126
5127        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5128
5129        // writer
5130        synchronized (mPackages) {
5131            ArrayList<PackageInfo> list;
5132            if (listUninstalled) {
5133                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5134                for (PackageSetting ps : mSettings.mPackages.values()) {
5135                    PackageInfo pi;
5136                    if (ps.pkg != null) {
5137                        pi = generatePackageInfo(ps.pkg, flags, userId);
5138                    } else {
5139                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5140                    }
5141                    if (pi != null) {
5142                        list.add(pi);
5143                    }
5144                }
5145            } else {
5146                list = new ArrayList<PackageInfo>(mPackages.size());
5147                for (PackageParser.Package p : mPackages.values()) {
5148                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5149                    if (pi != null) {
5150                        list.add(pi);
5151                    }
5152                }
5153            }
5154
5155            return new ParceledListSlice<PackageInfo>(list);
5156        }
5157    }
5158
5159    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5160            String[] permissions, boolean[] tmp, int flags, int userId) {
5161        int numMatch = 0;
5162        final PermissionsState permissionsState = ps.getPermissionsState();
5163        for (int i=0; i<permissions.length; i++) {
5164            final String permission = permissions[i];
5165            if (permissionsState.hasPermission(permission, userId)) {
5166                tmp[i] = true;
5167                numMatch++;
5168            } else {
5169                tmp[i] = false;
5170            }
5171        }
5172        if (numMatch == 0) {
5173            return;
5174        }
5175        PackageInfo pi;
5176        if (ps.pkg != null) {
5177            pi = generatePackageInfo(ps.pkg, flags, userId);
5178        } else {
5179            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5180        }
5181        // The above might return null in cases of uninstalled apps or install-state
5182        // skew across users/profiles.
5183        if (pi != null) {
5184            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5185                if (numMatch == permissions.length) {
5186                    pi.requestedPermissions = permissions;
5187                } else {
5188                    pi.requestedPermissions = new String[numMatch];
5189                    numMatch = 0;
5190                    for (int i=0; i<permissions.length; i++) {
5191                        if (tmp[i]) {
5192                            pi.requestedPermissions[numMatch] = permissions[i];
5193                            numMatch++;
5194                        }
5195                    }
5196                }
5197            }
5198            list.add(pi);
5199        }
5200    }
5201
5202    @Override
5203    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5204            String[] permissions, int flags, int userId) {
5205        if (!sUserManager.exists(userId)) return null;
5206        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5207
5208        // writer
5209        synchronized (mPackages) {
5210            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5211            boolean[] tmpBools = new boolean[permissions.length];
5212            if (listUninstalled) {
5213                for (PackageSetting ps : mSettings.mPackages.values()) {
5214                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5215                }
5216            } else {
5217                for (PackageParser.Package pkg : mPackages.values()) {
5218                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5219                    if (ps != null) {
5220                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5221                                userId);
5222                    }
5223                }
5224            }
5225
5226            return new ParceledListSlice<PackageInfo>(list);
5227        }
5228    }
5229
5230    @Override
5231    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5232        if (!sUserManager.exists(userId)) return null;
5233        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5234
5235        // writer
5236        synchronized (mPackages) {
5237            ArrayList<ApplicationInfo> list;
5238            if (listUninstalled) {
5239                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5240                for (PackageSetting ps : mSettings.mPackages.values()) {
5241                    ApplicationInfo ai;
5242                    if (ps.pkg != null) {
5243                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5244                                ps.readUserState(userId), userId);
5245                    } else {
5246                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5247                    }
5248                    if (ai != null) {
5249                        list.add(ai);
5250                    }
5251                }
5252            } else {
5253                list = new ArrayList<ApplicationInfo>(mPackages.size());
5254                for (PackageParser.Package p : mPackages.values()) {
5255                    if (p.mExtras != null) {
5256                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5257                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5258                        if (ai != null) {
5259                            list.add(ai);
5260                        }
5261                    }
5262                }
5263            }
5264
5265            return new ParceledListSlice<ApplicationInfo>(list);
5266        }
5267    }
5268
5269    public List<ApplicationInfo> getPersistentApplications(int flags) {
5270        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5271
5272        // reader
5273        synchronized (mPackages) {
5274            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5275            final int userId = UserHandle.getCallingUserId();
5276            while (i.hasNext()) {
5277                final PackageParser.Package p = i.next();
5278                if (p.applicationInfo != null
5279                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5280                        && (!mSafeMode || isSystemApp(p))) {
5281                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5282                    if (ps != null) {
5283                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5284                                ps.readUserState(userId), userId);
5285                        if (ai != null) {
5286                            finalList.add(ai);
5287                        }
5288                    }
5289                }
5290            }
5291        }
5292
5293        return finalList;
5294    }
5295
5296    @Override
5297    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5298        if (!sUserManager.exists(userId)) return null;
5299        // reader
5300        synchronized (mPackages) {
5301            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5302            PackageSetting ps = provider != null
5303                    ? mSettings.mPackages.get(provider.owner.packageName)
5304                    : null;
5305            return ps != null
5306                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5307                    && (!mSafeMode || (provider.info.applicationInfo.flags
5308                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5309                    ? PackageParser.generateProviderInfo(provider, flags,
5310                            ps.readUserState(userId), userId)
5311                    : null;
5312        }
5313    }
5314
5315    /**
5316     * @deprecated
5317     */
5318    @Deprecated
5319    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5320        // reader
5321        synchronized (mPackages) {
5322            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5323                    .entrySet().iterator();
5324            final int userId = UserHandle.getCallingUserId();
5325            while (i.hasNext()) {
5326                Map.Entry<String, PackageParser.Provider> entry = i.next();
5327                PackageParser.Provider p = entry.getValue();
5328                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5329
5330                if (ps != null && p.syncable
5331                        && (!mSafeMode || (p.info.applicationInfo.flags
5332                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5333                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5334                            ps.readUserState(userId), userId);
5335                    if (info != null) {
5336                        outNames.add(entry.getKey());
5337                        outInfo.add(info);
5338                    }
5339                }
5340            }
5341        }
5342    }
5343
5344    @Override
5345    public List<ProviderInfo> queryContentProviders(String processName,
5346            int uid, int flags) {
5347        ArrayList<ProviderInfo> finalList = null;
5348        // reader
5349        synchronized (mPackages) {
5350            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5351            final int userId = processName != null ?
5352                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5353            while (i.hasNext()) {
5354                final PackageParser.Provider p = i.next();
5355                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5356                if (ps != null && p.info.authority != null
5357                        && (processName == null
5358                                || (p.info.processName.equals(processName)
5359                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5360                        && mSettings.isEnabledLPr(p.info, flags, userId)
5361                        && (!mSafeMode
5362                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5363                    if (finalList == null) {
5364                        finalList = new ArrayList<ProviderInfo>(3);
5365                    }
5366                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5367                            ps.readUserState(userId), userId);
5368                    if (info != null) {
5369                        finalList.add(info);
5370                    }
5371                }
5372            }
5373        }
5374
5375        if (finalList != null) {
5376            Collections.sort(finalList, mProviderInitOrderSorter);
5377        }
5378
5379        return finalList;
5380    }
5381
5382    @Override
5383    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5384            int flags) {
5385        // reader
5386        synchronized (mPackages) {
5387            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5388            return PackageParser.generateInstrumentationInfo(i, flags);
5389        }
5390    }
5391
5392    @Override
5393    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5394            int flags) {
5395        ArrayList<InstrumentationInfo> finalList =
5396            new ArrayList<InstrumentationInfo>();
5397
5398        // reader
5399        synchronized (mPackages) {
5400            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5401            while (i.hasNext()) {
5402                final PackageParser.Instrumentation p = i.next();
5403                if (targetPackage == null
5404                        || targetPackage.equals(p.info.targetPackage)) {
5405                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5406                            flags);
5407                    if (ii != null) {
5408                        finalList.add(ii);
5409                    }
5410                }
5411            }
5412        }
5413
5414        return finalList;
5415    }
5416
5417    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5418        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5419        if (overlays == null) {
5420            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5421            return;
5422        }
5423        for (PackageParser.Package opkg : overlays.values()) {
5424            // Not much to do if idmap fails: we already logged the error
5425            // and we certainly don't want to abort installation of pkg simply
5426            // because an overlay didn't fit properly. For these reasons,
5427            // ignore the return value of createIdmapForPackagePairLI.
5428            createIdmapForPackagePairLI(pkg, opkg);
5429        }
5430    }
5431
5432    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5433            PackageParser.Package opkg) {
5434        if (!opkg.mTrustedOverlay) {
5435            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5436                    opkg.baseCodePath + ": overlay not trusted");
5437            return false;
5438        }
5439        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5440        if (overlaySet == null) {
5441            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5442                    opkg.baseCodePath + " but target package has no known overlays");
5443            return false;
5444        }
5445        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5446        // TODO: generate idmap for split APKs
5447        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5448            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5449                    + opkg.baseCodePath);
5450            return false;
5451        }
5452        PackageParser.Package[] overlayArray =
5453            overlaySet.values().toArray(new PackageParser.Package[0]);
5454        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5455            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5456                return p1.mOverlayPriority - p2.mOverlayPriority;
5457            }
5458        };
5459        Arrays.sort(overlayArray, cmp);
5460
5461        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5462        int i = 0;
5463        for (PackageParser.Package p : overlayArray) {
5464            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5465        }
5466        return true;
5467    }
5468
5469    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5470        final File[] files = dir.listFiles();
5471        if (ArrayUtils.isEmpty(files)) {
5472            Log.d(TAG, "No files in app dir " + dir);
5473            return;
5474        }
5475
5476        if (DEBUG_PACKAGE_SCANNING) {
5477            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5478                    + " flags=0x" + Integer.toHexString(parseFlags));
5479        }
5480
5481        for (File file : files) {
5482            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5483                    && !PackageInstallerService.isStageName(file.getName());
5484            if (!isPackage) {
5485                // Ignore entries which are not packages
5486                continue;
5487            }
5488            try {
5489                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5490                        scanFlags, currentTime, null);
5491            } catch (PackageManagerException e) {
5492                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5493
5494                // Delete invalid userdata apps
5495                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5496                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5497                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5498                    if (file.isDirectory()) {
5499                        mInstaller.rmPackageDir(file.getAbsolutePath());
5500                    } else {
5501                        file.delete();
5502                    }
5503                }
5504            }
5505        }
5506    }
5507
5508    private static File getSettingsProblemFile() {
5509        File dataDir = Environment.getDataDirectory();
5510        File systemDir = new File(dataDir, "system");
5511        File fname = new File(systemDir, "uiderrors.txt");
5512        return fname;
5513    }
5514
5515    static void reportSettingsProblem(int priority, String msg) {
5516        logCriticalInfo(priority, msg);
5517    }
5518
5519    static void logCriticalInfo(int priority, String msg) {
5520        Slog.println(priority, TAG, msg);
5521        EventLogTags.writePmCriticalInfo(msg);
5522        try {
5523            File fname = getSettingsProblemFile();
5524            FileOutputStream out = new FileOutputStream(fname, true);
5525            PrintWriter pw = new FastPrintWriter(out);
5526            SimpleDateFormat formatter = new SimpleDateFormat();
5527            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5528            pw.println(dateString + ": " + msg);
5529            pw.close();
5530            FileUtils.setPermissions(
5531                    fname.toString(),
5532                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5533                    -1, -1);
5534        } catch (java.io.IOException e) {
5535        }
5536    }
5537
5538    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5539            PackageParser.Package pkg, File srcFile, int parseFlags)
5540            throws PackageManagerException {
5541        if (ps != null
5542                && ps.codePath.equals(srcFile)
5543                && ps.timeStamp == srcFile.lastModified()
5544                && !isCompatSignatureUpdateNeeded(pkg)
5545                && !isRecoverSignatureUpdateNeeded(pkg)) {
5546            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5547            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5548            ArraySet<PublicKey> signingKs;
5549            synchronized (mPackages) {
5550                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5551            }
5552            if (ps.signatures.mSignatures != null
5553                    && ps.signatures.mSignatures.length != 0
5554                    && signingKs != null) {
5555                // Optimization: reuse the existing cached certificates
5556                // if the package appears to be unchanged.
5557                pkg.mSignatures = ps.signatures.mSignatures;
5558                pkg.mSigningKeys = signingKs;
5559                return;
5560            }
5561
5562            Slog.w(TAG, "PackageSetting for " + ps.name
5563                    + " is missing signatures.  Collecting certs again to recover them.");
5564        } else {
5565            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5566        }
5567
5568        try {
5569            pp.collectCertificates(pkg, parseFlags);
5570            pp.collectManifestDigest(pkg);
5571        } catch (PackageParserException e) {
5572            throw PackageManagerException.from(e);
5573        }
5574    }
5575
5576    /*
5577     *  Scan a package and return the newly parsed package.
5578     *  Returns null in case of errors and the error code is stored in mLastScanError
5579     */
5580    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5581            long currentTime, UserHandle user) throws PackageManagerException {
5582        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5583        parseFlags |= mDefParseFlags;
5584        PackageParser pp = new PackageParser();
5585        pp.setSeparateProcesses(mSeparateProcesses);
5586        pp.setOnlyCoreApps(mOnlyCore);
5587        pp.setDisplayMetrics(mMetrics);
5588
5589        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5590            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5591        }
5592
5593        final PackageParser.Package pkg;
5594        try {
5595            pkg = pp.parsePackage(scanFile, parseFlags);
5596        } catch (PackageParserException e) {
5597            throw PackageManagerException.from(e);
5598        }
5599
5600        PackageSetting ps = null;
5601        PackageSetting updatedPkg;
5602        // reader
5603        synchronized (mPackages) {
5604            // Look to see if we already know about this package.
5605            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5606            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5607                // This package has been renamed to its original name.  Let's
5608                // use that.
5609                ps = mSettings.peekPackageLPr(oldName);
5610            }
5611            // If there was no original package, see one for the real package name.
5612            if (ps == null) {
5613                ps = mSettings.peekPackageLPr(pkg.packageName);
5614            }
5615            // Check to see if this package could be hiding/updating a system
5616            // package.  Must look for it either under the original or real
5617            // package name depending on our state.
5618            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5619            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5620        }
5621        boolean updatedPkgBetter = false;
5622        // First check if this is a system package that may involve an update
5623        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5624            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5625            // it needs to drop FLAG_PRIVILEGED.
5626            if (locationIsPrivileged(scanFile)) {
5627                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5628            } else {
5629                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5630            }
5631
5632            if (ps != null && !ps.codePath.equals(scanFile)) {
5633                // The path has changed from what was last scanned...  check the
5634                // version of the new path against what we have stored to determine
5635                // what to do.
5636                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5637                if (pkg.mVersionCode <= ps.versionCode) {
5638                    // The system package has been updated and the code path does not match
5639                    // Ignore entry. Skip it.
5640                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5641                            + " ignored: updated version " + ps.versionCode
5642                            + " better than this " + pkg.mVersionCode);
5643                    if (!updatedPkg.codePath.equals(scanFile)) {
5644                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5645                                + ps.name + " changing from " + updatedPkg.codePathString
5646                                + " to " + scanFile);
5647                        updatedPkg.codePath = scanFile;
5648                        updatedPkg.codePathString = scanFile.toString();
5649                        updatedPkg.resourcePath = scanFile;
5650                        updatedPkg.resourcePathString = scanFile.toString();
5651                    }
5652                    updatedPkg.pkg = pkg;
5653                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5654                } else {
5655                    // The current app on the system partition is better than
5656                    // what we have updated to on the data partition; switch
5657                    // back to the system partition version.
5658                    // At this point, its safely assumed that package installation for
5659                    // apps in system partition will go through. If not there won't be a working
5660                    // version of the app
5661                    // writer
5662                    synchronized (mPackages) {
5663                        // Just remove the loaded entries from package lists.
5664                        mPackages.remove(ps.name);
5665                    }
5666
5667                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5668                            + " reverting from " + ps.codePathString
5669                            + ": new version " + pkg.mVersionCode
5670                            + " better than installed " + ps.versionCode);
5671
5672                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5673                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5674                    synchronized (mInstallLock) {
5675                        args.cleanUpResourcesLI();
5676                    }
5677                    synchronized (mPackages) {
5678                        mSettings.enableSystemPackageLPw(ps.name);
5679                    }
5680                    updatedPkgBetter = true;
5681                }
5682            }
5683        }
5684
5685        if (updatedPkg != null) {
5686            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5687            // initially
5688            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5689
5690            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5691            // flag set initially
5692            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5693                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5694            }
5695        }
5696
5697        // Verify certificates against what was last scanned
5698        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5699
5700        /*
5701         * A new system app appeared, but we already had a non-system one of the
5702         * same name installed earlier.
5703         */
5704        boolean shouldHideSystemApp = false;
5705        if (updatedPkg == null && ps != null
5706                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5707            /*
5708             * Check to make sure the signatures match first. If they don't,
5709             * wipe the installed application and its data.
5710             */
5711            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5712                    != PackageManager.SIGNATURE_MATCH) {
5713                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5714                        + " signatures don't match existing userdata copy; removing");
5715                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5716                ps = null;
5717            } else {
5718                /*
5719                 * If the newly-added system app is an older version than the
5720                 * already installed version, hide it. It will be scanned later
5721                 * and re-added like an update.
5722                 */
5723                if (pkg.mVersionCode <= ps.versionCode) {
5724                    shouldHideSystemApp = true;
5725                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5726                            + " but new version " + pkg.mVersionCode + " better than installed "
5727                            + ps.versionCode + "; hiding system");
5728                } else {
5729                    /*
5730                     * The newly found system app is a newer version that the
5731                     * one previously installed. Simply remove the
5732                     * already-installed application and replace it with our own
5733                     * while keeping the application data.
5734                     */
5735                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5736                            + " reverting from " + ps.codePathString + ": new version "
5737                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5738                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5739                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5740                    synchronized (mInstallLock) {
5741                        args.cleanUpResourcesLI();
5742                    }
5743                }
5744            }
5745        }
5746
5747        // The apk is forward locked (not public) if its code and resources
5748        // are kept in different files. (except for app in either system or
5749        // vendor path).
5750        // TODO grab this value from PackageSettings
5751        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5752            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5753                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5754            }
5755        }
5756
5757        // TODO: extend to support forward-locked splits
5758        String resourcePath = null;
5759        String baseResourcePath = null;
5760        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5761            if (ps != null && ps.resourcePathString != null) {
5762                resourcePath = ps.resourcePathString;
5763                baseResourcePath = ps.resourcePathString;
5764            } else {
5765                // Should not happen at all. Just log an error.
5766                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5767            }
5768        } else {
5769            resourcePath = pkg.codePath;
5770            baseResourcePath = pkg.baseCodePath;
5771        }
5772
5773        // Set application objects path explicitly.
5774        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5775        pkg.applicationInfo.setCodePath(pkg.codePath);
5776        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5777        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5778        pkg.applicationInfo.setResourcePath(resourcePath);
5779        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5780        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5781
5782        // Note that we invoke the following method only if we are about to unpack an application
5783        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5784                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5785
5786        /*
5787         * If the system app should be overridden by a previously installed
5788         * data, hide the system app now and let the /data/app scan pick it up
5789         * again.
5790         */
5791        if (shouldHideSystemApp) {
5792            synchronized (mPackages) {
5793                /*
5794                 * We have to grant systems permissions before we hide, because
5795                 * grantPermissions will assume the package update is trying to
5796                 * expand its permissions.
5797                 */
5798                grantPermissionsLPw(pkg, true, pkg.packageName);
5799                mSettings.disableSystemPackageLPw(pkg.packageName);
5800            }
5801        }
5802
5803        return scannedPkg;
5804    }
5805
5806    private static String fixProcessName(String defProcessName,
5807            String processName, int uid) {
5808        if (processName == null) {
5809            return defProcessName;
5810        }
5811        return processName;
5812    }
5813
5814    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5815            throws PackageManagerException {
5816        if (pkgSetting.signatures.mSignatures != null) {
5817            // Already existing package. Make sure signatures match
5818            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5819                    == PackageManager.SIGNATURE_MATCH;
5820            if (!match) {
5821                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5822                        == PackageManager.SIGNATURE_MATCH;
5823            }
5824            if (!match) {
5825                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5826                        == PackageManager.SIGNATURE_MATCH;
5827            }
5828            if (!match) {
5829                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5830                        + pkg.packageName + " signatures do not match the "
5831                        + "previously installed version; ignoring!");
5832            }
5833        }
5834
5835        // Check for shared user signatures
5836        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5837            // Already existing package. Make sure signatures match
5838            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5839                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5840            if (!match) {
5841                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5842                        == PackageManager.SIGNATURE_MATCH;
5843            }
5844            if (!match) {
5845                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5846                        == PackageManager.SIGNATURE_MATCH;
5847            }
5848            if (!match) {
5849                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5850                        "Package " + pkg.packageName
5851                        + " has no signatures that match those in shared user "
5852                        + pkgSetting.sharedUser.name + "; ignoring!");
5853            }
5854        }
5855    }
5856
5857    /**
5858     * Enforces that only the system UID or root's UID can call a method exposed
5859     * via Binder.
5860     *
5861     * @param message used as message if SecurityException is thrown
5862     * @throws SecurityException if the caller is not system or root
5863     */
5864    private static final void enforceSystemOrRoot(String message) {
5865        final int uid = Binder.getCallingUid();
5866        if (uid != Process.SYSTEM_UID && uid != 0) {
5867            throw new SecurityException(message);
5868        }
5869    }
5870
5871    @Override
5872    public void performBootDexOpt() {
5873        enforceSystemOrRoot("Only the system can request dexopt be performed");
5874
5875        // Before everything else, see whether we need to fstrim.
5876        try {
5877            IMountService ms = PackageHelper.getMountService();
5878            if (ms != null) {
5879                final boolean isUpgrade = isUpgrade();
5880                boolean doTrim = isUpgrade;
5881                if (doTrim) {
5882                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5883                } else {
5884                    final long interval = android.provider.Settings.Global.getLong(
5885                            mContext.getContentResolver(),
5886                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5887                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5888                    if (interval > 0) {
5889                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5890                        if (timeSinceLast > interval) {
5891                            doTrim = true;
5892                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5893                                    + "; running immediately");
5894                        }
5895                    }
5896                }
5897                if (doTrim) {
5898                    if (!isFirstBoot()) {
5899                        try {
5900                            ActivityManagerNative.getDefault().showBootMessage(
5901                                    mContext.getResources().getString(
5902                                            R.string.android_upgrading_fstrim), true);
5903                        } catch (RemoteException e) {
5904                        }
5905                    }
5906                    ms.runMaintenance();
5907                }
5908            } else {
5909                Slog.e(TAG, "Mount service unavailable!");
5910            }
5911        } catch (RemoteException e) {
5912            // Can't happen; MountService is local
5913        }
5914
5915        final ArraySet<PackageParser.Package> pkgs;
5916        synchronized (mPackages) {
5917            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5918        }
5919
5920        if (pkgs != null) {
5921            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5922            // in case the device runs out of space.
5923            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5924            // Give priority to core apps.
5925            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5926                PackageParser.Package pkg = it.next();
5927                if (pkg.coreApp) {
5928                    if (DEBUG_DEXOPT) {
5929                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5930                    }
5931                    sortedPkgs.add(pkg);
5932                    it.remove();
5933                }
5934            }
5935            // Give priority to system apps that listen for pre boot complete.
5936            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5937            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5938            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5939                PackageParser.Package pkg = it.next();
5940                if (pkgNames.contains(pkg.packageName)) {
5941                    if (DEBUG_DEXOPT) {
5942                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5943                    }
5944                    sortedPkgs.add(pkg);
5945                    it.remove();
5946                }
5947            }
5948            // Give priority to system apps.
5949            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5950                PackageParser.Package pkg = it.next();
5951                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5952                    if (DEBUG_DEXOPT) {
5953                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5954                    }
5955                    sortedPkgs.add(pkg);
5956                    it.remove();
5957                }
5958            }
5959            // Give priority to updated system apps.
5960            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5961                PackageParser.Package pkg = it.next();
5962                if (pkg.isUpdatedSystemApp()) {
5963                    if (DEBUG_DEXOPT) {
5964                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5965                    }
5966                    sortedPkgs.add(pkg);
5967                    it.remove();
5968                }
5969            }
5970            // Give priority to apps that listen for boot complete.
5971            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5972            pkgNames = getPackageNamesForIntent(intent);
5973            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5974                PackageParser.Package pkg = it.next();
5975                if (pkgNames.contains(pkg.packageName)) {
5976                    if (DEBUG_DEXOPT) {
5977                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5978                    }
5979                    sortedPkgs.add(pkg);
5980                    it.remove();
5981                }
5982            }
5983            // Filter out packages that aren't recently used.
5984            filterRecentlyUsedApps(pkgs);
5985            // Add all remaining apps.
5986            for (PackageParser.Package pkg : pkgs) {
5987                if (DEBUG_DEXOPT) {
5988                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5989                }
5990                sortedPkgs.add(pkg);
5991            }
5992
5993            // If we want to be lazy, filter everything that wasn't recently used.
5994            if (mLazyDexOpt) {
5995                filterRecentlyUsedApps(sortedPkgs);
5996            }
5997
5998            int i = 0;
5999            int total = sortedPkgs.size();
6000            File dataDir = Environment.getDataDirectory();
6001            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6002            if (lowThreshold == 0) {
6003                throw new IllegalStateException("Invalid low memory threshold");
6004            }
6005            for (PackageParser.Package pkg : sortedPkgs) {
6006                long usableSpace = dataDir.getUsableSpace();
6007                if (usableSpace < lowThreshold) {
6008                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6009                    break;
6010                }
6011                performBootDexOpt(pkg, ++i, total);
6012            }
6013        }
6014    }
6015
6016    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6017        // Filter out packages that aren't recently used.
6018        //
6019        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6020        // should do a full dexopt.
6021        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6022            int total = pkgs.size();
6023            int skipped = 0;
6024            long now = System.currentTimeMillis();
6025            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6026                PackageParser.Package pkg = i.next();
6027                long then = pkg.mLastPackageUsageTimeInMills;
6028                if (then + mDexOptLRUThresholdInMills < now) {
6029                    if (DEBUG_DEXOPT) {
6030                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6031                              ((then == 0) ? "never" : new Date(then)));
6032                    }
6033                    i.remove();
6034                    skipped++;
6035                }
6036            }
6037            if (DEBUG_DEXOPT) {
6038                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6039            }
6040        }
6041    }
6042
6043    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6044        List<ResolveInfo> ris = null;
6045        try {
6046            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6047                    intent, null, 0, UserHandle.USER_OWNER);
6048        } catch (RemoteException e) {
6049        }
6050        ArraySet<String> pkgNames = new ArraySet<String>();
6051        if (ris != null) {
6052            for (ResolveInfo ri : ris) {
6053                pkgNames.add(ri.activityInfo.packageName);
6054            }
6055        }
6056        return pkgNames;
6057    }
6058
6059    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6060        if (DEBUG_DEXOPT) {
6061            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6062        }
6063        if (!isFirstBoot()) {
6064            try {
6065                ActivityManagerNative.getDefault().showBootMessage(
6066                        mContext.getResources().getString(R.string.android_upgrading_apk,
6067                                curr, total), true);
6068            } catch (RemoteException e) {
6069            }
6070        }
6071        PackageParser.Package p = pkg;
6072        synchronized (mInstallLock) {
6073            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6074                    false /* force dex */, false /* defer */, true /* include dependencies */);
6075        }
6076    }
6077
6078    @Override
6079    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6080        return performDexOpt(packageName, instructionSet, false);
6081    }
6082
6083    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6084        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6085        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6086        if (!dexopt && !updateUsage) {
6087            // We aren't going to dexopt or update usage, so bail early.
6088            return false;
6089        }
6090        PackageParser.Package p;
6091        final String targetInstructionSet;
6092        synchronized (mPackages) {
6093            p = mPackages.get(packageName);
6094            if (p == null) {
6095                return false;
6096            }
6097            if (updateUsage) {
6098                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6099            }
6100            mPackageUsage.write(false);
6101            if (!dexopt) {
6102                // We aren't going to dexopt, so bail early.
6103                return false;
6104            }
6105
6106            targetInstructionSet = instructionSet != null ? instructionSet :
6107                    getPrimaryInstructionSet(p.applicationInfo);
6108            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6109                return false;
6110            }
6111        }
6112
6113        synchronized (mInstallLock) {
6114            final String[] instructionSets = new String[] { targetInstructionSet };
6115            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6116                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6117            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6118        }
6119    }
6120
6121    public ArraySet<String> getPackagesThatNeedDexOpt() {
6122        ArraySet<String> pkgs = null;
6123        synchronized (mPackages) {
6124            for (PackageParser.Package p : mPackages.values()) {
6125                if (DEBUG_DEXOPT) {
6126                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6127                }
6128                if (!p.mDexOptPerformed.isEmpty()) {
6129                    continue;
6130                }
6131                if (pkgs == null) {
6132                    pkgs = new ArraySet<String>();
6133                }
6134                pkgs.add(p.packageName);
6135            }
6136        }
6137        return pkgs;
6138    }
6139
6140    public void shutdown() {
6141        mPackageUsage.write(true);
6142    }
6143
6144    @Override
6145    public void forceDexOpt(String packageName) {
6146        enforceSystemOrRoot("forceDexOpt");
6147
6148        PackageParser.Package pkg;
6149        synchronized (mPackages) {
6150            pkg = mPackages.get(packageName);
6151            if (pkg == null) {
6152                throw new IllegalArgumentException("Missing package: " + packageName);
6153            }
6154        }
6155
6156        synchronized (mInstallLock) {
6157            final String[] instructionSets = new String[] {
6158                    getPrimaryInstructionSet(pkg.applicationInfo) };
6159            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6160                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6161            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6162                throw new IllegalStateException("Failed to dexopt: " + res);
6163            }
6164        }
6165    }
6166
6167    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6168        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6169            Slog.w(TAG, "Unable to update from " + oldPkg.name
6170                    + " to " + newPkg.packageName
6171                    + ": old package not in system partition");
6172            return false;
6173        } else if (mPackages.get(oldPkg.name) != null) {
6174            Slog.w(TAG, "Unable to update from " + oldPkg.name
6175                    + " to " + newPkg.packageName
6176                    + ": old package still exists");
6177            return false;
6178        }
6179        return true;
6180    }
6181
6182    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6183        int[] users = sUserManager.getUserIds();
6184        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6185        if (res < 0) {
6186            return res;
6187        }
6188        for (int user : users) {
6189            if (user != 0) {
6190                res = mInstaller.createUserData(volumeUuid, packageName,
6191                        UserHandle.getUid(user, uid), user, seinfo);
6192                if (res < 0) {
6193                    return res;
6194                }
6195            }
6196        }
6197        return res;
6198    }
6199
6200    private int removeDataDirsLI(String volumeUuid, String packageName) {
6201        int[] users = sUserManager.getUserIds();
6202        int res = 0;
6203        for (int user : users) {
6204            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6205            if (resInner < 0) {
6206                res = resInner;
6207            }
6208        }
6209
6210        return res;
6211    }
6212
6213    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6214        int[] users = sUserManager.getUserIds();
6215        int res = 0;
6216        for (int user : users) {
6217            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6218            if (resInner < 0) {
6219                res = resInner;
6220            }
6221        }
6222        return res;
6223    }
6224
6225    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6226            PackageParser.Package changingLib) {
6227        if (file.path != null) {
6228            usesLibraryFiles.add(file.path);
6229            return;
6230        }
6231        PackageParser.Package p = mPackages.get(file.apk);
6232        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6233            // If we are doing this while in the middle of updating a library apk,
6234            // then we need to make sure to use that new apk for determining the
6235            // dependencies here.  (We haven't yet finished committing the new apk
6236            // to the package manager state.)
6237            if (p == null || p.packageName.equals(changingLib.packageName)) {
6238                p = changingLib;
6239            }
6240        }
6241        if (p != null) {
6242            usesLibraryFiles.addAll(p.getAllCodePaths());
6243        }
6244    }
6245
6246    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6247            PackageParser.Package changingLib) throws PackageManagerException {
6248        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6249            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6250            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6251            for (int i=0; i<N; i++) {
6252                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6253                if (file == null) {
6254                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6255                            "Package " + pkg.packageName + " requires unavailable shared library "
6256                            + pkg.usesLibraries.get(i) + "; failing!");
6257                }
6258                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6259            }
6260            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6261            for (int i=0; i<N; i++) {
6262                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6263                if (file == null) {
6264                    Slog.w(TAG, "Package " + pkg.packageName
6265                            + " desires unavailable shared library "
6266                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6267                } else {
6268                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6269                }
6270            }
6271            N = usesLibraryFiles.size();
6272            if (N > 0) {
6273                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6274            } else {
6275                pkg.usesLibraryFiles = null;
6276            }
6277        }
6278    }
6279
6280    private static boolean hasString(List<String> list, List<String> which) {
6281        if (list == null) {
6282            return false;
6283        }
6284        for (int i=list.size()-1; i>=0; i--) {
6285            for (int j=which.size()-1; j>=0; j--) {
6286                if (which.get(j).equals(list.get(i))) {
6287                    return true;
6288                }
6289            }
6290        }
6291        return false;
6292    }
6293
6294    private void updateAllSharedLibrariesLPw() {
6295        for (PackageParser.Package pkg : mPackages.values()) {
6296            try {
6297                updateSharedLibrariesLPw(pkg, null);
6298            } catch (PackageManagerException e) {
6299                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6300            }
6301        }
6302    }
6303
6304    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6305            PackageParser.Package changingPkg) {
6306        ArrayList<PackageParser.Package> res = null;
6307        for (PackageParser.Package pkg : mPackages.values()) {
6308            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6309                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6310                if (res == null) {
6311                    res = new ArrayList<PackageParser.Package>();
6312                }
6313                res.add(pkg);
6314                try {
6315                    updateSharedLibrariesLPw(pkg, changingPkg);
6316                } catch (PackageManagerException e) {
6317                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6318                }
6319            }
6320        }
6321        return res;
6322    }
6323
6324    /**
6325     * Derive the value of the {@code cpuAbiOverride} based on the provided
6326     * value and an optional stored value from the package settings.
6327     */
6328    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6329        String cpuAbiOverride = null;
6330
6331        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6332            cpuAbiOverride = null;
6333        } else if (abiOverride != null) {
6334            cpuAbiOverride = abiOverride;
6335        } else if (settings != null) {
6336            cpuAbiOverride = settings.cpuAbiOverrideString;
6337        }
6338
6339        return cpuAbiOverride;
6340    }
6341
6342    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6343            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6344        boolean success = false;
6345        try {
6346            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6347                    currentTime, user);
6348            success = true;
6349            return res;
6350        } finally {
6351            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6352                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6353            }
6354        }
6355    }
6356
6357    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6358            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6359        final File scanFile = new File(pkg.codePath);
6360        if (pkg.applicationInfo.getCodePath() == null ||
6361                pkg.applicationInfo.getResourcePath() == null) {
6362            // Bail out. The resource and code paths haven't been set.
6363            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6364                    "Code and resource paths haven't been set correctly");
6365        }
6366
6367        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6368            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6369        } else {
6370            // Only allow system apps to be flagged as core apps.
6371            pkg.coreApp = false;
6372        }
6373
6374        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6375            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6376        }
6377
6378        if (mCustomResolverComponentName != null &&
6379                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6380            setUpCustomResolverActivity(pkg);
6381        }
6382
6383        if (pkg.packageName.equals("android")) {
6384            synchronized (mPackages) {
6385                if (mAndroidApplication != null) {
6386                    Slog.w(TAG, "*************************************************");
6387                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6388                    Slog.w(TAG, " file=" + scanFile);
6389                    Slog.w(TAG, "*************************************************");
6390                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6391                            "Core android package being redefined.  Skipping.");
6392                }
6393
6394                // Set up information for our fall-back user intent resolution activity.
6395                mPlatformPackage = pkg;
6396                pkg.mVersionCode = mSdkVersion;
6397                mAndroidApplication = pkg.applicationInfo;
6398
6399                if (!mResolverReplaced) {
6400                    mResolveActivity.applicationInfo = mAndroidApplication;
6401                    mResolveActivity.name = ResolverActivity.class.getName();
6402                    mResolveActivity.packageName = mAndroidApplication.packageName;
6403                    mResolveActivity.processName = "system:ui";
6404                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6405                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6406                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6407                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6408                    mResolveActivity.exported = true;
6409                    mResolveActivity.enabled = true;
6410                    mResolveInfo.activityInfo = mResolveActivity;
6411                    mResolveInfo.priority = 0;
6412                    mResolveInfo.preferredOrder = 0;
6413                    mResolveInfo.match = 0;
6414                    mResolveComponentName = new ComponentName(
6415                            mAndroidApplication.packageName, mResolveActivity.name);
6416                }
6417            }
6418        }
6419
6420        if (DEBUG_PACKAGE_SCANNING) {
6421            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6422                Log.d(TAG, "Scanning package " + pkg.packageName);
6423        }
6424
6425        if (mPackages.containsKey(pkg.packageName)
6426                || mSharedLibraries.containsKey(pkg.packageName)) {
6427            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6428                    "Application package " + pkg.packageName
6429                    + " already installed.  Skipping duplicate.");
6430        }
6431
6432        // If we're only installing presumed-existing packages, require that the
6433        // scanned APK is both already known and at the path previously established
6434        // for it.  Previously unknown packages we pick up normally, but if we have an
6435        // a priori expectation about this package's install presence, enforce it.
6436        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6437            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6438            if (known != null) {
6439                if (DEBUG_PACKAGE_SCANNING) {
6440                    Log.d(TAG, "Examining " + pkg.codePath
6441                            + " and requiring known paths " + known.codePathString
6442                            + " & " + known.resourcePathString);
6443                }
6444                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6445                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6446                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6447                            "Application package " + pkg.packageName
6448                            + " found at " + pkg.applicationInfo.getCodePath()
6449                            + " but expected at " + known.codePathString + "; ignoring.");
6450                }
6451            }
6452        }
6453
6454        // Initialize package source and resource directories
6455        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6456        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6457
6458        SharedUserSetting suid = null;
6459        PackageSetting pkgSetting = null;
6460
6461        if (!isSystemApp(pkg)) {
6462            // Only system apps can use these features.
6463            pkg.mOriginalPackages = null;
6464            pkg.mRealPackage = null;
6465            pkg.mAdoptPermissions = null;
6466        }
6467
6468        // writer
6469        synchronized (mPackages) {
6470            if (pkg.mSharedUserId != null) {
6471                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6472                if (suid == null) {
6473                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6474                            "Creating application package " + pkg.packageName
6475                            + " for shared user failed");
6476                }
6477                if (DEBUG_PACKAGE_SCANNING) {
6478                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6479                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6480                                + "): packages=" + suid.packages);
6481                }
6482            }
6483
6484            // Check if we are renaming from an original package name.
6485            PackageSetting origPackage = null;
6486            String realName = null;
6487            if (pkg.mOriginalPackages != null) {
6488                // This package may need to be renamed to a previously
6489                // installed name.  Let's check on that...
6490                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6491                if (pkg.mOriginalPackages.contains(renamed)) {
6492                    // This package had originally been installed as the
6493                    // original name, and we have already taken care of
6494                    // transitioning to the new one.  Just update the new
6495                    // one to continue using the old name.
6496                    realName = pkg.mRealPackage;
6497                    if (!pkg.packageName.equals(renamed)) {
6498                        // Callers into this function may have already taken
6499                        // care of renaming the package; only do it here if
6500                        // it is not already done.
6501                        pkg.setPackageName(renamed);
6502                    }
6503
6504                } else {
6505                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6506                        if ((origPackage = mSettings.peekPackageLPr(
6507                                pkg.mOriginalPackages.get(i))) != null) {
6508                            // We do have the package already installed under its
6509                            // original name...  should we use it?
6510                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6511                                // New package is not compatible with original.
6512                                origPackage = null;
6513                                continue;
6514                            } else if (origPackage.sharedUser != null) {
6515                                // Make sure uid is compatible between packages.
6516                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6517                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6518                                            + " to " + pkg.packageName + ": old uid "
6519                                            + origPackage.sharedUser.name
6520                                            + " differs from " + pkg.mSharedUserId);
6521                                    origPackage = null;
6522                                    continue;
6523                                }
6524                            } else {
6525                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6526                                        + pkg.packageName + " to old name " + origPackage.name);
6527                            }
6528                            break;
6529                        }
6530                    }
6531                }
6532            }
6533
6534            if (mTransferedPackages.contains(pkg.packageName)) {
6535                Slog.w(TAG, "Package " + pkg.packageName
6536                        + " was transferred to another, but its .apk remains");
6537            }
6538
6539            // Just create the setting, don't add it yet. For already existing packages
6540            // the PkgSetting exists already and doesn't have to be created.
6541            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6542                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6543                    pkg.applicationInfo.primaryCpuAbi,
6544                    pkg.applicationInfo.secondaryCpuAbi,
6545                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6546                    user, false);
6547            if (pkgSetting == null) {
6548                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6549                        "Creating application package " + pkg.packageName + " failed");
6550            }
6551
6552            if (pkgSetting.origPackage != null) {
6553                // If we are first transitioning from an original package,
6554                // fix up the new package's name now.  We need to do this after
6555                // looking up the package under its new name, so getPackageLP
6556                // can take care of fiddling things correctly.
6557                pkg.setPackageName(origPackage.name);
6558
6559                // File a report about this.
6560                String msg = "New package " + pkgSetting.realName
6561                        + " renamed to replace old package " + pkgSetting.name;
6562                reportSettingsProblem(Log.WARN, msg);
6563
6564                // Make a note of it.
6565                mTransferedPackages.add(origPackage.name);
6566
6567                // No longer need to retain this.
6568                pkgSetting.origPackage = null;
6569            }
6570
6571            if (realName != null) {
6572                // Make a note of it.
6573                mTransferedPackages.add(pkg.packageName);
6574            }
6575
6576            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6577                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6578            }
6579
6580            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6581                // Check all shared libraries and map to their actual file path.
6582                // We only do this here for apps not on a system dir, because those
6583                // are the only ones that can fail an install due to this.  We
6584                // will take care of the system apps by updating all of their
6585                // library paths after the scan is done.
6586                updateSharedLibrariesLPw(pkg, null);
6587            }
6588
6589            if (mFoundPolicyFile) {
6590                SELinuxMMAC.assignSeinfoValue(pkg);
6591            }
6592
6593            pkg.applicationInfo.uid = pkgSetting.appId;
6594            pkg.mExtras = pkgSetting;
6595            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6596                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6597                    // We just determined the app is signed correctly, so bring
6598                    // over the latest parsed certs.
6599                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6600                } else {
6601                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6602                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6603                                "Package " + pkg.packageName + " upgrade keys do not match the "
6604                                + "previously installed version");
6605                    } else {
6606                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6607                        String msg = "System package " + pkg.packageName
6608                            + " signature changed; retaining data.";
6609                        reportSettingsProblem(Log.WARN, msg);
6610                    }
6611                }
6612            } else {
6613                try {
6614                    verifySignaturesLP(pkgSetting, pkg);
6615                    // We just determined the app is signed correctly, so bring
6616                    // over the latest parsed certs.
6617                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6618                } catch (PackageManagerException e) {
6619                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6620                        throw e;
6621                    }
6622                    // The signature has changed, but this package is in the system
6623                    // image...  let's recover!
6624                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6625                    // However...  if this package is part of a shared user, but it
6626                    // doesn't match the signature of the shared user, let's fail.
6627                    // What this means is that you can't change the signatures
6628                    // associated with an overall shared user, which doesn't seem all
6629                    // that unreasonable.
6630                    if (pkgSetting.sharedUser != null) {
6631                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6632                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6633                            throw new PackageManagerException(
6634                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6635                                            "Signature mismatch for shared user : "
6636                                            + pkgSetting.sharedUser);
6637                        }
6638                    }
6639                    // File a report about this.
6640                    String msg = "System package " + pkg.packageName
6641                        + " signature changed; retaining data.";
6642                    reportSettingsProblem(Log.WARN, msg);
6643                }
6644            }
6645            // Verify that this new package doesn't have any content providers
6646            // that conflict with existing packages.  Only do this if the
6647            // package isn't already installed, since we don't want to break
6648            // things that are installed.
6649            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6650                final int N = pkg.providers.size();
6651                int i;
6652                for (i=0; i<N; i++) {
6653                    PackageParser.Provider p = pkg.providers.get(i);
6654                    if (p.info.authority != null) {
6655                        String names[] = p.info.authority.split(";");
6656                        for (int j = 0; j < names.length; j++) {
6657                            if (mProvidersByAuthority.containsKey(names[j])) {
6658                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6659                                final String otherPackageName =
6660                                        ((other != null && other.getComponentName() != null) ?
6661                                                other.getComponentName().getPackageName() : "?");
6662                                throw new PackageManagerException(
6663                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6664                                                "Can't install because provider name " + names[j]
6665                                                + " (in package " + pkg.applicationInfo.packageName
6666                                                + ") is already used by " + otherPackageName);
6667                            }
6668                        }
6669                    }
6670                }
6671            }
6672
6673            if (pkg.mAdoptPermissions != null) {
6674                // This package wants to adopt ownership of permissions from
6675                // another package.
6676                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6677                    final String origName = pkg.mAdoptPermissions.get(i);
6678                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6679                    if (orig != null) {
6680                        if (verifyPackageUpdateLPr(orig, pkg)) {
6681                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6682                                    + pkg.packageName);
6683                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6684                        }
6685                    }
6686                }
6687            }
6688        }
6689
6690        final String pkgName = pkg.packageName;
6691
6692        final long scanFileTime = scanFile.lastModified();
6693        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6694        pkg.applicationInfo.processName = fixProcessName(
6695                pkg.applicationInfo.packageName,
6696                pkg.applicationInfo.processName,
6697                pkg.applicationInfo.uid);
6698
6699        File dataPath;
6700        if (mPlatformPackage == pkg) {
6701            // The system package is special.
6702            dataPath = new File(Environment.getDataDirectory(), "system");
6703
6704            pkg.applicationInfo.dataDir = dataPath.getPath();
6705
6706        } else {
6707            // This is a normal package, need to make its data directory.
6708            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6709                    UserHandle.USER_OWNER, pkg.packageName);
6710
6711            boolean uidError = false;
6712            if (dataPath.exists()) {
6713                int currentUid = 0;
6714                try {
6715                    StructStat stat = Os.stat(dataPath.getPath());
6716                    currentUid = stat.st_uid;
6717                } catch (ErrnoException e) {
6718                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6719                }
6720
6721                // If we have mismatched owners for the data path, we have a problem.
6722                if (currentUid != pkg.applicationInfo.uid) {
6723                    boolean recovered = false;
6724                    if (currentUid == 0) {
6725                        // The directory somehow became owned by root.  Wow.
6726                        // This is probably because the system was stopped while
6727                        // installd was in the middle of messing with its libs
6728                        // directory.  Ask installd to fix that.
6729                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6730                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6731                        if (ret >= 0) {
6732                            recovered = true;
6733                            String msg = "Package " + pkg.packageName
6734                                    + " unexpectedly changed to uid 0; recovered to " +
6735                                    + pkg.applicationInfo.uid;
6736                            reportSettingsProblem(Log.WARN, msg);
6737                        }
6738                    }
6739                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6740                            || (scanFlags&SCAN_BOOTING) != 0)) {
6741                        // If this is a system app, we can at least delete its
6742                        // current data so the application will still work.
6743                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6744                        if (ret >= 0) {
6745                            // TODO: Kill the processes first
6746                            // Old data gone!
6747                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6748                                    ? "System package " : "Third party package ";
6749                            String msg = prefix + pkg.packageName
6750                                    + " has changed from uid: "
6751                                    + currentUid + " to "
6752                                    + pkg.applicationInfo.uid + "; old data erased";
6753                            reportSettingsProblem(Log.WARN, msg);
6754                            recovered = true;
6755
6756                            // And now re-install the app.
6757                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6758                                    pkg.applicationInfo.seinfo);
6759                            if (ret == -1) {
6760                                // Ack should not happen!
6761                                msg = prefix + pkg.packageName
6762                                        + " could not have data directory re-created after delete.";
6763                                reportSettingsProblem(Log.WARN, msg);
6764                                throw new PackageManagerException(
6765                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6766                            }
6767                        }
6768                        if (!recovered) {
6769                            mHasSystemUidErrors = true;
6770                        }
6771                    } else if (!recovered) {
6772                        // If we allow this install to proceed, we will be broken.
6773                        // Abort, abort!
6774                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6775                                "scanPackageLI");
6776                    }
6777                    if (!recovered) {
6778                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6779                            + pkg.applicationInfo.uid + "/fs_"
6780                            + currentUid;
6781                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6782                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6783                        String msg = "Package " + pkg.packageName
6784                                + " has mismatched uid: "
6785                                + currentUid + " on disk, "
6786                                + pkg.applicationInfo.uid + " in settings";
6787                        // writer
6788                        synchronized (mPackages) {
6789                            mSettings.mReadMessages.append(msg);
6790                            mSettings.mReadMessages.append('\n');
6791                            uidError = true;
6792                            if (!pkgSetting.uidError) {
6793                                reportSettingsProblem(Log.ERROR, msg);
6794                            }
6795                        }
6796                    }
6797                }
6798                pkg.applicationInfo.dataDir = dataPath.getPath();
6799                if (mShouldRestoreconData) {
6800                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6801                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6802                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6803                }
6804            } else {
6805                if (DEBUG_PACKAGE_SCANNING) {
6806                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6807                        Log.v(TAG, "Want this data dir: " + dataPath);
6808                }
6809                //invoke installer to do the actual installation
6810                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6811                        pkg.applicationInfo.seinfo);
6812                if (ret < 0) {
6813                    // Error from installer
6814                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6815                            "Unable to create data dirs [errorCode=" + ret + "]");
6816                }
6817
6818                if (dataPath.exists()) {
6819                    pkg.applicationInfo.dataDir = dataPath.getPath();
6820                } else {
6821                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6822                    pkg.applicationInfo.dataDir = null;
6823                }
6824            }
6825
6826            pkgSetting.uidError = uidError;
6827        }
6828
6829        final String path = scanFile.getPath();
6830        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6831
6832        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6833            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6834
6835            // Some system apps still use directory structure for native libraries
6836            // in which case we might end up not detecting abi solely based on apk
6837            // structure. Try to detect abi based on directory structure.
6838            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6839                    pkg.applicationInfo.primaryCpuAbi == null) {
6840                setBundledAppAbisAndRoots(pkg, pkgSetting);
6841                setNativeLibraryPaths(pkg);
6842            }
6843
6844        } else {
6845            if ((scanFlags & SCAN_MOVE) != 0) {
6846                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6847                // but we already have this packages package info in the PackageSetting. We just
6848                // use that and derive the native library path based on the new codepath.
6849                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6850                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6851            }
6852
6853            // Set native library paths again. For moves, the path will be updated based on the
6854            // ABIs we've determined above. For non-moves, the path will be updated based on the
6855            // ABIs we determined during compilation, but the path will depend on the final
6856            // package path (after the rename away from the stage path).
6857            setNativeLibraryPaths(pkg);
6858        }
6859
6860        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6861        final int[] userIds = sUserManager.getUserIds();
6862        synchronized (mInstallLock) {
6863            // Make sure all user data directories are ready to roll; we're okay
6864            // if they already exist
6865            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6866                for (int userId : userIds) {
6867                    if (userId != 0) {
6868                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6869                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6870                                pkg.applicationInfo.seinfo);
6871                    }
6872                }
6873            }
6874
6875            // Create a native library symlink only if we have native libraries
6876            // and if the native libraries are 32 bit libraries. We do not provide
6877            // this symlink for 64 bit libraries.
6878            if (pkg.applicationInfo.primaryCpuAbi != null &&
6879                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6880                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6881                for (int userId : userIds) {
6882                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6883                            nativeLibPath, userId) < 0) {
6884                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6885                                "Failed linking native library dir (user=" + userId + ")");
6886                    }
6887                }
6888            }
6889        }
6890
6891        // This is a special case for the "system" package, where the ABI is
6892        // dictated by the zygote configuration (and init.rc). We should keep track
6893        // of this ABI so that we can deal with "normal" applications that run under
6894        // the same UID correctly.
6895        if (mPlatformPackage == pkg) {
6896            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6897                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6898        }
6899
6900        // If there's a mismatch between the abi-override in the package setting
6901        // and the abiOverride specified for the install. Warn about this because we
6902        // would've already compiled the app without taking the package setting into
6903        // account.
6904        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6905            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6906                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6907                        " for package: " + pkg.packageName);
6908            }
6909        }
6910
6911        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6912        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6913        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6914
6915        // Copy the derived override back to the parsed package, so that we can
6916        // update the package settings accordingly.
6917        pkg.cpuAbiOverride = cpuAbiOverride;
6918
6919        if (DEBUG_ABI_SELECTION) {
6920            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6921                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6922                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6923        }
6924
6925        // Push the derived path down into PackageSettings so we know what to
6926        // clean up at uninstall time.
6927        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6928
6929        if (DEBUG_ABI_SELECTION) {
6930            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6931                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6932                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6933        }
6934
6935        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6936            // We don't do this here during boot because we can do it all
6937            // at once after scanning all existing packages.
6938            //
6939            // We also do this *before* we perform dexopt on this package, so that
6940            // we can avoid redundant dexopts, and also to make sure we've got the
6941            // code and package path correct.
6942            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6943                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6944        }
6945
6946        if ((scanFlags & SCAN_NO_DEX) == 0) {
6947            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6948                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6949            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6950                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6951            }
6952        }
6953        if (mFactoryTest && pkg.requestedPermissions.contains(
6954                android.Manifest.permission.FACTORY_TEST)) {
6955            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6956        }
6957
6958        ArrayList<PackageParser.Package> clientLibPkgs = null;
6959
6960        // writer
6961        synchronized (mPackages) {
6962            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6963                // Only system apps can add new shared libraries.
6964                if (pkg.libraryNames != null) {
6965                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6966                        String name = pkg.libraryNames.get(i);
6967                        boolean allowed = false;
6968                        if (pkg.isUpdatedSystemApp()) {
6969                            // New library entries can only be added through the
6970                            // system image.  This is important to get rid of a lot
6971                            // of nasty edge cases: for example if we allowed a non-
6972                            // system update of the app to add a library, then uninstalling
6973                            // the update would make the library go away, and assumptions
6974                            // we made such as through app install filtering would now
6975                            // have allowed apps on the device which aren't compatible
6976                            // with it.  Better to just have the restriction here, be
6977                            // conservative, and create many fewer cases that can negatively
6978                            // impact the user experience.
6979                            final PackageSetting sysPs = mSettings
6980                                    .getDisabledSystemPkgLPr(pkg.packageName);
6981                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6982                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6983                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6984                                        allowed = true;
6985                                        allowed = true;
6986                                        break;
6987                                    }
6988                                }
6989                            }
6990                        } else {
6991                            allowed = true;
6992                        }
6993                        if (allowed) {
6994                            if (!mSharedLibraries.containsKey(name)) {
6995                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6996                            } else if (!name.equals(pkg.packageName)) {
6997                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6998                                        + name + " already exists; skipping");
6999                            }
7000                        } else {
7001                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7002                                    + name + " that is not declared on system image; skipping");
7003                        }
7004                    }
7005                    if ((scanFlags&SCAN_BOOTING) == 0) {
7006                        // If we are not booting, we need to update any applications
7007                        // that are clients of our shared library.  If we are booting,
7008                        // this will all be done once the scan is complete.
7009                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7010                    }
7011                }
7012            }
7013        }
7014
7015        // We also need to dexopt any apps that are dependent on this library.  Note that
7016        // if these fail, we should abort the install since installing the library will
7017        // result in some apps being broken.
7018        if (clientLibPkgs != null) {
7019            if ((scanFlags & SCAN_NO_DEX) == 0) {
7020                for (int i = 0; i < clientLibPkgs.size(); i++) {
7021                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7022                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7023                            null /* instruction sets */, forceDex,
7024                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7025                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7026                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7027                                "scanPackageLI failed to dexopt clientLibPkgs");
7028                    }
7029                }
7030            }
7031        }
7032
7033        // Also need to kill any apps that are dependent on the library.
7034        if (clientLibPkgs != null) {
7035            for (int i=0; i<clientLibPkgs.size(); i++) {
7036                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7037                killApplication(clientPkg.applicationInfo.packageName,
7038                        clientPkg.applicationInfo.uid, "update lib");
7039            }
7040        }
7041
7042        // Make sure we're not adding any bogus keyset info
7043        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7044        ksms.assertScannedPackageValid(pkg);
7045
7046        // writer
7047        synchronized (mPackages) {
7048            // We don't expect installation to fail beyond this point
7049
7050            // Add the new setting to mSettings
7051            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7052            // Add the new setting to mPackages
7053            mPackages.put(pkg.applicationInfo.packageName, pkg);
7054            // Make sure we don't accidentally delete its data.
7055            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7056            while (iter.hasNext()) {
7057                PackageCleanItem item = iter.next();
7058                if (pkgName.equals(item.packageName)) {
7059                    iter.remove();
7060                }
7061            }
7062
7063            // Take care of first install / last update times.
7064            if (currentTime != 0) {
7065                if (pkgSetting.firstInstallTime == 0) {
7066                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7067                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7068                    pkgSetting.lastUpdateTime = currentTime;
7069                }
7070            } else if (pkgSetting.firstInstallTime == 0) {
7071                // We need *something*.  Take time time stamp of the file.
7072                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7073            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7074                if (scanFileTime != pkgSetting.timeStamp) {
7075                    // A package on the system image has changed; consider this
7076                    // to be an update.
7077                    pkgSetting.lastUpdateTime = scanFileTime;
7078                }
7079            }
7080
7081            // Add the package's KeySets to the global KeySetManagerService
7082            ksms.addScannedPackageLPw(pkg);
7083
7084            int N = pkg.providers.size();
7085            StringBuilder r = null;
7086            int i;
7087            for (i=0; i<N; i++) {
7088                PackageParser.Provider p = pkg.providers.get(i);
7089                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7090                        p.info.processName, pkg.applicationInfo.uid);
7091                mProviders.addProvider(p);
7092                p.syncable = p.info.isSyncable;
7093                if (p.info.authority != null) {
7094                    String names[] = p.info.authority.split(";");
7095                    p.info.authority = null;
7096                    for (int j = 0; j < names.length; j++) {
7097                        if (j == 1 && p.syncable) {
7098                            // We only want the first authority for a provider to possibly be
7099                            // syncable, so if we already added this provider using a different
7100                            // authority clear the syncable flag. We copy the provider before
7101                            // changing it because the mProviders object contains a reference
7102                            // to a provider that we don't want to change.
7103                            // Only do this for the second authority since the resulting provider
7104                            // object can be the same for all future authorities for this provider.
7105                            p = new PackageParser.Provider(p);
7106                            p.syncable = false;
7107                        }
7108                        if (!mProvidersByAuthority.containsKey(names[j])) {
7109                            mProvidersByAuthority.put(names[j], p);
7110                            if (p.info.authority == null) {
7111                                p.info.authority = names[j];
7112                            } else {
7113                                p.info.authority = p.info.authority + ";" + names[j];
7114                            }
7115                            if (DEBUG_PACKAGE_SCANNING) {
7116                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7117                                    Log.d(TAG, "Registered content provider: " + names[j]
7118                                            + ", className = " + p.info.name + ", isSyncable = "
7119                                            + p.info.isSyncable);
7120                            }
7121                        } else {
7122                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7123                            Slog.w(TAG, "Skipping provider name " + names[j] +
7124                                    " (in package " + pkg.applicationInfo.packageName +
7125                                    "): name already used by "
7126                                    + ((other != null && other.getComponentName() != null)
7127                                            ? other.getComponentName().getPackageName() : "?"));
7128                        }
7129                    }
7130                }
7131                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7132                    if (r == null) {
7133                        r = new StringBuilder(256);
7134                    } else {
7135                        r.append(' ');
7136                    }
7137                    r.append(p.info.name);
7138                }
7139            }
7140            if (r != null) {
7141                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7142            }
7143
7144            N = pkg.services.size();
7145            r = null;
7146            for (i=0; i<N; i++) {
7147                PackageParser.Service s = pkg.services.get(i);
7148                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7149                        s.info.processName, pkg.applicationInfo.uid);
7150                mServices.addService(s);
7151                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7152                    if (r == null) {
7153                        r = new StringBuilder(256);
7154                    } else {
7155                        r.append(' ');
7156                    }
7157                    r.append(s.info.name);
7158                }
7159            }
7160            if (r != null) {
7161                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7162            }
7163
7164            N = pkg.receivers.size();
7165            r = null;
7166            for (i=0; i<N; i++) {
7167                PackageParser.Activity a = pkg.receivers.get(i);
7168                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7169                        a.info.processName, pkg.applicationInfo.uid);
7170                mReceivers.addActivity(a, "receiver");
7171                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7172                    if (r == null) {
7173                        r = new StringBuilder(256);
7174                    } else {
7175                        r.append(' ');
7176                    }
7177                    r.append(a.info.name);
7178                }
7179            }
7180            if (r != null) {
7181                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7182            }
7183
7184            N = pkg.activities.size();
7185            r = null;
7186            for (i=0; i<N; i++) {
7187                PackageParser.Activity a = pkg.activities.get(i);
7188                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7189                        a.info.processName, pkg.applicationInfo.uid);
7190                mActivities.addActivity(a, "activity");
7191                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7192                    if (r == null) {
7193                        r = new StringBuilder(256);
7194                    } else {
7195                        r.append(' ');
7196                    }
7197                    r.append(a.info.name);
7198                }
7199            }
7200            if (r != null) {
7201                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7202            }
7203
7204            N = pkg.permissionGroups.size();
7205            r = null;
7206            for (i=0; i<N; i++) {
7207                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7208                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7209                if (cur == null) {
7210                    mPermissionGroups.put(pg.info.name, pg);
7211                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7212                        if (r == null) {
7213                            r = new StringBuilder(256);
7214                        } else {
7215                            r.append(' ');
7216                        }
7217                        r.append(pg.info.name);
7218                    }
7219                } else {
7220                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7221                            + pg.info.packageName + " ignored: original from "
7222                            + cur.info.packageName);
7223                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7224                        if (r == null) {
7225                            r = new StringBuilder(256);
7226                        } else {
7227                            r.append(' ');
7228                        }
7229                        r.append("DUP:");
7230                        r.append(pg.info.name);
7231                    }
7232                }
7233            }
7234            if (r != null) {
7235                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7236            }
7237
7238            N = pkg.permissions.size();
7239            r = null;
7240            for (i=0; i<N; i++) {
7241                PackageParser.Permission p = pkg.permissions.get(i);
7242
7243                // Now that permission groups have a special meaning, we ignore permission
7244                // groups for legacy apps to prevent unexpected behavior. In particular,
7245                // permissions for one app being granted to someone just becuase they happen
7246                // to be in a group defined by another app (before this had no implications).
7247                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7248                    p.group = mPermissionGroups.get(p.info.group);
7249                    // Warn for a permission in an unknown group.
7250                    if (p.info.group != null && p.group == null) {
7251                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7252                                + p.info.packageName + " in an unknown group " + p.info.group);
7253                    }
7254                }
7255
7256                ArrayMap<String, BasePermission> permissionMap =
7257                        p.tree ? mSettings.mPermissionTrees
7258                                : mSettings.mPermissions;
7259                BasePermission bp = permissionMap.get(p.info.name);
7260
7261                // Allow system apps to redefine non-system permissions
7262                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7263                    final boolean currentOwnerIsSystem = (bp.perm != null
7264                            && isSystemApp(bp.perm.owner));
7265                    if (isSystemApp(p.owner)) {
7266                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7267                            // It's a built-in permission and no owner, take ownership now
7268                            bp.packageSetting = pkgSetting;
7269                            bp.perm = p;
7270                            bp.uid = pkg.applicationInfo.uid;
7271                            bp.sourcePackage = p.info.packageName;
7272                        } else if (!currentOwnerIsSystem) {
7273                            String msg = "New decl " + p.owner + " of permission  "
7274                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7275                            reportSettingsProblem(Log.WARN, msg);
7276                            bp = null;
7277                        }
7278                    }
7279                }
7280
7281                if (bp == null) {
7282                    bp = new BasePermission(p.info.name, p.info.packageName,
7283                            BasePermission.TYPE_NORMAL);
7284                    permissionMap.put(p.info.name, bp);
7285                }
7286
7287                if (bp.perm == null) {
7288                    if (bp.sourcePackage == null
7289                            || bp.sourcePackage.equals(p.info.packageName)) {
7290                        BasePermission tree = findPermissionTreeLP(p.info.name);
7291                        if (tree == null
7292                                || tree.sourcePackage.equals(p.info.packageName)) {
7293                            bp.packageSetting = pkgSetting;
7294                            bp.perm = p;
7295                            bp.uid = pkg.applicationInfo.uid;
7296                            bp.sourcePackage = p.info.packageName;
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(p.info.name);
7304                            }
7305                        } else {
7306                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7307                                    + p.info.packageName + " ignored: base tree "
7308                                    + tree.name + " is from package "
7309                                    + tree.sourcePackage);
7310                        }
7311                    } else {
7312                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7313                                + p.info.packageName + " ignored: original from "
7314                                + bp.sourcePackage);
7315                    }
7316                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7317                    if (r == null) {
7318                        r = new StringBuilder(256);
7319                    } else {
7320                        r.append(' ');
7321                    }
7322                    r.append("DUP:");
7323                    r.append(p.info.name);
7324                }
7325                if (bp.perm == p) {
7326                    bp.protectionLevel = p.info.protectionLevel;
7327                }
7328            }
7329
7330            if (r != null) {
7331                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7332            }
7333
7334            N = pkg.instrumentation.size();
7335            r = null;
7336            for (i=0; i<N; i++) {
7337                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7338                a.info.packageName = pkg.applicationInfo.packageName;
7339                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7340                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7341                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7342                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7343                a.info.dataDir = pkg.applicationInfo.dataDir;
7344
7345                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7346                // need other information about the application, like the ABI and what not ?
7347                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7348                mInstrumentation.put(a.getComponentName(), a);
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(a.info.name);
7356                }
7357            }
7358            if (r != null) {
7359                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7360            }
7361
7362            if (pkg.protectedBroadcasts != null) {
7363                N = pkg.protectedBroadcasts.size();
7364                for (i=0; i<N; i++) {
7365                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7366                }
7367            }
7368
7369            pkgSetting.setTimeStamp(scanFileTime);
7370
7371            // Create idmap files for pairs of (packages, overlay packages).
7372            // Note: "android", ie framework-res.apk, is handled by native layers.
7373            if (pkg.mOverlayTarget != null) {
7374                // This is an overlay package.
7375                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7376                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7377                        mOverlays.put(pkg.mOverlayTarget,
7378                                new ArrayMap<String, PackageParser.Package>());
7379                    }
7380                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7381                    map.put(pkg.packageName, pkg);
7382                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7383                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7384                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7385                                "scanPackageLI failed to createIdmap");
7386                    }
7387                }
7388            } else if (mOverlays.containsKey(pkg.packageName) &&
7389                    !pkg.packageName.equals("android")) {
7390                // This is a regular package, with one or more known overlay packages.
7391                createIdmapsForPackageLI(pkg);
7392            }
7393        }
7394
7395        return pkg;
7396    }
7397
7398    /**
7399     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7400     * is derived purely on the basis of the contents of {@code scanFile} and
7401     * {@code cpuAbiOverride}.
7402     *
7403     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7404     */
7405    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7406                                 String cpuAbiOverride, boolean extractLibs)
7407            throws PackageManagerException {
7408        // TODO: We can probably be smarter about this stuff. For installed apps,
7409        // we can calculate this information at install time once and for all. For
7410        // system apps, we can probably assume that this information doesn't change
7411        // after the first boot scan. As things stand, we do lots of unnecessary work.
7412
7413        // Give ourselves some initial paths; we'll come back for another
7414        // pass once we've determined ABI below.
7415        setNativeLibraryPaths(pkg);
7416
7417        // We would never need to extract libs for forward-locked and external packages,
7418        // since the container service will do it for us. We shouldn't attempt to
7419        // extract libs from system app when it was not updated.
7420        if (pkg.isForwardLocked() || isExternal(pkg) ||
7421            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7422            extractLibs = false;
7423        }
7424
7425        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7426        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7427
7428        NativeLibraryHelper.Handle handle = null;
7429        try {
7430            handle = NativeLibraryHelper.Handle.create(scanFile);
7431            // TODO(multiArch): This can be null for apps that didn't go through the
7432            // usual installation process. We can calculate it again, like we
7433            // do during install time.
7434            //
7435            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7436            // unnecessary.
7437            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7438
7439            // Null out the abis so that they can be recalculated.
7440            pkg.applicationInfo.primaryCpuAbi = null;
7441            pkg.applicationInfo.secondaryCpuAbi = null;
7442            if (isMultiArch(pkg.applicationInfo)) {
7443                // Warn if we've set an abiOverride for multi-lib packages..
7444                // By definition, we need to copy both 32 and 64 bit libraries for
7445                // such packages.
7446                if (pkg.cpuAbiOverride != null
7447                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7448                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7449                }
7450
7451                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7452                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7453                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7454                    if (extractLibs) {
7455                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7456                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7457                                useIsaSpecificSubdirs);
7458                    } else {
7459                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7460                    }
7461                }
7462
7463                maybeThrowExceptionForMultiArchCopy(
7464                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7465
7466                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7467                    if (extractLibs) {
7468                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7469                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7470                                useIsaSpecificSubdirs);
7471                    } else {
7472                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7473                    }
7474                }
7475
7476                maybeThrowExceptionForMultiArchCopy(
7477                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7478
7479                if (abi64 >= 0) {
7480                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7481                }
7482
7483                if (abi32 >= 0) {
7484                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7485                    if (abi64 >= 0) {
7486                        pkg.applicationInfo.secondaryCpuAbi = abi;
7487                    } else {
7488                        pkg.applicationInfo.primaryCpuAbi = abi;
7489                    }
7490                }
7491            } else {
7492                String[] abiList = (cpuAbiOverride != null) ?
7493                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7494
7495                // Enable gross and lame hacks for apps that are built with old
7496                // SDK tools. We must scan their APKs for renderscript bitcode and
7497                // not launch them if it's present. Don't bother checking on devices
7498                // that don't have 64 bit support.
7499                boolean needsRenderScriptOverride = false;
7500                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7501                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7502                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7503                    needsRenderScriptOverride = true;
7504                }
7505
7506                final int copyRet;
7507                if (extractLibs) {
7508                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7509                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7510                } else {
7511                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7512                }
7513
7514                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7515                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7516                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7517                }
7518
7519                if (copyRet >= 0) {
7520                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7521                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7522                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7523                } else if (needsRenderScriptOverride) {
7524                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7525                }
7526            }
7527        } catch (IOException ioe) {
7528            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7529        } finally {
7530            IoUtils.closeQuietly(handle);
7531        }
7532
7533        // Now that we've calculated the ABIs and determined if it's an internal app,
7534        // we will go ahead and populate the nativeLibraryPath.
7535        setNativeLibraryPaths(pkg);
7536    }
7537
7538    /**
7539     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7540     * i.e, so that all packages can be run inside a single process if required.
7541     *
7542     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7543     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7544     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7545     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7546     * updating a package that belongs to a shared user.
7547     *
7548     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7549     * adds unnecessary complexity.
7550     */
7551    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7552            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7553        String requiredInstructionSet = null;
7554        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7555            requiredInstructionSet = VMRuntime.getInstructionSet(
7556                     scannedPackage.applicationInfo.primaryCpuAbi);
7557        }
7558
7559        PackageSetting requirer = null;
7560        for (PackageSetting ps : packagesForUser) {
7561            // If packagesForUser contains scannedPackage, we skip it. This will happen
7562            // when scannedPackage is an update of an existing package. Without this check,
7563            // we will never be able to change the ABI of any package belonging to a shared
7564            // user, even if it's compatible with other packages.
7565            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7566                if (ps.primaryCpuAbiString == null) {
7567                    continue;
7568                }
7569
7570                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7571                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7572                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7573                    // this but there's not much we can do.
7574                    String errorMessage = "Instruction set mismatch, "
7575                            + ((requirer == null) ? "[caller]" : requirer)
7576                            + " requires " + requiredInstructionSet + " whereas " + ps
7577                            + " requires " + instructionSet;
7578                    Slog.w(TAG, errorMessage);
7579                }
7580
7581                if (requiredInstructionSet == null) {
7582                    requiredInstructionSet = instructionSet;
7583                    requirer = ps;
7584                }
7585            }
7586        }
7587
7588        if (requiredInstructionSet != null) {
7589            String adjustedAbi;
7590            if (requirer != null) {
7591                // requirer != null implies that either scannedPackage was null or that scannedPackage
7592                // did not require an ABI, in which case we have to adjust scannedPackage to match
7593                // the ABI of the set (which is the same as requirer's ABI)
7594                adjustedAbi = requirer.primaryCpuAbiString;
7595                if (scannedPackage != null) {
7596                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7597                }
7598            } else {
7599                // requirer == null implies that we're updating all ABIs in the set to
7600                // match scannedPackage.
7601                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7602            }
7603
7604            for (PackageSetting ps : packagesForUser) {
7605                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7606                    if (ps.primaryCpuAbiString != null) {
7607                        continue;
7608                    }
7609
7610                    ps.primaryCpuAbiString = adjustedAbi;
7611                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7612                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7613                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7614
7615                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7616                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7617                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7618                            ps.primaryCpuAbiString = null;
7619                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7620                            return;
7621                        } else {
7622                            mInstaller.rmdex(ps.codePathString,
7623                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7624                        }
7625                    }
7626                }
7627            }
7628        }
7629    }
7630
7631    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7632        synchronized (mPackages) {
7633            mResolverReplaced = true;
7634            // Set up information for custom user intent resolution activity.
7635            mResolveActivity.applicationInfo = pkg.applicationInfo;
7636            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7637            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7638            mResolveActivity.processName = pkg.applicationInfo.packageName;
7639            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7640            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7641                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7642            mResolveActivity.theme = 0;
7643            mResolveActivity.exported = true;
7644            mResolveActivity.enabled = true;
7645            mResolveInfo.activityInfo = mResolveActivity;
7646            mResolveInfo.priority = 0;
7647            mResolveInfo.preferredOrder = 0;
7648            mResolveInfo.match = 0;
7649            mResolveComponentName = mCustomResolverComponentName;
7650            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7651                    mResolveComponentName);
7652        }
7653    }
7654
7655    private static String calculateBundledApkRoot(final String codePathString) {
7656        final File codePath = new File(codePathString);
7657        final File codeRoot;
7658        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7659            codeRoot = Environment.getRootDirectory();
7660        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7661            codeRoot = Environment.getOemDirectory();
7662        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7663            codeRoot = Environment.getVendorDirectory();
7664        } else {
7665            // Unrecognized code path; take its top real segment as the apk root:
7666            // e.g. /something/app/blah.apk => /something
7667            try {
7668                File f = codePath.getCanonicalFile();
7669                File parent = f.getParentFile();    // non-null because codePath is a file
7670                File tmp;
7671                while ((tmp = parent.getParentFile()) != null) {
7672                    f = parent;
7673                    parent = tmp;
7674                }
7675                codeRoot = f;
7676                Slog.w(TAG, "Unrecognized code path "
7677                        + codePath + " - using " + codeRoot);
7678            } catch (IOException e) {
7679                // Can't canonicalize the code path -- shenanigans?
7680                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7681                return Environment.getRootDirectory().getPath();
7682            }
7683        }
7684        return codeRoot.getPath();
7685    }
7686
7687    /**
7688     * Derive and set the location of native libraries for the given package,
7689     * which varies depending on where and how the package was installed.
7690     */
7691    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7692        final ApplicationInfo info = pkg.applicationInfo;
7693        final String codePath = pkg.codePath;
7694        final File codeFile = new File(codePath);
7695        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7696        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7697
7698        info.nativeLibraryRootDir = null;
7699        info.nativeLibraryRootRequiresIsa = false;
7700        info.nativeLibraryDir = null;
7701        info.secondaryNativeLibraryDir = null;
7702
7703        if (isApkFile(codeFile)) {
7704            // Monolithic install
7705            if (bundledApp) {
7706                // If "/system/lib64/apkname" exists, assume that is the per-package
7707                // native library directory to use; otherwise use "/system/lib/apkname".
7708                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7709                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7710                        getPrimaryInstructionSet(info));
7711
7712                // This is a bundled system app so choose the path based on the ABI.
7713                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7714                // is just the default path.
7715                final String apkName = deriveCodePathName(codePath);
7716                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7717                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7718                        apkName).getAbsolutePath();
7719
7720                if (info.secondaryCpuAbi != null) {
7721                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7722                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7723                            secondaryLibDir, apkName).getAbsolutePath();
7724                }
7725            } else if (asecApp) {
7726                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7727                        .getAbsolutePath();
7728            } else {
7729                final String apkName = deriveCodePathName(codePath);
7730                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7731                        .getAbsolutePath();
7732            }
7733
7734            info.nativeLibraryRootRequiresIsa = false;
7735            info.nativeLibraryDir = info.nativeLibraryRootDir;
7736        } else {
7737            // Cluster install
7738            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7739            info.nativeLibraryRootRequiresIsa = true;
7740
7741            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7742                    getPrimaryInstructionSet(info)).getAbsolutePath();
7743
7744            if (info.secondaryCpuAbi != null) {
7745                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7746                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7747            }
7748        }
7749    }
7750
7751    /**
7752     * Calculate the abis and roots for a bundled app. These can uniquely
7753     * be determined from the contents of the system partition, i.e whether
7754     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7755     * of this information, and instead assume that the system was built
7756     * sensibly.
7757     */
7758    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7759                                           PackageSetting pkgSetting) {
7760        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7761
7762        // If "/system/lib64/apkname" exists, assume that is the per-package
7763        // native library directory to use; otherwise use "/system/lib/apkname".
7764        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7765        setBundledAppAbi(pkg, apkRoot, apkName);
7766        // pkgSetting might be null during rescan following uninstall of updates
7767        // to a bundled app, so accommodate that possibility.  The settings in
7768        // that case will be established later from the parsed package.
7769        //
7770        // If the settings aren't null, sync them up with what we've just derived.
7771        // note that apkRoot isn't stored in the package settings.
7772        if (pkgSetting != null) {
7773            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7774            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7775        }
7776    }
7777
7778    /**
7779     * Deduces the ABI of a bundled app and sets the relevant fields on the
7780     * parsed pkg object.
7781     *
7782     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7783     *        under which system libraries are installed.
7784     * @param apkName the name of the installed package.
7785     */
7786    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7787        final File codeFile = new File(pkg.codePath);
7788
7789        final boolean has64BitLibs;
7790        final boolean has32BitLibs;
7791        if (isApkFile(codeFile)) {
7792            // Monolithic install
7793            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7794            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7795        } else {
7796            // Cluster install
7797            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7798            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7799                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7800                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7801                has64BitLibs = (new File(rootDir, isa)).exists();
7802            } else {
7803                has64BitLibs = false;
7804            }
7805            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7806                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7807                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7808                has32BitLibs = (new File(rootDir, isa)).exists();
7809            } else {
7810                has32BitLibs = false;
7811            }
7812        }
7813
7814        if (has64BitLibs && !has32BitLibs) {
7815            // The package has 64 bit libs, but not 32 bit libs. Its primary
7816            // ABI should be 64 bit. We can safely assume here that the bundled
7817            // native libraries correspond to the most preferred ABI in the list.
7818
7819            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7820            pkg.applicationInfo.secondaryCpuAbi = null;
7821        } else if (has32BitLibs && !has64BitLibs) {
7822            // The package has 32 bit libs but not 64 bit libs. Its primary
7823            // ABI should be 32 bit.
7824
7825            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7826            pkg.applicationInfo.secondaryCpuAbi = null;
7827        } else if (has32BitLibs && has64BitLibs) {
7828            // The application has both 64 and 32 bit bundled libraries. We check
7829            // here that the app declares multiArch support, and warn if it doesn't.
7830            //
7831            // We will be lenient here and record both ABIs. The primary will be the
7832            // ABI that's higher on the list, i.e, a device that's configured to prefer
7833            // 64 bit apps will see a 64 bit primary ABI,
7834
7835            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7836                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7837            }
7838
7839            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7840                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7841                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7842            } else {
7843                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7844                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7845            }
7846        } else {
7847            pkg.applicationInfo.primaryCpuAbi = null;
7848            pkg.applicationInfo.secondaryCpuAbi = null;
7849        }
7850    }
7851
7852    private void killApplication(String pkgName, int appId, String reason) {
7853        // Request the ActivityManager to kill the process(only for existing packages)
7854        // so that we do not end up in a confused state while the user is still using the older
7855        // version of the application while the new one gets installed.
7856        IActivityManager am = ActivityManagerNative.getDefault();
7857        if (am != null) {
7858            try {
7859                am.killApplicationWithAppId(pkgName, appId, reason);
7860            } catch (RemoteException e) {
7861            }
7862        }
7863    }
7864
7865    void removePackageLI(PackageSetting ps, boolean chatty) {
7866        if (DEBUG_INSTALL) {
7867            if (chatty)
7868                Log.d(TAG, "Removing package " + ps.name);
7869        }
7870
7871        // writer
7872        synchronized (mPackages) {
7873            mPackages.remove(ps.name);
7874            final PackageParser.Package pkg = ps.pkg;
7875            if (pkg != null) {
7876                cleanPackageDataStructuresLILPw(pkg, chatty);
7877            }
7878        }
7879    }
7880
7881    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7882        if (DEBUG_INSTALL) {
7883            if (chatty)
7884                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7885        }
7886
7887        // writer
7888        synchronized (mPackages) {
7889            mPackages.remove(pkg.applicationInfo.packageName);
7890            cleanPackageDataStructuresLILPw(pkg, chatty);
7891        }
7892    }
7893
7894    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7895        int N = pkg.providers.size();
7896        StringBuilder r = null;
7897        int i;
7898        for (i=0; i<N; i++) {
7899            PackageParser.Provider p = pkg.providers.get(i);
7900            mProviders.removeProvider(p);
7901            if (p.info.authority == null) {
7902
7903                /* There was another ContentProvider with this authority when
7904                 * this app was installed so this authority is null,
7905                 * Ignore it as we don't have to unregister the provider.
7906                 */
7907                continue;
7908            }
7909            String names[] = p.info.authority.split(";");
7910            for (int j = 0; j < names.length; j++) {
7911                if (mProvidersByAuthority.get(names[j]) == p) {
7912                    mProvidersByAuthority.remove(names[j]);
7913                    if (DEBUG_REMOVE) {
7914                        if (chatty)
7915                            Log.d(TAG, "Unregistered content provider: " + names[j]
7916                                    + ", className = " + p.info.name + ", isSyncable = "
7917                                    + p.info.isSyncable);
7918                    }
7919                }
7920            }
7921            if (DEBUG_REMOVE && chatty) {
7922                if (r == null) {
7923                    r = new StringBuilder(256);
7924                } else {
7925                    r.append(' ');
7926                }
7927                r.append(p.info.name);
7928            }
7929        }
7930        if (r != null) {
7931            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7932        }
7933
7934        N = pkg.services.size();
7935        r = null;
7936        for (i=0; i<N; i++) {
7937            PackageParser.Service s = pkg.services.get(i);
7938            mServices.removeService(s);
7939            if (chatty) {
7940                if (r == null) {
7941                    r = new StringBuilder(256);
7942                } else {
7943                    r.append(' ');
7944                }
7945                r.append(s.info.name);
7946            }
7947        }
7948        if (r != null) {
7949            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7950        }
7951
7952        N = pkg.receivers.size();
7953        r = null;
7954        for (i=0; i<N; i++) {
7955            PackageParser.Activity a = pkg.receivers.get(i);
7956            mReceivers.removeActivity(a, "receiver");
7957            if (DEBUG_REMOVE && chatty) {
7958                if (r == null) {
7959                    r = new StringBuilder(256);
7960                } else {
7961                    r.append(' ');
7962                }
7963                r.append(a.info.name);
7964            }
7965        }
7966        if (r != null) {
7967            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7968        }
7969
7970        N = pkg.activities.size();
7971        r = null;
7972        for (i=0; i<N; i++) {
7973            PackageParser.Activity a = pkg.activities.get(i);
7974            mActivities.removeActivity(a, "activity");
7975            if (DEBUG_REMOVE && chatty) {
7976                if (r == null) {
7977                    r = new StringBuilder(256);
7978                } else {
7979                    r.append(' ');
7980                }
7981                r.append(a.info.name);
7982            }
7983        }
7984        if (r != null) {
7985            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7986        }
7987
7988        N = pkg.permissions.size();
7989        r = null;
7990        for (i=0; i<N; i++) {
7991            PackageParser.Permission p = pkg.permissions.get(i);
7992            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7993            if (bp == null) {
7994                bp = mSettings.mPermissionTrees.get(p.info.name);
7995            }
7996            if (bp != null && bp.perm == p) {
7997                bp.perm = null;
7998                if (DEBUG_REMOVE && chatty) {
7999                    if (r == null) {
8000                        r = new StringBuilder(256);
8001                    } else {
8002                        r.append(' ');
8003                    }
8004                    r.append(p.info.name);
8005                }
8006            }
8007            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8008                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8009                if (appOpPerms != null) {
8010                    appOpPerms.remove(pkg.packageName);
8011                }
8012            }
8013        }
8014        if (r != null) {
8015            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8016        }
8017
8018        N = pkg.requestedPermissions.size();
8019        r = null;
8020        for (i=0; i<N; i++) {
8021            String perm = pkg.requestedPermissions.get(i);
8022            BasePermission bp = mSettings.mPermissions.get(perm);
8023            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8024                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8025                if (appOpPerms != null) {
8026                    appOpPerms.remove(pkg.packageName);
8027                    if (appOpPerms.isEmpty()) {
8028                        mAppOpPermissionPackages.remove(perm);
8029                    }
8030                }
8031            }
8032        }
8033        if (r != null) {
8034            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8035        }
8036
8037        N = pkg.instrumentation.size();
8038        r = null;
8039        for (i=0; i<N; i++) {
8040            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8041            mInstrumentation.remove(a.getComponentName());
8042            if (DEBUG_REMOVE && chatty) {
8043                if (r == null) {
8044                    r = new StringBuilder(256);
8045                } else {
8046                    r.append(' ');
8047                }
8048                r.append(a.info.name);
8049            }
8050        }
8051        if (r != null) {
8052            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8053        }
8054
8055        r = null;
8056        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8057            // Only system apps can hold shared libraries.
8058            if (pkg.libraryNames != null) {
8059                for (i=0; i<pkg.libraryNames.size(); i++) {
8060                    String name = pkg.libraryNames.get(i);
8061                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8062                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8063                        mSharedLibraries.remove(name);
8064                        if (DEBUG_REMOVE && chatty) {
8065                            if (r == null) {
8066                                r = new StringBuilder(256);
8067                            } else {
8068                                r.append(' ');
8069                            }
8070                            r.append(name);
8071                        }
8072                    }
8073                }
8074            }
8075        }
8076        if (r != null) {
8077            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8078        }
8079    }
8080
8081    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8082        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8083            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8084                return true;
8085            }
8086        }
8087        return false;
8088    }
8089
8090    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8091    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8092    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8093
8094    private void updatePermissionsLPw(String changingPkg,
8095            PackageParser.Package pkgInfo, int flags) {
8096        // Make sure there are no dangling permission trees.
8097        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8098        while (it.hasNext()) {
8099            final BasePermission bp = it.next();
8100            if (bp.packageSetting == null) {
8101                // We may not yet have parsed the package, so just see if
8102                // we still know about its settings.
8103                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8104            }
8105            if (bp.packageSetting == null) {
8106                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8107                        + " from package " + bp.sourcePackage);
8108                it.remove();
8109            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8110                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8111                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8112                            + " from package " + bp.sourcePackage);
8113                    flags |= UPDATE_PERMISSIONS_ALL;
8114                    it.remove();
8115                }
8116            }
8117        }
8118
8119        // Make sure all dynamic permissions have been assigned to a package,
8120        // and make sure there are no dangling permissions.
8121        it = mSettings.mPermissions.values().iterator();
8122        while (it.hasNext()) {
8123            final BasePermission bp = it.next();
8124            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8125                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8126                        + bp.name + " pkg=" + bp.sourcePackage
8127                        + " info=" + bp.pendingInfo);
8128                if (bp.packageSetting == null && bp.pendingInfo != null) {
8129                    final BasePermission tree = findPermissionTreeLP(bp.name);
8130                    if (tree != null && tree.perm != null) {
8131                        bp.packageSetting = tree.packageSetting;
8132                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8133                                new PermissionInfo(bp.pendingInfo));
8134                        bp.perm.info.packageName = tree.perm.info.packageName;
8135                        bp.perm.info.name = bp.name;
8136                        bp.uid = tree.uid;
8137                    }
8138                }
8139            }
8140            if (bp.packageSetting == null) {
8141                // We may not yet have parsed the package, so just see if
8142                // we still know about its settings.
8143                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8144            }
8145            if (bp.packageSetting == null) {
8146                Slog.w(TAG, "Removing dangling permission: " + bp.name
8147                        + " from package " + bp.sourcePackage);
8148                it.remove();
8149            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8150                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8151                    Slog.i(TAG, "Removing old permission: " + bp.name
8152                            + " from package " + bp.sourcePackage);
8153                    flags |= UPDATE_PERMISSIONS_ALL;
8154                    it.remove();
8155                }
8156            }
8157        }
8158
8159        // Now update the permissions for all packages, in particular
8160        // replace the granted permissions of the system packages.
8161        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8162            for (PackageParser.Package pkg : mPackages.values()) {
8163                if (pkg != pkgInfo) {
8164                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8165                            changingPkg);
8166                }
8167            }
8168        }
8169
8170        if (pkgInfo != null) {
8171            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8172        }
8173    }
8174
8175    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8176            String packageOfInterest) {
8177        // IMPORTANT: There are two types of permissions: install and runtime.
8178        // Install time permissions are granted when the app is installed to
8179        // all device users and users added in the future. Runtime permissions
8180        // are granted at runtime explicitly to specific users. Normal and signature
8181        // protected permissions are install time permissions. Dangerous permissions
8182        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8183        // otherwise they are runtime permissions. This function does not manage
8184        // runtime permissions except for the case an app targeting Lollipop MR1
8185        // being upgraded to target a newer SDK, in which case dangerous permissions
8186        // are transformed from install time to runtime ones.
8187
8188        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8189        if (ps == null) {
8190            return;
8191        }
8192
8193        PermissionsState permissionsState = ps.getPermissionsState();
8194        PermissionsState origPermissions = permissionsState;
8195
8196        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8197
8198        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8199
8200        boolean changedInstallPermission = false;
8201
8202        if (replace) {
8203            ps.installPermissionsFixed = false;
8204            if (!ps.isSharedUser()) {
8205                origPermissions = new PermissionsState(permissionsState);
8206                permissionsState.reset();
8207            }
8208        }
8209
8210        permissionsState.setGlobalGids(mGlobalGids);
8211
8212        final int N = pkg.requestedPermissions.size();
8213        for (int i=0; i<N; i++) {
8214            final String name = pkg.requestedPermissions.get(i);
8215            final BasePermission bp = mSettings.mPermissions.get(name);
8216
8217            if (DEBUG_INSTALL) {
8218                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8219            }
8220
8221            if (bp == null || bp.packageSetting == null) {
8222                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8223                    Slog.w(TAG, "Unknown permission " + name
8224                            + " in package " + pkg.packageName);
8225                }
8226                continue;
8227            }
8228
8229            final String perm = bp.name;
8230            boolean allowedSig = false;
8231            int grant = GRANT_DENIED;
8232
8233            // Keep track of app op permissions.
8234            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8235                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8236                if (pkgs == null) {
8237                    pkgs = new ArraySet<>();
8238                    mAppOpPermissionPackages.put(bp.name, pkgs);
8239                }
8240                pkgs.add(pkg.packageName);
8241            }
8242
8243            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8244            switch (level) {
8245                case PermissionInfo.PROTECTION_NORMAL: {
8246                    // For all apps normal permissions are install time ones.
8247                    grant = GRANT_INSTALL;
8248                } break;
8249
8250                case PermissionInfo.PROTECTION_DANGEROUS: {
8251                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8252                        // For legacy apps dangerous permissions are install time ones.
8253                        grant = GRANT_INSTALL_LEGACY;
8254                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8255                        // For legacy apps that became modern, install becomes runtime.
8256                        grant = GRANT_UPGRADE;
8257                    } else {
8258                        // For modern apps keep runtime permissions unchanged.
8259                        grant = GRANT_RUNTIME;
8260                    }
8261                } break;
8262
8263                case PermissionInfo.PROTECTION_SIGNATURE: {
8264                    // For all apps signature permissions are install time ones.
8265                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8266                    if (allowedSig) {
8267                        grant = GRANT_INSTALL;
8268                    }
8269                } break;
8270            }
8271
8272            if (DEBUG_INSTALL) {
8273                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8274            }
8275
8276            if (grant != GRANT_DENIED) {
8277                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8278                    // If this is an existing, non-system package, then
8279                    // we can't add any new permissions to it.
8280                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8281                        // Except...  if this is a permission that was added
8282                        // to the platform (note: need to only do this when
8283                        // updating the platform).
8284                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8285                            grant = GRANT_DENIED;
8286                        }
8287                    }
8288                }
8289
8290                switch (grant) {
8291                    case GRANT_INSTALL: {
8292                        // Revoke this as runtime permission to handle the case of
8293                        // a runtime permission being downgraded to an install one.
8294                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8295                            if (origPermissions.getRuntimePermissionState(
8296                                    bp.name, userId) != null) {
8297                                // Revoke the runtime permission and clear the flags.
8298                                origPermissions.revokeRuntimePermission(bp, userId);
8299                                origPermissions.updatePermissionFlags(bp, userId,
8300                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8301                                // If we revoked a permission permission, we have to write.
8302                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8303                                        changedRuntimePermissionUserIds, userId);
8304                            }
8305                        }
8306                        // Grant an install permission.
8307                        if (permissionsState.grantInstallPermission(bp) !=
8308                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8309                            changedInstallPermission = true;
8310                        }
8311                    } break;
8312
8313                    case GRANT_INSTALL_LEGACY: {
8314                        // Grant an install permission.
8315                        if (permissionsState.grantInstallPermission(bp) !=
8316                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8317                            changedInstallPermission = true;
8318                        }
8319                    } break;
8320
8321                    case GRANT_RUNTIME: {
8322                        // Grant previously granted runtime permissions.
8323                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8324                            PermissionState permissionState = origPermissions
8325                                    .getRuntimePermissionState(bp.name, userId);
8326                            final int flags = permissionState != null
8327                                    ? permissionState.getFlags() : 0;
8328                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8329                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8330                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8331                                    // If we cannot put the permission as it was, we have to write.
8332                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8333                                            changedRuntimePermissionUserIds, userId);
8334                                }
8335                            }
8336                            // Propagate the permission flags.
8337                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8338                        }
8339                    } break;
8340
8341                    case GRANT_UPGRADE: {
8342                        // Grant runtime permissions for a previously held install permission.
8343                        PermissionState permissionState = origPermissions
8344                                .getInstallPermissionState(bp.name);
8345                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8346
8347                        if (origPermissions.revokeInstallPermission(bp)
8348                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8349                            // We will be transferring the permission flags, so clear them.
8350                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8351                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8352                            changedInstallPermission = true;
8353                        }
8354
8355                        // If the permission is not to be promoted to runtime we ignore it and
8356                        // also its other flags as they are not applicable to install permissions.
8357                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8358                            for (int userId : currentUserIds) {
8359                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8360                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8361                                    // Transfer the permission flags.
8362                                    permissionsState.updatePermissionFlags(bp, userId,
8363                                            flags, flags);
8364                                    // If we granted the permission, we have to write.
8365                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8366                                            changedRuntimePermissionUserIds, userId);
8367                                }
8368                            }
8369                        }
8370                    } break;
8371
8372                    default: {
8373                        if (packageOfInterest == null
8374                                || packageOfInterest.equals(pkg.packageName)) {
8375                            Slog.w(TAG, "Not granting permission " + perm
8376                                    + " to package " + pkg.packageName
8377                                    + " because it was previously installed without");
8378                        }
8379                    } break;
8380                }
8381            } else {
8382                if (permissionsState.revokeInstallPermission(bp) !=
8383                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8384                    // Also drop the permission flags.
8385                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8386                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8387                    changedInstallPermission = true;
8388                    Slog.i(TAG, "Un-granting permission " + perm
8389                            + " from package " + pkg.packageName
8390                            + " (protectionLevel=" + bp.protectionLevel
8391                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8392                            + ")");
8393                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8394                    // Don't print warning for app op permissions, since it is fine for them
8395                    // not to be granted, there is a UI for the user to decide.
8396                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8397                        Slog.w(TAG, "Not granting permission " + perm
8398                                + " to package " + pkg.packageName
8399                                + " (protectionLevel=" + bp.protectionLevel
8400                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8401                                + ")");
8402                    }
8403                }
8404            }
8405        }
8406
8407        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8408                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8409            // This is the first that we have heard about this package, so the
8410            // permissions we have now selected are fixed until explicitly
8411            // changed.
8412            ps.installPermissionsFixed = true;
8413        }
8414
8415        // Persist the runtime permissions state for users with changes.
8416        for (int userId : changedRuntimePermissionUserIds) {
8417            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8418        }
8419    }
8420
8421    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8422        boolean allowed = false;
8423        final int NP = PackageParser.NEW_PERMISSIONS.length;
8424        for (int ip=0; ip<NP; ip++) {
8425            final PackageParser.NewPermissionInfo npi
8426                    = PackageParser.NEW_PERMISSIONS[ip];
8427            if (npi.name.equals(perm)
8428                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8429                allowed = true;
8430                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8431                        + pkg.packageName);
8432                break;
8433            }
8434        }
8435        return allowed;
8436    }
8437
8438    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8439            BasePermission bp, PermissionsState origPermissions) {
8440        boolean allowed;
8441        allowed = (compareSignatures(
8442                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8443                        == PackageManager.SIGNATURE_MATCH)
8444                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8445                        == PackageManager.SIGNATURE_MATCH);
8446        if (!allowed && (bp.protectionLevel
8447                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8448            if (isSystemApp(pkg)) {
8449                // For updated system applications, a system permission
8450                // is granted only if it had been defined by the original application.
8451                if (pkg.isUpdatedSystemApp()) {
8452                    final PackageSetting sysPs = mSettings
8453                            .getDisabledSystemPkgLPr(pkg.packageName);
8454                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8455                        // If the original was granted this permission, we take
8456                        // that grant decision as read and propagate it to the
8457                        // update.
8458                        if (sysPs.isPrivileged()) {
8459                            allowed = true;
8460                        }
8461                    } else {
8462                        // The system apk may have been updated with an older
8463                        // version of the one on the data partition, but which
8464                        // granted a new system permission that it didn't have
8465                        // before.  In this case we do want to allow the app to
8466                        // now get the new permission if the ancestral apk is
8467                        // privileged to get it.
8468                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8469                            for (int j=0;
8470                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8471                                if (perm.equals(
8472                                        sysPs.pkg.requestedPermissions.get(j))) {
8473                                    allowed = true;
8474                                    break;
8475                                }
8476                            }
8477                        }
8478                    }
8479                } else {
8480                    allowed = isPrivilegedApp(pkg);
8481                }
8482            }
8483        }
8484        if (!allowed) {
8485            if (!allowed && (bp.protectionLevel
8486                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8487                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8488                // If this was a previously normal/dangerous permission that got moved
8489                // to a system permission as part of the runtime permission redesign, then
8490                // we still want to blindly grant it to old apps.
8491                allowed = true;
8492            }
8493            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8494                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8495                // If this permission is to be granted to the system installer and
8496                // this app is an installer, then it gets the permission.
8497                allowed = true;
8498            }
8499            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8500                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8501                // If this permission is to be granted to the system verifier and
8502                // this app is a verifier, then it gets the permission.
8503                allowed = true;
8504            }
8505            if (!allowed && (bp.protectionLevel
8506                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8507                    && isSystemApp(pkg)) {
8508                // Any pre-installed system app is allowed to get this permission.
8509                allowed = true;
8510            }
8511            if (!allowed && (bp.protectionLevel
8512                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8513                // For development permissions, a development permission
8514                // is granted only if it was already granted.
8515                allowed = origPermissions.hasInstallPermission(perm);
8516            }
8517        }
8518        return allowed;
8519    }
8520
8521    final class ActivityIntentResolver
8522            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8523        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8524                boolean defaultOnly, int userId) {
8525            if (!sUserManager.exists(userId)) return null;
8526            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8527            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8528        }
8529
8530        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8531                int userId) {
8532            if (!sUserManager.exists(userId)) return null;
8533            mFlags = flags;
8534            return super.queryIntent(intent, resolvedType,
8535                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8536        }
8537
8538        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8539                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8540            if (!sUserManager.exists(userId)) return null;
8541            if (packageActivities == null) {
8542                return null;
8543            }
8544            mFlags = flags;
8545            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8546            final int N = packageActivities.size();
8547            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8548                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8549
8550            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8551            for (int i = 0; i < N; ++i) {
8552                intentFilters = packageActivities.get(i).intents;
8553                if (intentFilters != null && intentFilters.size() > 0) {
8554                    PackageParser.ActivityIntentInfo[] array =
8555                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8556                    intentFilters.toArray(array);
8557                    listCut.add(array);
8558                }
8559            }
8560            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8561        }
8562
8563        public final void addActivity(PackageParser.Activity a, String type) {
8564            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8565            mActivities.put(a.getComponentName(), a);
8566            if (DEBUG_SHOW_INFO)
8567                Log.v(
8568                TAG, "  " + type + " " +
8569                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8570            if (DEBUG_SHOW_INFO)
8571                Log.v(TAG, "    Class=" + a.info.name);
8572            final int NI = a.intents.size();
8573            for (int j=0; j<NI; j++) {
8574                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8575                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8576                    intent.setPriority(0);
8577                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8578                            + a.className + " with priority > 0, forcing to 0");
8579                }
8580                if (DEBUG_SHOW_INFO) {
8581                    Log.v(TAG, "    IntentFilter:");
8582                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8583                }
8584                if (!intent.debugCheck()) {
8585                    Log.w(TAG, "==> For Activity " + a.info.name);
8586                }
8587                addFilter(intent);
8588            }
8589        }
8590
8591        public final void removeActivity(PackageParser.Activity a, String type) {
8592            mActivities.remove(a.getComponentName());
8593            if (DEBUG_SHOW_INFO) {
8594                Log.v(TAG, "  " + type + " "
8595                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8596                                : a.info.name) + ":");
8597                Log.v(TAG, "    Class=" + a.info.name);
8598            }
8599            final int NI = a.intents.size();
8600            for (int j=0; j<NI; j++) {
8601                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8602                if (DEBUG_SHOW_INFO) {
8603                    Log.v(TAG, "    IntentFilter:");
8604                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8605                }
8606                removeFilter(intent);
8607            }
8608        }
8609
8610        @Override
8611        protected boolean allowFilterResult(
8612                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8613            ActivityInfo filterAi = filter.activity.info;
8614            for (int i=dest.size()-1; i>=0; i--) {
8615                ActivityInfo destAi = dest.get(i).activityInfo;
8616                if (destAi.name == filterAi.name
8617                        && destAi.packageName == filterAi.packageName) {
8618                    return false;
8619                }
8620            }
8621            return true;
8622        }
8623
8624        @Override
8625        protected ActivityIntentInfo[] newArray(int size) {
8626            return new ActivityIntentInfo[size];
8627        }
8628
8629        @Override
8630        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8631            if (!sUserManager.exists(userId)) return true;
8632            PackageParser.Package p = filter.activity.owner;
8633            if (p != null) {
8634                PackageSetting ps = (PackageSetting)p.mExtras;
8635                if (ps != null) {
8636                    // System apps are never considered stopped for purposes of
8637                    // filtering, because there may be no way for the user to
8638                    // actually re-launch them.
8639                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8640                            && ps.getStopped(userId);
8641                }
8642            }
8643            return false;
8644        }
8645
8646        @Override
8647        protected boolean isPackageForFilter(String packageName,
8648                PackageParser.ActivityIntentInfo info) {
8649            return packageName.equals(info.activity.owner.packageName);
8650        }
8651
8652        @Override
8653        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8654                int match, int userId) {
8655            if (!sUserManager.exists(userId)) return null;
8656            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8657                return null;
8658            }
8659            final PackageParser.Activity activity = info.activity;
8660            if (mSafeMode && (activity.info.applicationInfo.flags
8661                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8662                return null;
8663            }
8664            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8665            if (ps == null) {
8666                return null;
8667            }
8668            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8669                    ps.readUserState(userId), userId);
8670            if (ai == null) {
8671                return null;
8672            }
8673            final ResolveInfo res = new ResolveInfo();
8674            res.activityInfo = ai;
8675            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8676                res.filter = info;
8677            }
8678            if (info != null) {
8679                res.handleAllWebDataURI = info.handleAllWebDataURI();
8680            }
8681            res.priority = info.getPriority();
8682            res.preferredOrder = activity.owner.mPreferredOrder;
8683            //System.out.println("Result: " + res.activityInfo.className +
8684            //                   " = " + res.priority);
8685            res.match = match;
8686            res.isDefault = info.hasDefault;
8687            res.labelRes = info.labelRes;
8688            res.nonLocalizedLabel = info.nonLocalizedLabel;
8689            if (userNeedsBadging(userId)) {
8690                res.noResourceId = true;
8691            } else {
8692                res.icon = info.icon;
8693            }
8694            res.iconResourceId = info.icon;
8695            res.system = res.activityInfo.applicationInfo.isSystemApp();
8696            return res;
8697        }
8698
8699        @Override
8700        protected void sortResults(List<ResolveInfo> results) {
8701            Collections.sort(results, mResolvePrioritySorter);
8702        }
8703
8704        @Override
8705        protected void dumpFilter(PrintWriter out, String prefix,
8706                PackageParser.ActivityIntentInfo filter) {
8707            out.print(prefix); out.print(
8708                    Integer.toHexString(System.identityHashCode(filter.activity)));
8709                    out.print(' ');
8710                    filter.activity.printComponentShortName(out);
8711                    out.print(" filter ");
8712                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8713        }
8714
8715        @Override
8716        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8717            return filter.activity;
8718        }
8719
8720        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8721            PackageParser.Activity activity = (PackageParser.Activity)label;
8722            out.print(prefix); out.print(
8723                    Integer.toHexString(System.identityHashCode(activity)));
8724                    out.print(' ');
8725                    activity.printComponentShortName(out);
8726            if (count > 1) {
8727                out.print(" ("); out.print(count); out.print(" filters)");
8728            }
8729            out.println();
8730        }
8731
8732//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8733//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8734//            final List<ResolveInfo> retList = Lists.newArrayList();
8735//            while (i.hasNext()) {
8736//                final ResolveInfo resolveInfo = i.next();
8737//                if (isEnabledLP(resolveInfo.activityInfo)) {
8738//                    retList.add(resolveInfo);
8739//                }
8740//            }
8741//            return retList;
8742//        }
8743
8744        // Keys are String (activity class name), values are Activity.
8745        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8746                = new ArrayMap<ComponentName, PackageParser.Activity>();
8747        private int mFlags;
8748    }
8749
8750    private final class ServiceIntentResolver
8751            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8752        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8753                boolean defaultOnly, int userId) {
8754            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8755            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8756        }
8757
8758        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8759                int userId) {
8760            if (!sUserManager.exists(userId)) return null;
8761            mFlags = flags;
8762            return super.queryIntent(intent, resolvedType,
8763                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8764        }
8765
8766        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8767                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8768            if (!sUserManager.exists(userId)) return null;
8769            if (packageServices == null) {
8770                return null;
8771            }
8772            mFlags = flags;
8773            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8774            final int N = packageServices.size();
8775            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8776                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8777
8778            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8779            for (int i = 0; i < N; ++i) {
8780                intentFilters = packageServices.get(i).intents;
8781                if (intentFilters != null && intentFilters.size() > 0) {
8782                    PackageParser.ServiceIntentInfo[] array =
8783                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8784                    intentFilters.toArray(array);
8785                    listCut.add(array);
8786                }
8787            }
8788            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8789        }
8790
8791        public final void addService(PackageParser.Service s) {
8792            mServices.put(s.getComponentName(), s);
8793            if (DEBUG_SHOW_INFO) {
8794                Log.v(TAG, "  "
8795                        + (s.info.nonLocalizedLabel != null
8796                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8797                Log.v(TAG, "    Class=" + s.info.name);
8798            }
8799            final int NI = s.intents.size();
8800            int j;
8801            for (j=0; j<NI; j++) {
8802                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8803                if (DEBUG_SHOW_INFO) {
8804                    Log.v(TAG, "    IntentFilter:");
8805                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8806                }
8807                if (!intent.debugCheck()) {
8808                    Log.w(TAG, "==> For Service " + s.info.name);
8809                }
8810                addFilter(intent);
8811            }
8812        }
8813
8814        public final void removeService(PackageParser.Service s) {
8815            mServices.remove(s.getComponentName());
8816            if (DEBUG_SHOW_INFO) {
8817                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8818                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8819                Log.v(TAG, "    Class=" + s.info.name);
8820            }
8821            final int NI = s.intents.size();
8822            int j;
8823            for (j=0; j<NI; j++) {
8824                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8825                if (DEBUG_SHOW_INFO) {
8826                    Log.v(TAG, "    IntentFilter:");
8827                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8828                }
8829                removeFilter(intent);
8830            }
8831        }
8832
8833        @Override
8834        protected boolean allowFilterResult(
8835                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8836            ServiceInfo filterSi = filter.service.info;
8837            for (int i=dest.size()-1; i>=0; i--) {
8838                ServiceInfo destAi = dest.get(i).serviceInfo;
8839                if (destAi.name == filterSi.name
8840                        && destAi.packageName == filterSi.packageName) {
8841                    return false;
8842                }
8843            }
8844            return true;
8845        }
8846
8847        @Override
8848        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8849            return new PackageParser.ServiceIntentInfo[size];
8850        }
8851
8852        @Override
8853        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8854            if (!sUserManager.exists(userId)) return true;
8855            PackageParser.Package p = filter.service.owner;
8856            if (p != null) {
8857                PackageSetting ps = (PackageSetting)p.mExtras;
8858                if (ps != null) {
8859                    // System apps are never considered stopped for purposes of
8860                    // filtering, because there may be no way for the user to
8861                    // actually re-launch them.
8862                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8863                            && ps.getStopped(userId);
8864                }
8865            }
8866            return false;
8867        }
8868
8869        @Override
8870        protected boolean isPackageForFilter(String packageName,
8871                PackageParser.ServiceIntentInfo info) {
8872            return packageName.equals(info.service.owner.packageName);
8873        }
8874
8875        @Override
8876        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8877                int match, int userId) {
8878            if (!sUserManager.exists(userId)) return null;
8879            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8880            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8881                return null;
8882            }
8883            final PackageParser.Service service = info.service;
8884            if (mSafeMode && (service.info.applicationInfo.flags
8885                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8886                return null;
8887            }
8888            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8889            if (ps == null) {
8890                return null;
8891            }
8892            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8893                    ps.readUserState(userId), userId);
8894            if (si == null) {
8895                return null;
8896            }
8897            final ResolveInfo res = new ResolveInfo();
8898            res.serviceInfo = si;
8899            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8900                res.filter = filter;
8901            }
8902            res.priority = info.getPriority();
8903            res.preferredOrder = service.owner.mPreferredOrder;
8904            res.match = match;
8905            res.isDefault = info.hasDefault;
8906            res.labelRes = info.labelRes;
8907            res.nonLocalizedLabel = info.nonLocalizedLabel;
8908            res.icon = info.icon;
8909            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8910            return res;
8911        }
8912
8913        @Override
8914        protected void sortResults(List<ResolveInfo> results) {
8915            Collections.sort(results, mResolvePrioritySorter);
8916        }
8917
8918        @Override
8919        protected void dumpFilter(PrintWriter out, String prefix,
8920                PackageParser.ServiceIntentInfo filter) {
8921            out.print(prefix); out.print(
8922                    Integer.toHexString(System.identityHashCode(filter.service)));
8923                    out.print(' ');
8924                    filter.service.printComponentShortName(out);
8925                    out.print(" filter ");
8926                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8927        }
8928
8929        @Override
8930        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8931            return filter.service;
8932        }
8933
8934        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8935            PackageParser.Service service = (PackageParser.Service)label;
8936            out.print(prefix); out.print(
8937                    Integer.toHexString(System.identityHashCode(service)));
8938                    out.print(' ');
8939                    service.printComponentShortName(out);
8940            if (count > 1) {
8941                out.print(" ("); out.print(count); out.print(" filters)");
8942            }
8943            out.println();
8944        }
8945
8946//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8947//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8948//            final List<ResolveInfo> retList = Lists.newArrayList();
8949//            while (i.hasNext()) {
8950//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8951//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8952//                    retList.add(resolveInfo);
8953//                }
8954//            }
8955//            return retList;
8956//        }
8957
8958        // Keys are String (activity class name), values are Activity.
8959        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8960                = new ArrayMap<ComponentName, PackageParser.Service>();
8961        private int mFlags;
8962    };
8963
8964    private final class ProviderIntentResolver
8965            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8966        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8967                boolean defaultOnly, int userId) {
8968            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8969            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8970        }
8971
8972        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8973                int userId) {
8974            if (!sUserManager.exists(userId))
8975                return null;
8976            mFlags = flags;
8977            return super.queryIntent(intent, resolvedType,
8978                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8979        }
8980
8981        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8982                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8983            if (!sUserManager.exists(userId))
8984                return null;
8985            if (packageProviders == null) {
8986                return null;
8987            }
8988            mFlags = flags;
8989            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8990            final int N = packageProviders.size();
8991            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8992                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8993
8994            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8995            for (int i = 0; i < N; ++i) {
8996                intentFilters = packageProviders.get(i).intents;
8997                if (intentFilters != null && intentFilters.size() > 0) {
8998                    PackageParser.ProviderIntentInfo[] array =
8999                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9000                    intentFilters.toArray(array);
9001                    listCut.add(array);
9002                }
9003            }
9004            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9005        }
9006
9007        public final void addProvider(PackageParser.Provider p) {
9008            if (mProviders.containsKey(p.getComponentName())) {
9009                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9010                return;
9011            }
9012
9013            mProviders.put(p.getComponentName(), p);
9014            if (DEBUG_SHOW_INFO) {
9015                Log.v(TAG, "  "
9016                        + (p.info.nonLocalizedLabel != null
9017                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9018                Log.v(TAG, "    Class=" + p.info.name);
9019            }
9020            final int NI = p.intents.size();
9021            int j;
9022            for (j = 0; j < NI; j++) {
9023                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9024                if (DEBUG_SHOW_INFO) {
9025                    Log.v(TAG, "    IntentFilter:");
9026                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9027                }
9028                if (!intent.debugCheck()) {
9029                    Log.w(TAG, "==> For Provider " + p.info.name);
9030                }
9031                addFilter(intent);
9032            }
9033        }
9034
9035        public final void removeProvider(PackageParser.Provider p) {
9036            mProviders.remove(p.getComponentName());
9037            if (DEBUG_SHOW_INFO) {
9038                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9039                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9040                Log.v(TAG, "    Class=" + p.info.name);
9041            }
9042            final int NI = p.intents.size();
9043            int j;
9044            for (j = 0; j < NI; j++) {
9045                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9046                if (DEBUG_SHOW_INFO) {
9047                    Log.v(TAG, "    IntentFilter:");
9048                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9049                }
9050                removeFilter(intent);
9051            }
9052        }
9053
9054        @Override
9055        protected boolean allowFilterResult(
9056                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9057            ProviderInfo filterPi = filter.provider.info;
9058            for (int i = dest.size() - 1; i >= 0; i--) {
9059                ProviderInfo destPi = dest.get(i).providerInfo;
9060                if (destPi.name == filterPi.name
9061                        && destPi.packageName == filterPi.packageName) {
9062                    return false;
9063                }
9064            }
9065            return true;
9066        }
9067
9068        @Override
9069        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9070            return new PackageParser.ProviderIntentInfo[size];
9071        }
9072
9073        @Override
9074        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9075            if (!sUserManager.exists(userId))
9076                return true;
9077            PackageParser.Package p = filter.provider.owner;
9078            if (p != null) {
9079                PackageSetting ps = (PackageSetting) p.mExtras;
9080                if (ps != null) {
9081                    // System apps are never considered stopped for purposes of
9082                    // filtering, because there may be no way for the user to
9083                    // actually re-launch them.
9084                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9085                            && ps.getStopped(userId);
9086                }
9087            }
9088            return false;
9089        }
9090
9091        @Override
9092        protected boolean isPackageForFilter(String packageName,
9093                PackageParser.ProviderIntentInfo info) {
9094            return packageName.equals(info.provider.owner.packageName);
9095        }
9096
9097        @Override
9098        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9099                int match, int userId) {
9100            if (!sUserManager.exists(userId))
9101                return null;
9102            final PackageParser.ProviderIntentInfo info = filter;
9103            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9104                return null;
9105            }
9106            final PackageParser.Provider provider = info.provider;
9107            if (mSafeMode && (provider.info.applicationInfo.flags
9108                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9109                return null;
9110            }
9111            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9112            if (ps == null) {
9113                return null;
9114            }
9115            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9116                    ps.readUserState(userId), userId);
9117            if (pi == null) {
9118                return null;
9119            }
9120            final ResolveInfo res = new ResolveInfo();
9121            res.providerInfo = pi;
9122            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9123                res.filter = filter;
9124            }
9125            res.priority = info.getPriority();
9126            res.preferredOrder = provider.owner.mPreferredOrder;
9127            res.match = match;
9128            res.isDefault = info.hasDefault;
9129            res.labelRes = info.labelRes;
9130            res.nonLocalizedLabel = info.nonLocalizedLabel;
9131            res.icon = info.icon;
9132            res.system = res.providerInfo.applicationInfo.isSystemApp();
9133            return res;
9134        }
9135
9136        @Override
9137        protected void sortResults(List<ResolveInfo> results) {
9138            Collections.sort(results, mResolvePrioritySorter);
9139        }
9140
9141        @Override
9142        protected void dumpFilter(PrintWriter out, String prefix,
9143                PackageParser.ProviderIntentInfo filter) {
9144            out.print(prefix);
9145            out.print(
9146                    Integer.toHexString(System.identityHashCode(filter.provider)));
9147            out.print(' ');
9148            filter.provider.printComponentShortName(out);
9149            out.print(" filter ");
9150            out.println(Integer.toHexString(System.identityHashCode(filter)));
9151        }
9152
9153        @Override
9154        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9155            return filter.provider;
9156        }
9157
9158        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9159            PackageParser.Provider provider = (PackageParser.Provider)label;
9160            out.print(prefix); out.print(
9161                    Integer.toHexString(System.identityHashCode(provider)));
9162                    out.print(' ');
9163                    provider.printComponentShortName(out);
9164            if (count > 1) {
9165                out.print(" ("); out.print(count); out.print(" filters)");
9166            }
9167            out.println();
9168        }
9169
9170        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9171                = new ArrayMap<ComponentName, PackageParser.Provider>();
9172        private int mFlags;
9173    };
9174
9175    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9176            new Comparator<ResolveInfo>() {
9177        public int compare(ResolveInfo r1, ResolveInfo r2) {
9178            int v1 = r1.priority;
9179            int v2 = r2.priority;
9180            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9181            if (v1 != v2) {
9182                return (v1 > v2) ? -1 : 1;
9183            }
9184            v1 = r1.preferredOrder;
9185            v2 = r2.preferredOrder;
9186            if (v1 != v2) {
9187                return (v1 > v2) ? -1 : 1;
9188            }
9189            if (r1.isDefault != r2.isDefault) {
9190                return r1.isDefault ? -1 : 1;
9191            }
9192            v1 = r1.match;
9193            v2 = r2.match;
9194            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9195            if (v1 != v2) {
9196                return (v1 > v2) ? -1 : 1;
9197            }
9198            if (r1.system != r2.system) {
9199                return r1.system ? -1 : 1;
9200            }
9201            return 0;
9202        }
9203    };
9204
9205    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9206            new Comparator<ProviderInfo>() {
9207        public int compare(ProviderInfo p1, ProviderInfo p2) {
9208            final int v1 = p1.initOrder;
9209            final int v2 = p2.initOrder;
9210            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9211        }
9212    };
9213
9214    final void sendPackageBroadcast(final String action, final String pkg,
9215            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9216            final int[] userIds) {
9217        mHandler.post(new Runnable() {
9218            @Override
9219            public void run() {
9220                try {
9221                    final IActivityManager am = ActivityManagerNative.getDefault();
9222                    if (am == null) return;
9223                    final int[] resolvedUserIds;
9224                    if (userIds == null) {
9225                        resolvedUserIds = am.getRunningUserIds();
9226                    } else {
9227                        resolvedUserIds = userIds;
9228                    }
9229                    for (int id : resolvedUserIds) {
9230                        final Intent intent = new Intent(action,
9231                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9232                        if (extras != null) {
9233                            intent.putExtras(extras);
9234                        }
9235                        if (targetPkg != null) {
9236                            intent.setPackage(targetPkg);
9237                        }
9238                        // Modify the UID when posting to other users
9239                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9240                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9241                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9242                            intent.putExtra(Intent.EXTRA_UID, uid);
9243                        }
9244                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9245                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9246                        if (DEBUG_BROADCASTS) {
9247                            RuntimeException here = new RuntimeException("here");
9248                            here.fillInStackTrace();
9249                            Slog.d(TAG, "Sending to user " + id + ": "
9250                                    + intent.toShortString(false, true, false, false)
9251                                    + " " + intent.getExtras(), here);
9252                        }
9253                        am.broadcastIntent(null, intent, null, finishedReceiver,
9254                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9255                                null, finishedReceiver != null, false, id);
9256                    }
9257                } catch (RemoteException ex) {
9258                }
9259            }
9260        });
9261    }
9262
9263    /**
9264     * Check if the external storage media is available. This is true if there
9265     * is a mounted external storage medium or if the external storage is
9266     * emulated.
9267     */
9268    private boolean isExternalMediaAvailable() {
9269        return mMediaMounted || Environment.isExternalStorageEmulated();
9270    }
9271
9272    @Override
9273    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9274        // writer
9275        synchronized (mPackages) {
9276            if (!isExternalMediaAvailable()) {
9277                // If the external storage is no longer mounted at this point,
9278                // the caller may not have been able to delete all of this
9279                // packages files and can not delete any more.  Bail.
9280                return null;
9281            }
9282            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9283            if (lastPackage != null) {
9284                pkgs.remove(lastPackage);
9285            }
9286            if (pkgs.size() > 0) {
9287                return pkgs.get(0);
9288            }
9289        }
9290        return null;
9291    }
9292
9293    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9294        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9295                userId, andCode ? 1 : 0, packageName);
9296        if (mSystemReady) {
9297            msg.sendToTarget();
9298        } else {
9299            if (mPostSystemReadyMessages == null) {
9300                mPostSystemReadyMessages = new ArrayList<>();
9301            }
9302            mPostSystemReadyMessages.add(msg);
9303        }
9304    }
9305
9306    void startCleaningPackages() {
9307        // reader
9308        synchronized (mPackages) {
9309            if (!isExternalMediaAvailable()) {
9310                return;
9311            }
9312            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9313                return;
9314            }
9315        }
9316        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9317        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9318        IActivityManager am = ActivityManagerNative.getDefault();
9319        if (am != null) {
9320            try {
9321                am.startService(null, intent, null, mContext.getOpPackageName(),
9322                        UserHandle.USER_OWNER);
9323            } catch (RemoteException e) {
9324            }
9325        }
9326    }
9327
9328    @Override
9329    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9330            int installFlags, String installerPackageName, VerificationParams verificationParams,
9331            String packageAbiOverride) {
9332        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9333                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9334    }
9335
9336    @Override
9337    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9338            int installFlags, String installerPackageName, VerificationParams verificationParams,
9339            String packageAbiOverride, int userId) {
9340        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9341
9342        final int callingUid = Binder.getCallingUid();
9343        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9344
9345        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9346            try {
9347                if (observer != null) {
9348                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9349                }
9350            } catch (RemoteException re) {
9351            }
9352            return;
9353        }
9354
9355        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9356            installFlags |= PackageManager.INSTALL_FROM_ADB;
9357
9358        } else {
9359            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9360            // about installerPackageName.
9361
9362            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9363            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9364        }
9365
9366        UserHandle user;
9367        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9368            user = UserHandle.ALL;
9369        } else {
9370            user = new UserHandle(userId);
9371        }
9372
9373        // Only system components can circumvent runtime permissions when installing.
9374        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9375                && mContext.checkCallingOrSelfPermission(Manifest.permission
9376                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9377            throw new SecurityException("You need the "
9378                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9379                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9380        }
9381
9382        verificationParams.setInstallerUid(callingUid);
9383
9384        final File originFile = new File(originPath);
9385        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9386
9387        final Message msg = mHandler.obtainMessage(INIT_COPY);
9388        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9389                null, verificationParams, user, packageAbiOverride);
9390        mHandler.sendMessage(msg);
9391    }
9392
9393    void installStage(String packageName, File stagedDir, String stagedCid,
9394            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9395            String installerPackageName, int installerUid, UserHandle user) {
9396        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9397                params.referrerUri, installerUid, null);
9398        verifParams.setInstallerUid(installerUid);
9399
9400        final OriginInfo origin;
9401        if (stagedDir != null) {
9402            origin = OriginInfo.fromStagedFile(stagedDir);
9403        } else {
9404            origin = OriginInfo.fromStagedContainer(stagedCid);
9405        }
9406
9407        final Message msg = mHandler.obtainMessage(INIT_COPY);
9408        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9409                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9410        mHandler.sendMessage(msg);
9411    }
9412
9413    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9414        Bundle extras = new Bundle(1);
9415        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9416
9417        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9418                packageName, extras, null, null, new int[] {userId});
9419        try {
9420            IActivityManager am = ActivityManagerNative.getDefault();
9421            final boolean isSystem =
9422                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9423            if (isSystem && am.isUserRunning(userId, false)) {
9424                // The just-installed/enabled app is bundled on the system, so presumed
9425                // to be able to run automatically without needing an explicit launch.
9426                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9427                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9428                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9429                        .setPackage(packageName);
9430                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9431                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9432            }
9433        } catch (RemoteException e) {
9434            // shouldn't happen
9435            Slog.w(TAG, "Unable to bootstrap installed package", e);
9436        }
9437    }
9438
9439    @Override
9440    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9441            int userId) {
9442        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9443        PackageSetting pkgSetting;
9444        final int uid = Binder.getCallingUid();
9445        enforceCrossUserPermission(uid, userId, true, true,
9446                "setApplicationHiddenSetting for user " + userId);
9447
9448        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9449            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9450            return false;
9451        }
9452
9453        long callingId = Binder.clearCallingIdentity();
9454        try {
9455            boolean sendAdded = false;
9456            boolean sendRemoved = false;
9457            // writer
9458            synchronized (mPackages) {
9459                pkgSetting = mSettings.mPackages.get(packageName);
9460                if (pkgSetting == null) {
9461                    return false;
9462                }
9463                if (pkgSetting.getHidden(userId) != hidden) {
9464                    pkgSetting.setHidden(hidden, userId);
9465                    mSettings.writePackageRestrictionsLPr(userId);
9466                    if (hidden) {
9467                        sendRemoved = true;
9468                    } else {
9469                        sendAdded = true;
9470                    }
9471                }
9472            }
9473            if (sendAdded) {
9474                sendPackageAddedForUser(packageName, pkgSetting, userId);
9475                return true;
9476            }
9477            if (sendRemoved) {
9478                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9479                        "hiding pkg");
9480                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9481            }
9482        } finally {
9483            Binder.restoreCallingIdentity(callingId);
9484        }
9485        return false;
9486    }
9487
9488    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9489            int userId) {
9490        final PackageRemovedInfo info = new PackageRemovedInfo();
9491        info.removedPackage = packageName;
9492        info.removedUsers = new int[] {userId};
9493        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9494        info.sendBroadcast(false, false, false);
9495    }
9496
9497    /**
9498     * Returns true if application is not found or there was an error. Otherwise it returns
9499     * the hidden state of the package for the given user.
9500     */
9501    @Override
9502    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9503        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9504        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9505                false, "getApplicationHidden for user " + userId);
9506        PackageSetting pkgSetting;
9507        long callingId = Binder.clearCallingIdentity();
9508        try {
9509            // writer
9510            synchronized (mPackages) {
9511                pkgSetting = mSettings.mPackages.get(packageName);
9512                if (pkgSetting == null) {
9513                    return true;
9514                }
9515                return pkgSetting.getHidden(userId);
9516            }
9517        } finally {
9518            Binder.restoreCallingIdentity(callingId);
9519        }
9520    }
9521
9522    /**
9523     * @hide
9524     */
9525    @Override
9526    public int installExistingPackageAsUser(String packageName, int userId) {
9527        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9528                null);
9529        PackageSetting pkgSetting;
9530        final int uid = Binder.getCallingUid();
9531        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9532                + userId);
9533        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9534            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9535        }
9536
9537        long callingId = Binder.clearCallingIdentity();
9538        try {
9539            boolean sendAdded = false;
9540
9541            // writer
9542            synchronized (mPackages) {
9543                pkgSetting = mSettings.mPackages.get(packageName);
9544                if (pkgSetting == null) {
9545                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9546                }
9547                if (!pkgSetting.getInstalled(userId)) {
9548                    pkgSetting.setInstalled(true, userId);
9549                    pkgSetting.setHidden(false, userId);
9550                    mSettings.writePackageRestrictionsLPr(userId);
9551                    sendAdded = true;
9552                }
9553            }
9554
9555            if (sendAdded) {
9556                sendPackageAddedForUser(packageName, pkgSetting, userId);
9557            }
9558        } finally {
9559            Binder.restoreCallingIdentity(callingId);
9560        }
9561
9562        return PackageManager.INSTALL_SUCCEEDED;
9563    }
9564
9565    boolean isUserRestricted(int userId, String restrictionKey) {
9566        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9567        if (restrictions.getBoolean(restrictionKey, false)) {
9568            Log.w(TAG, "User is restricted: " + restrictionKey);
9569            return true;
9570        }
9571        return false;
9572    }
9573
9574    @Override
9575    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9576        mContext.enforceCallingOrSelfPermission(
9577                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9578                "Only package verification agents can verify applications");
9579
9580        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9581        final PackageVerificationResponse response = new PackageVerificationResponse(
9582                verificationCode, Binder.getCallingUid());
9583        msg.arg1 = id;
9584        msg.obj = response;
9585        mHandler.sendMessage(msg);
9586    }
9587
9588    @Override
9589    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9590            long millisecondsToDelay) {
9591        mContext.enforceCallingOrSelfPermission(
9592                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9593                "Only package verification agents can extend verification timeouts");
9594
9595        final PackageVerificationState state = mPendingVerification.get(id);
9596        final PackageVerificationResponse response = new PackageVerificationResponse(
9597                verificationCodeAtTimeout, Binder.getCallingUid());
9598
9599        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9600            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9601        }
9602        if (millisecondsToDelay < 0) {
9603            millisecondsToDelay = 0;
9604        }
9605        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9606                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9607            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9608        }
9609
9610        if ((state != null) && !state.timeoutExtended()) {
9611            state.extendTimeout();
9612
9613            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9614            msg.arg1 = id;
9615            msg.obj = response;
9616            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9617        }
9618    }
9619
9620    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9621            int verificationCode, UserHandle user) {
9622        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9623        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9624        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9625        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9626        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9627
9628        mContext.sendBroadcastAsUser(intent, user,
9629                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9630    }
9631
9632    private ComponentName matchComponentForVerifier(String packageName,
9633            List<ResolveInfo> receivers) {
9634        ActivityInfo targetReceiver = null;
9635
9636        final int NR = receivers.size();
9637        for (int i = 0; i < NR; i++) {
9638            final ResolveInfo info = receivers.get(i);
9639            if (info.activityInfo == null) {
9640                continue;
9641            }
9642
9643            if (packageName.equals(info.activityInfo.packageName)) {
9644                targetReceiver = info.activityInfo;
9645                break;
9646            }
9647        }
9648
9649        if (targetReceiver == null) {
9650            return null;
9651        }
9652
9653        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9654    }
9655
9656    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9657            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9658        if (pkgInfo.verifiers.length == 0) {
9659            return null;
9660        }
9661
9662        final int N = pkgInfo.verifiers.length;
9663        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9664        for (int i = 0; i < N; i++) {
9665            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9666
9667            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9668                    receivers);
9669            if (comp == null) {
9670                continue;
9671            }
9672
9673            final int verifierUid = getUidForVerifier(verifierInfo);
9674            if (verifierUid == -1) {
9675                continue;
9676            }
9677
9678            if (DEBUG_VERIFY) {
9679                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9680                        + " with the correct signature");
9681            }
9682            sufficientVerifiers.add(comp);
9683            verificationState.addSufficientVerifier(verifierUid);
9684        }
9685
9686        return sufficientVerifiers;
9687    }
9688
9689    private int getUidForVerifier(VerifierInfo verifierInfo) {
9690        synchronized (mPackages) {
9691            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9692            if (pkg == null) {
9693                return -1;
9694            } else if (pkg.mSignatures.length != 1) {
9695                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9696                        + " has more than one signature; ignoring");
9697                return -1;
9698            }
9699
9700            /*
9701             * If the public key of the package's signature does not match
9702             * our expected public key, then this is a different package and
9703             * we should skip.
9704             */
9705
9706            final byte[] expectedPublicKey;
9707            try {
9708                final Signature verifierSig = pkg.mSignatures[0];
9709                final PublicKey publicKey = verifierSig.getPublicKey();
9710                expectedPublicKey = publicKey.getEncoded();
9711            } catch (CertificateException e) {
9712                return -1;
9713            }
9714
9715            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9716
9717            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9718                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9719                        + " does not have the expected public key; ignoring");
9720                return -1;
9721            }
9722
9723            return pkg.applicationInfo.uid;
9724        }
9725    }
9726
9727    @Override
9728    public void finishPackageInstall(int token) {
9729        enforceSystemOrRoot("Only the system is allowed to finish installs");
9730
9731        if (DEBUG_INSTALL) {
9732            Slog.v(TAG, "BM finishing package install for " + token);
9733        }
9734
9735        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9736        mHandler.sendMessage(msg);
9737    }
9738
9739    /**
9740     * Get the verification agent timeout.
9741     *
9742     * @return verification timeout in milliseconds
9743     */
9744    private long getVerificationTimeout() {
9745        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9746                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9747                DEFAULT_VERIFICATION_TIMEOUT);
9748    }
9749
9750    /**
9751     * Get the default verification agent response code.
9752     *
9753     * @return default verification response code
9754     */
9755    private int getDefaultVerificationResponse() {
9756        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9757                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9758                DEFAULT_VERIFICATION_RESPONSE);
9759    }
9760
9761    /**
9762     * Check whether or not package verification has been enabled.
9763     *
9764     * @return true if verification should be performed
9765     */
9766    private boolean isVerificationEnabled(int userId, int installFlags) {
9767        if (!DEFAULT_VERIFY_ENABLE) {
9768            return false;
9769        }
9770
9771        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9772
9773        // Check if installing from ADB
9774        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9775            // Do not run verification in a test harness environment
9776            if (ActivityManager.isRunningInTestHarness()) {
9777                return false;
9778            }
9779            if (ensureVerifyAppsEnabled) {
9780                return true;
9781            }
9782            // Check if the developer does not want package verification for ADB installs
9783            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9784                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9785                return false;
9786            }
9787        }
9788
9789        if (ensureVerifyAppsEnabled) {
9790            return true;
9791        }
9792
9793        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9794                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9795    }
9796
9797    @Override
9798    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9799            throws RemoteException {
9800        mContext.enforceCallingOrSelfPermission(
9801                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9802                "Only intentfilter verification agents can verify applications");
9803
9804        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9805        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9806                Binder.getCallingUid(), verificationCode, failedDomains);
9807        msg.arg1 = id;
9808        msg.obj = response;
9809        mHandler.sendMessage(msg);
9810    }
9811
9812    @Override
9813    public int getIntentVerificationStatus(String packageName, int userId) {
9814        synchronized (mPackages) {
9815            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9816        }
9817    }
9818
9819    @Override
9820    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9821        mContext.enforceCallingOrSelfPermission(
9822                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9823
9824        boolean result = false;
9825        synchronized (mPackages) {
9826            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9827        }
9828        if (result) {
9829            scheduleWritePackageRestrictionsLocked(userId);
9830        }
9831        return result;
9832    }
9833
9834    @Override
9835    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9836        synchronized (mPackages) {
9837            return mSettings.getIntentFilterVerificationsLPr(packageName);
9838        }
9839    }
9840
9841    @Override
9842    public List<IntentFilter> getAllIntentFilters(String packageName) {
9843        if (TextUtils.isEmpty(packageName)) {
9844            return Collections.<IntentFilter>emptyList();
9845        }
9846        synchronized (mPackages) {
9847            PackageParser.Package pkg = mPackages.get(packageName);
9848            if (pkg == null || pkg.activities == null) {
9849                return Collections.<IntentFilter>emptyList();
9850            }
9851            final int count = pkg.activities.size();
9852            ArrayList<IntentFilter> result = new ArrayList<>();
9853            for (int n=0; n<count; n++) {
9854                PackageParser.Activity activity = pkg.activities.get(n);
9855                if (activity.intents != null || activity.intents.size() > 0) {
9856                    result.addAll(activity.intents);
9857                }
9858            }
9859            return result;
9860        }
9861    }
9862
9863    @Override
9864    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9865        mContext.enforceCallingOrSelfPermission(
9866                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9867
9868        synchronized (mPackages) {
9869            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9870            if (packageName != null) {
9871                result |= updateIntentVerificationStatus(packageName,
9872                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9873                        UserHandle.myUserId());
9874                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9875                        packageName, userId);
9876            }
9877            return result;
9878        }
9879    }
9880
9881    @Override
9882    public String getDefaultBrowserPackageName(int userId) {
9883        synchronized (mPackages) {
9884            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9885        }
9886    }
9887
9888    /**
9889     * Get the "allow unknown sources" setting.
9890     *
9891     * @return the current "allow unknown sources" setting
9892     */
9893    private int getUnknownSourcesSettings() {
9894        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9895                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9896                -1);
9897    }
9898
9899    @Override
9900    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9901        final int uid = Binder.getCallingUid();
9902        // writer
9903        synchronized (mPackages) {
9904            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9905            if (targetPackageSetting == null) {
9906                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9907            }
9908
9909            PackageSetting installerPackageSetting;
9910            if (installerPackageName != null) {
9911                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9912                if (installerPackageSetting == null) {
9913                    throw new IllegalArgumentException("Unknown installer package: "
9914                            + installerPackageName);
9915                }
9916            } else {
9917                installerPackageSetting = null;
9918            }
9919
9920            Signature[] callerSignature;
9921            Object obj = mSettings.getUserIdLPr(uid);
9922            if (obj != null) {
9923                if (obj instanceof SharedUserSetting) {
9924                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9925                } else if (obj instanceof PackageSetting) {
9926                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9927                } else {
9928                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9929                }
9930            } else {
9931                throw new SecurityException("Unknown calling uid " + uid);
9932            }
9933
9934            // Verify: can't set installerPackageName to a package that is
9935            // not signed with the same cert as the caller.
9936            if (installerPackageSetting != null) {
9937                if (compareSignatures(callerSignature,
9938                        installerPackageSetting.signatures.mSignatures)
9939                        != PackageManager.SIGNATURE_MATCH) {
9940                    throw new SecurityException(
9941                            "Caller does not have same cert as new installer package "
9942                            + installerPackageName);
9943                }
9944            }
9945
9946            // Verify: if target already has an installer package, it must
9947            // be signed with the same cert as the caller.
9948            if (targetPackageSetting.installerPackageName != null) {
9949                PackageSetting setting = mSettings.mPackages.get(
9950                        targetPackageSetting.installerPackageName);
9951                // If the currently set package isn't valid, then it's always
9952                // okay to change it.
9953                if (setting != null) {
9954                    if (compareSignatures(callerSignature,
9955                            setting.signatures.mSignatures)
9956                            != PackageManager.SIGNATURE_MATCH) {
9957                        throw new SecurityException(
9958                                "Caller does not have same cert as old installer package "
9959                                + targetPackageSetting.installerPackageName);
9960                    }
9961                }
9962            }
9963
9964            // Okay!
9965            targetPackageSetting.installerPackageName = installerPackageName;
9966            scheduleWriteSettingsLocked();
9967        }
9968    }
9969
9970    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9971        // Queue up an async operation since the package installation may take a little while.
9972        mHandler.post(new Runnable() {
9973            public void run() {
9974                mHandler.removeCallbacks(this);
9975                 // Result object to be returned
9976                PackageInstalledInfo res = new PackageInstalledInfo();
9977                res.returnCode = currentStatus;
9978                res.uid = -1;
9979                res.pkg = null;
9980                res.removedInfo = new PackageRemovedInfo();
9981                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9982                    args.doPreInstall(res.returnCode);
9983                    synchronized (mInstallLock) {
9984                        installPackageLI(args, res);
9985                    }
9986                    args.doPostInstall(res.returnCode, res.uid);
9987                }
9988
9989                // A restore should be performed at this point if (a) the install
9990                // succeeded, (b) the operation is not an update, and (c) the new
9991                // package has not opted out of backup participation.
9992                final boolean update = res.removedInfo.removedPackage != null;
9993                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9994                boolean doRestore = !update
9995                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9996
9997                // Set up the post-install work request bookkeeping.  This will be used
9998                // and cleaned up by the post-install event handling regardless of whether
9999                // there's a restore pass performed.  Token values are >= 1.
10000                int token;
10001                if (mNextInstallToken < 0) mNextInstallToken = 1;
10002                token = mNextInstallToken++;
10003
10004                PostInstallData data = new PostInstallData(args, res);
10005                mRunningInstalls.put(token, data);
10006                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10007
10008                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10009                    // Pass responsibility to the Backup Manager.  It will perform a
10010                    // restore if appropriate, then pass responsibility back to the
10011                    // Package Manager to run the post-install observer callbacks
10012                    // and broadcasts.
10013                    IBackupManager bm = IBackupManager.Stub.asInterface(
10014                            ServiceManager.getService(Context.BACKUP_SERVICE));
10015                    if (bm != null) {
10016                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10017                                + " to BM for possible restore");
10018                        try {
10019                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10020                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10021                            } else {
10022                                doRestore = false;
10023                            }
10024                        } catch (RemoteException e) {
10025                            // can't happen; the backup manager is local
10026                        } catch (Exception e) {
10027                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10028                            doRestore = false;
10029                        }
10030                    } else {
10031                        Slog.e(TAG, "Backup Manager not found!");
10032                        doRestore = false;
10033                    }
10034                }
10035
10036                if (!doRestore) {
10037                    // No restore possible, or the Backup Manager was mysteriously not
10038                    // available -- just fire the post-install work request directly.
10039                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10040                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10041                    mHandler.sendMessage(msg);
10042                }
10043            }
10044        });
10045    }
10046
10047    private abstract class HandlerParams {
10048        private static final int MAX_RETRIES = 4;
10049
10050        /**
10051         * Number of times startCopy() has been attempted and had a non-fatal
10052         * error.
10053         */
10054        private int mRetries = 0;
10055
10056        /** User handle for the user requesting the information or installation. */
10057        private final UserHandle mUser;
10058
10059        HandlerParams(UserHandle user) {
10060            mUser = user;
10061        }
10062
10063        UserHandle getUser() {
10064            return mUser;
10065        }
10066
10067        final boolean startCopy() {
10068            boolean res;
10069            try {
10070                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10071
10072                if (++mRetries > MAX_RETRIES) {
10073                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10074                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10075                    handleServiceError();
10076                    return false;
10077                } else {
10078                    handleStartCopy();
10079                    res = true;
10080                }
10081            } catch (RemoteException e) {
10082                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10083                mHandler.sendEmptyMessage(MCS_RECONNECT);
10084                res = false;
10085            }
10086            handleReturnCode();
10087            return res;
10088        }
10089
10090        final void serviceError() {
10091            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10092            handleServiceError();
10093            handleReturnCode();
10094        }
10095
10096        abstract void handleStartCopy() throws RemoteException;
10097        abstract void handleServiceError();
10098        abstract void handleReturnCode();
10099    }
10100
10101    class MeasureParams extends HandlerParams {
10102        private final PackageStats mStats;
10103        private boolean mSuccess;
10104
10105        private final IPackageStatsObserver mObserver;
10106
10107        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10108            super(new UserHandle(stats.userHandle));
10109            mObserver = observer;
10110            mStats = stats;
10111        }
10112
10113        @Override
10114        public String toString() {
10115            return "MeasureParams{"
10116                + Integer.toHexString(System.identityHashCode(this))
10117                + " " + mStats.packageName + "}";
10118        }
10119
10120        @Override
10121        void handleStartCopy() throws RemoteException {
10122            synchronized (mInstallLock) {
10123                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10124            }
10125
10126            if (mSuccess) {
10127                final boolean mounted;
10128                if (Environment.isExternalStorageEmulated()) {
10129                    mounted = true;
10130                } else {
10131                    final String status = Environment.getExternalStorageState();
10132                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10133                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10134                }
10135
10136                if (mounted) {
10137                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10138
10139                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10140                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10141
10142                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10143                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10144
10145                    // Always subtract cache size, since it's a subdirectory
10146                    mStats.externalDataSize -= mStats.externalCacheSize;
10147
10148                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10149                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10150
10151                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10152                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10153                }
10154            }
10155        }
10156
10157        @Override
10158        void handleReturnCode() {
10159            if (mObserver != null) {
10160                try {
10161                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10162                } catch (RemoteException e) {
10163                    Slog.i(TAG, "Observer no longer exists.");
10164                }
10165            }
10166        }
10167
10168        @Override
10169        void handleServiceError() {
10170            Slog.e(TAG, "Could not measure application " + mStats.packageName
10171                            + " external storage");
10172        }
10173    }
10174
10175    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10176            throws RemoteException {
10177        long result = 0;
10178        for (File path : paths) {
10179            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10180        }
10181        return result;
10182    }
10183
10184    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10185        for (File path : paths) {
10186            try {
10187                mcs.clearDirectory(path.getAbsolutePath());
10188            } catch (RemoteException e) {
10189            }
10190        }
10191    }
10192
10193    static class OriginInfo {
10194        /**
10195         * Location where install is coming from, before it has been
10196         * copied/renamed into place. This could be a single monolithic APK
10197         * file, or a cluster directory. This location may be untrusted.
10198         */
10199        final File file;
10200        final String cid;
10201
10202        /**
10203         * Flag indicating that {@link #file} or {@link #cid} has already been
10204         * staged, meaning downstream users don't need to defensively copy the
10205         * contents.
10206         */
10207        final boolean staged;
10208
10209        /**
10210         * Flag indicating that {@link #file} or {@link #cid} is an already
10211         * installed app that is being moved.
10212         */
10213        final boolean existing;
10214
10215        final String resolvedPath;
10216        final File resolvedFile;
10217
10218        static OriginInfo fromNothing() {
10219            return new OriginInfo(null, null, false, false);
10220        }
10221
10222        static OriginInfo fromUntrustedFile(File file) {
10223            return new OriginInfo(file, null, false, false);
10224        }
10225
10226        static OriginInfo fromExistingFile(File file) {
10227            return new OriginInfo(file, null, false, true);
10228        }
10229
10230        static OriginInfo fromStagedFile(File file) {
10231            return new OriginInfo(file, null, true, false);
10232        }
10233
10234        static OriginInfo fromStagedContainer(String cid) {
10235            return new OriginInfo(null, cid, true, false);
10236        }
10237
10238        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10239            this.file = file;
10240            this.cid = cid;
10241            this.staged = staged;
10242            this.existing = existing;
10243
10244            if (cid != null) {
10245                resolvedPath = PackageHelper.getSdDir(cid);
10246                resolvedFile = new File(resolvedPath);
10247            } else if (file != null) {
10248                resolvedPath = file.getAbsolutePath();
10249                resolvedFile = file;
10250            } else {
10251                resolvedPath = null;
10252                resolvedFile = null;
10253            }
10254        }
10255    }
10256
10257    class MoveInfo {
10258        final int moveId;
10259        final String fromUuid;
10260        final String toUuid;
10261        final String packageName;
10262        final String dataAppName;
10263        final int appId;
10264        final String seinfo;
10265
10266        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10267                String dataAppName, int appId, String seinfo) {
10268            this.moveId = moveId;
10269            this.fromUuid = fromUuid;
10270            this.toUuid = toUuid;
10271            this.packageName = packageName;
10272            this.dataAppName = dataAppName;
10273            this.appId = appId;
10274            this.seinfo = seinfo;
10275        }
10276    }
10277
10278    class InstallParams extends HandlerParams {
10279        final OriginInfo origin;
10280        final MoveInfo move;
10281        final IPackageInstallObserver2 observer;
10282        int installFlags;
10283        final String installerPackageName;
10284        final String volumeUuid;
10285        final VerificationParams verificationParams;
10286        private InstallArgs mArgs;
10287        private int mRet;
10288        final String packageAbiOverride;
10289
10290        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10291                int installFlags, String installerPackageName, String volumeUuid,
10292                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10293            super(user);
10294            this.origin = origin;
10295            this.move = move;
10296            this.observer = observer;
10297            this.installFlags = installFlags;
10298            this.installerPackageName = installerPackageName;
10299            this.volumeUuid = volumeUuid;
10300            this.verificationParams = verificationParams;
10301            this.packageAbiOverride = packageAbiOverride;
10302        }
10303
10304        @Override
10305        public String toString() {
10306            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10307                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10308        }
10309
10310        public ManifestDigest getManifestDigest() {
10311            if (verificationParams == null) {
10312                return null;
10313            }
10314            return verificationParams.getManifestDigest();
10315        }
10316
10317        private int installLocationPolicy(PackageInfoLite pkgLite) {
10318            String packageName = pkgLite.packageName;
10319            int installLocation = pkgLite.installLocation;
10320            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10321            // reader
10322            synchronized (mPackages) {
10323                PackageParser.Package pkg = mPackages.get(packageName);
10324                if (pkg != null) {
10325                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10326                        // Check for downgrading.
10327                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10328                            try {
10329                                checkDowngrade(pkg, pkgLite);
10330                            } catch (PackageManagerException e) {
10331                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10332                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10333                            }
10334                        }
10335                        // Check for updated system application.
10336                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10337                            if (onSd) {
10338                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10339                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10340                            }
10341                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10342                        } else {
10343                            if (onSd) {
10344                                // Install flag overrides everything.
10345                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10346                            }
10347                            // If current upgrade specifies particular preference
10348                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10349                                // Application explicitly specified internal.
10350                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10351                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10352                                // App explictly prefers external. Let policy decide
10353                            } else {
10354                                // Prefer previous location
10355                                if (isExternal(pkg)) {
10356                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10357                                }
10358                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10359                            }
10360                        }
10361                    } else {
10362                        // Invalid install. Return error code
10363                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10364                    }
10365                }
10366            }
10367            // All the special cases have been taken care of.
10368            // Return result based on recommended install location.
10369            if (onSd) {
10370                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10371            }
10372            return pkgLite.recommendedInstallLocation;
10373        }
10374
10375        /*
10376         * Invoke remote method to get package information and install
10377         * location values. Override install location based on default
10378         * policy if needed and then create install arguments based
10379         * on the install location.
10380         */
10381        public void handleStartCopy() throws RemoteException {
10382            int ret = PackageManager.INSTALL_SUCCEEDED;
10383
10384            // If we're already staged, we've firmly committed to an install location
10385            if (origin.staged) {
10386                if (origin.file != null) {
10387                    installFlags |= PackageManager.INSTALL_INTERNAL;
10388                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10389                } else if (origin.cid != null) {
10390                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10391                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10392                } else {
10393                    throw new IllegalStateException("Invalid stage location");
10394                }
10395            }
10396
10397            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10398            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10399
10400            PackageInfoLite pkgLite = null;
10401
10402            if (onInt && onSd) {
10403                // Check if both bits are set.
10404                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10405                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10406            } else {
10407                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10408                        packageAbiOverride);
10409
10410                /*
10411                 * If we have too little free space, try to free cache
10412                 * before giving up.
10413                 */
10414                if (!origin.staged && pkgLite.recommendedInstallLocation
10415                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10416                    // TODO: focus freeing disk space on the target device
10417                    final StorageManager storage = StorageManager.from(mContext);
10418                    final long lowThreshold = storage.getStorageLowBytes(
10419                            Environment.getDataDirectory());
10420
10421                    final long sizeBytes = mContainerService.calculateInstalledSize(
10422                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10423
10424                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10425                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10426                                installFlags, packageAbiOverride);
10427                    }
10428
10429                    /*
10430                     * The cache free must have deleted the file we
10431                     * downloaded to install.
10432                     *
10433                     * TODO: fix the "freeCache" call to not delete
10434                     *       the file we care about.
10435                     */
10436                    if (pkgLite.recommendedInstallLocation
10437                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10438                        pkgLite.recommendedInstallLocation
10439                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10440                    }
10441                }
10442            }
10443
10444            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10445                int loc = pkgLite.recommendedInstallLocation;
10446                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10447                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10448                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10449                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10450                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10451                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10452                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10453                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10454                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10455                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10456                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10457                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10458                } else {
10459                    // Override with defaults if needed.
10460                    loc = installLocationPolicy(pkgLite);
10461                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10462                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10463                    } else if (!onSd && !onInt) {
10464                        // Override install location with flags
10465                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10466                            // Set the flag to install on external media.
10467                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10468                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10469                        } else {
10470                            // Make sure the flag for installing on external
10471                            // media is unset
10472                            installFlags |= PackageManager.INSTALL_INTERNAL;
10473                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10474                        }
10475                    }
10476                }
10477            }
10478
10479            final InstallArgs args = createInstallArgs(this);
10480            mArgs = args;
10481
10482            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10483                 /*
10484                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10485                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10486                 */
10487                int userIdentifier = getUser().getIdentifier();
10488                if (userIdentifier == UserHandle.USER_ALL
10489                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10490                    userIdentifier = UserHandle.USER_OWNER;
10491                }
10492
10493                /*
10494                 * Determine if we have any installed package verifiers. If we
10495                 * do, then we'll defer to them to verify the packages.
10496                 */
10497                final int requiredUid = mRequiredVerifierPackage == null ? -1
10498                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10499                if (!origin.existing && requiredUid != -1
10500                        && isVerificationEnabled(userIdentifier, installFlags)) {
10501                    final Intent verification = new Intent(
10502                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10503                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10504                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10505                            PACKAGE_MIME_TYPE);
10506                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10507
10508                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10509                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10510                            0 /* TODO: Which userId? */);
10511
10512                    if (DEBUG_VERIFY) {
10513                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10514                                + verification.toString() + " with " + pkgLite.verifiers.length
10515                                + " optional verifiers");
10516                    }
10517
10518                    final int verificationId = mPendingVerificationToken++;
10519
10520                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10521
10522                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10523                            installerPackageName);
10524
10525                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10526                            installFlags);
10527
10528                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10529                            pkgLite.packageName);
10530
10531                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10532                            pkgLite.versionCode);
10533
10534                    if (verificationParams != null) {
10535                        if (verificationParams.getVerificationURI() != null) {
10536                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10537                                 verificationParams.getVerificationURI());
10538                        }
10539                        if (verificationParams.getOriginatingURI() != null) {
10540                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10541                                  verificationParams.getOriginatingURI());
10542                        }
10543                        if (verificationParams.getReferrer() != null) {
10544                            verification.putExtra(Intent.EXTRA_REFERRER,
10545                                  verificationParams.getReferrer());
10546                        }
10547                        if (verificationParams.getOriginatingUid() >= 0) {
10548                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10549                                  verificationParams.getOriginatingUid());
10550                        }
10551                        if (verificationParams.getInstallerUid() >= 0) {
10552                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10553                                  verificationParams.getInstallerUid());
10554                        }
10555                    }
10556
10557                    final PackageVerificationState verificationState = new PackageVerificationState(
10558                            requiredUid, args);
10559
10560                    mPendingVerification.append(verificationId, verificationState);
10561
10562                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10563                            receivers, verificationState);
10564
10565                    /*
10566                     * If any sufficient verifiers were listed in the package
10567                     * manifest, attempt to ask them.
10568                     */
10569                    if (sufficientVerifiers != null) {
10570                        final int N = sufficientVerifiers.size();
10571                        if (N == 0) {
10572                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10573                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10574                        } else {
10575                            for (int i = 0; i < N; i++) {
10576                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10577
10578                                final Intent sufficientIntent = new Intent(verification);
10579                                sufficientIntent.setComponent(verifierComponent);
10580
10581                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10582                            }
10583                        }
10584                    }
10585
10586                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10587                            mRequiredVerifierPackage, receivers);
10588                    if (ret == PackageManager.INSTALL_SUCCEEDED
10589                            && mRequiredVerifierPackage != null) {
10590                        /*
10591                         * Send the intent to the required verification agent,
10592                         * but only start the verification timeout after the
10593                         * target BroadcastReceivers have run.
10594                         */
10595                        verification.setComponent(requiredVerifierComponent);
10596                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10597                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10598                                new BroadcastReceiver() {
10599                                    @Override
10600                                    public void onReceive(Context context, Intent intent) {
10601                                        final Message msg = mHandler
10602                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10603                                        msg.arg1 = verificationId;
10604                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10605                                    }
10606                                }, null, 0, null, null);
10607
10608                        /*
10609                         * We don't want the copy to proceed until verification
10610                         * succeeds, so null out this field.
10611                         */
10612                        mArgs = null;
10613                    }
10614                } else {
10615                    /*
10616                     * No package verification is enabled, so immediately start
10617                     * the remote call to initiate copy using temporary file.
10618                     */
10619                    ret = args.copyApk(mContainerService, true);
10620                }
10621            }
10622
10623            mRet = ret;
10624        }
10625
10626        @Override
10627        void handleReturnCode() {
10628            // If mArgs is null, then MCS couldn't be reached. When it
10629            // reconnects, it will try again to install. At that point, this
10630            // will succeed.
10631            if (mArgs != null) {
10632                processPendingInstall(mArgs, mRet);
10633            }
10634        }
10635
10636        @Override
10637        void handleServiceError() {
10638            mArgs = createInstallArgs(this);
10639            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10640        }
10641
10642        public boolean isForwardLocked() {
10643            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10644        }
10645    }
10646
10647    /**
10648     * Used during creation of InstallArgs
10649     *
10650     * @param installFlags package installation flags
10651     * @return true if should be installed on external storage
10652     */
10653    private static boolean installOnExternalAsec(int installFlags) {
10654        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10655            return false;
10656        }
10657        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10658            return true;
10659        }
10660        return false;
10661    }
10662
10663    /**
10664     * Used during creation of InstallArgs
10665     *
10666     * @param installFlags package installation flags
10667     * @return true if should be installed as forward locked
10668     */
10669    private static boolean installForwardLocked(int installFlags) {
10670        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10671    }
10672
10673    private InstallArgs createInstallArgs(InstallParams params) {
10674        if (params.move != null) {
10675            return new MoveInstallArgs(params);
10676        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10677            return new AsecInstallArgs(params);
10678        } else {
10679            return new FileInstallArgs(params);
10680        }
10681    }
10682
10683    /**
10684     * Create args that describe an existing installed package. Typically used
10685     * when cleaning up old installs, or used as a move source.
10686     */
10687    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10688            String resourcePath, String[] instructionSets) {
10689        final boolean isInAsec;
10690        if (installOnExternalAsec(installFlags)) {
10691            /* Apps on SD card are always in ASEC containers. */
10692            isInAsec = true;
10693        } else if (installForwardLocked(installFlags)
10694                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10695            /*
10696             * Forward-locked apps are only in ASEC containers if they're the
10697             * new style
10698             */
10699            isInAsec = true;
10700        } else {
10701            isInAsec = false;
10702        }
10703
10704        if (isInAsec) {
10705            return new AsecInstallArgs(codePath, instructionSets,
10706                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10707        } else {
10708            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10709        }
10710    }
10711
10712    static abstract class InstallArgs {
10713        /** @see InstallParams#origin */
10714        final OriginInfo origin;
10715        /** @see InstallParams#move */
10716        final MoveInfo move;
10717
10718        final IPackageInstallObserver2 observer;
10719        // Always refers to PackageManager flags only
10720        final int installFlags;
10721        final String installerPackageName;
10722        final String volumeUuid;
10723        final ManifestDigest manifestDigest;
10724        final UserHandle user;
10725        final String abiOverride;
10726
10727        // The list of instruction sets supported by this app. This is currently
10728        // only used during the rmdex() phase to clean up resources. We can get rid of this
10729        // if we move dex files under the common app path.
10730        /* nullable */ String[] instructionSets;
10731
10732        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10733                int installFlags, String installerPackageName, String volumeUuid,
10734                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10735                String abiOverride) {
10736            this.origin = origin;
10737            this.move = move;
10738            this.installFlags = installFlags;
10739            this.observer = observer;
10740            this.installerPackageName = installerPackageName;
10741            this.volumeUuid = volumeUuid;
10742            this.manifestDigest = manifestDigest;
10743            this.user = user;
10744            this.instructionSets = instructionSets;
10745            this.abiOverride = abiOverride;
10746        }
10747
10748        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10749        abstract int doPreInstall(int status);
10750
10751        /**
10752         * Rename package into final resting place. All paths on the given
10753         * scanned package should be updated to reflect the rename.
10754         */
10755        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10756        abstract int doPostInstall(int status, int uid);
10757
10758        /** @see PackageSettingBase#codePathString */
10759        abstract String getCodePath();
10760        /** @see PackageSettingBase#resourcePathString */
10761        abstract String getResourcePath();
10762
10763        // Need installer lock especially for dex file removal.
10764        abstract void cleanUpResourcesLI();
10765        abstract boolean doPostDeleteLI(boolean delete);
10766
10767        /**
10768         * Called before the source arguments are copied. This is used mostly
10769         * for MoveParams when it needs to read the source file to put it in the
10770         * destination.
10771         */
10772        int doPreCopy() {
10773            return PackageManager.INSTALL_SUCCEEDED;
10774        }
10775
10776        /**
10777         * Called after the source arguments are copied. This is used mostly for
10778         * MoveParams when it needs to read the source file to put it in the
10779         * destination.
10780         *
10781         * @return
10782         */
10783        int doPostCopy(int uid) {
10784            return PackageManager.INSTALL_SUCCEEDED;
10785        }
10786
10787        protected boolean isFwdLocked() {
10788            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10789        }
10790
10791        protected boolean isExternalAsec() {
10792            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10793        }
10794
10795        UserHandle getUser() {
10796            return user;
10797        }
10798    }
10799
10800    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10801        if (!allCodePaths.isEmpty()) {
10802            if (instructionSets == null) {
10803                throw new IllegalStateException("instructionSet == null");
10804            }
10805            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10806            for (String codePath : allCodePaths) {
10807                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10808                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10809                    if (retCode < 0) {
10810                        Slog.w(TAG, "Couldn't remove dex file for package: "
10811                                + " at location " + codePath + ", retcode=" + retCode);
10812                        // we don't consider this to be a failure of the core package deletion
10813                    }
10814                }
10815            }
10816        }
10817    }
10818
10819    /**
10820     * Logic to handle installation of non-ASEC applications, including copying
10821     * and renaming logic.
10822     */
10823    class FileInstallArgs extends InstallArgs {
10824        private File codeFile;
10825        private File resourceFile;
10826
10827        // Example topology:
10828        // /data/app/com.example/base.apk
10829        // /data/app/com.example/split_foo.apk
10830        // /data/app/com.example/lib/arm/libfoo.so
10831        // /data/app/com.example/lib/arm64/libfoo.so
10832        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10833
10834        /** New install */
10835        FileInstallArgs(InstallParams params) {
10836            super(params.origin, params.move, params.observer, params.installFlags,
10837                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10838                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10839            if (isFwdLocked()) {
10840                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10841            }
10842        }
10843
10844        /** Existing install */
10845        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10846            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10847                    null);
10848            this.codeFile = (codePath != null) ? new File(codePath) : null;
10849            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10850        }
10851
10852        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10853            if (origin.staged) {
10854                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10855                codeFile = origin.file;
10856                resourceFile = origin.file;
10857                return PackageManager.INSTALL_SUCCEEDED;
10858            }
10859
10860            try {
10861                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10862                codeFile = tempDir;
10863                resourceFile = tempDir;
10864            } catch (IOException e) {
10865                Slog.w(TAG, "Failed to create copy file: " + e);
10866                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10867            }
10868
10869            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10870                @Override
10871                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10872                    if (!FileUtils.isValidExtFilename(name)) {
10873                        throw new IllegalArgumentException("Invalid filename: " + name);
10874                    }
10875                    try {
10876                        final File file = new File(codeFile, name);
10877                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10878                                O_RDWR | O_CREAT, 0644);
10879                        Os.chmod(file.getAbsolutePath(), 0644);
10880                        return new ParcelFileDescriptor(fd);
10881                    } catch (ErrnoException e) {
10882                        throw new RemoteException("Failed to open: " + e.getMessage());
10883                    }
10884                }
10885            };
10886
10887            int ret = PackageManager.INSTALL_SUCCEEDED;
10888            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10889            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10890                Slog.e(TAG, "Failed to copy package");
10891                return ret;
10892            }
10893
10894            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10895            NativeLibraryHelper.Handle handle = null;
10896            try {
10897                handle = NativeLibraryHelper.Handle.create(codeFile);
10898                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10899                        abiOverride);
10900            } catch (IOException e) {
10901                Slog.e(TAG, "Copying native libraries failed", e);
10902                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10903            } finally {
10904                IoUtils.closeQuietly(handle);
10905            }
10906
10907            return ret;
10908        }
10909
10910        int doPreInstall(int status) {
10911            if (status != PackageManager.INSTALL_SUCCEEDED) {
10912                cleanUp();
10913            }
10914            return status;
10915        }
10916
10917        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10918            if (status != PackageManager.INSTALL_SUCCEEDED) {
10919                cleanUp();
10920                return false;
10921            }
10922
10923            final File targetDir = codeFile.getParentFile();
10924            final File beforeCodeFile = codeFile;
10925            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10926
10927            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10928            try {
10929                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10930            } catch (ErrnoException e) {
10931                Slog.w(TAG, "Failed to rename", e);
10932                return false;
10933            }
10934
10935            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10936                Slog.w(TAG, "Failed to restorecon");
10937                return false;
10938            }
10939
10940            // Reflect the rename internally
10941            codeFile = afterCodeFile;
10942            resourceFile = afterCodeFile;
10943
10944            // Reflect the rename in scanned details
10945            pkg.codePath = afterCodeFile.getAbsolutePath();
10946            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10947                    pkg.baseCodePath);
10948            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10949                    pkg.splitCodePaths);
10950
10951            // Reflect the rename in app info
10952            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10953            pkg.applicationInfo.setCodePath(pkg.codePath);
10954            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10955            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10956            pkg.applicationInfo.setResourcePath(pkg.codePath);
10957            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10958            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10959
10960            return true;
10961        }
10962
10963        int doPostInstall(int status, int uid) {
10964            if (status != PackageManager.INSTALL_SUCCEEDED) {
10965                cleanUp();
10966            }
10967            return status;
10968        }
10969
10970        @Override
10971        String getCodePath() {
10972            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10973        }
10974
10975        @Override
10976        String getResourcePath() {
10977            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10978        }
10979
10980        private boolean cleanUp() {
10981            if (codeFile == null || !codeFile.exists()) {
10982                return false;
10983            }
10984
10985            if (codeFile.isDirectory()) {
10986                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10987            } else {
10988                codeFile.delete();
10989            }
10990
10991            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10992                resourceFile.delete();
10993            }
10994
10995            return true;
10996        }
10997
10998        void cleanUpResourcesLI() {
10999            // Try enumerating all code paths before deleting
11000            List<String> allCodePaths = Collections.EMPTY_LIST;
11001            if (codeFile != null && codeFile.exists()) {
11002                try {
11003                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11004                    allCodePaths = pkg.getAllCodePaths();
11005                } catch (PackageParserException e) {
11006                    // Ignored; we tried our best
11007                }
11008            }
11009
11010            cleanUp();
11011            removeDexFiles(allCodePaths, instructionSets);
11012        }
11013
11014        boolean doPostDeleteLI(boolean delete) {
11015            // XXX err, shouldn't we respect the delete flag?
11016            cleanUpResourcesLI();
11017            return true;
11018        }
11019    }
11020
11021    private boolean isAsecExternal(String cid) {
11022        final String asecPath = PackageHelper.getSdFilesystem(cid);
11023        return !asecPath.startsWith(mAsecInternalPath);
11024    }
11025
11026    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11027            PackageManagerException {
11028        if (copyRet < 0) {
11029            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11030                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11031                throw new PackageManagerException(copyRet, message);
11032            }
11033        }
11034    }
11035
11036    /**
11037     * Extract the MountService "container ID" from the full code path of an
11038     * .apk.
11039     */
11040    static String cidFromCodePath(String fullCodePath) {
11041        int eidx = fullCodePath.lastIndexOf("/");
11042        String subStr1 = fullCodePath.substring(0, eidx);
11043        int sidx = subStr1.lastIndexOf("/");
11044        return subStr1.substring(sidx+1, eidx);
11045    }
11046
11047    /**
11048     * Logic to handle installation of ASEC applications, including copying and
11049     * renaming logic.
11050     */
11051    class AsecInstallArgs extends InstallArgs {
11052        static final String RES_FILE_NAME = "pkg.apk";
11053        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11054
11055        String cid;
11056        String packagePath;
11057        String resourcePath;
11058
11059        /** New install */
11060        AsecInstallArgs(InstallParams params) {
11061            super(params.origin, params.move, params.observer, params.installFlags,
11062                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11063                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11064        }
11065
11066        /** Existing install */
11067        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11068                        boolean isExternal, boolean isForwardLocked) {
11069            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11070                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11071                    instructionSets, null);
11072            // Hackily pretend we're still looking at a full code path
11073            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11074                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11075            }
11076
11077            // Extract cid from fullCodePath
11078            int eidx = fullCodePath.lastIndexOf("/");
11079            String subStr1 = fullCodePath.substring(0, eidx);
11080            int sidx = subStr1.lastIndexOf("/");
11081            cid = subStr1.substring(sidx+1, eidx);
11082            setMountPath(subStr1);
11083        }
11084
11085        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11086            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11087                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11088                    instructionSets, null);
11089            this.cid = cid;
11090            setMountPath(PackageHelper.getSdDir(cid));
11091        }
11092
11093        void createCopyFile() {
11094            cid = mInstallerService.allocateExternalStageCidLegacy();
11095        }
11096
11097        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11098            if (origin.staged) {
11099                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11100                cid = origin.cid;
11101                setMountPath(PackageHelper.getSdDir(cid));
11102                return PackageManager.INSTALL_SUCCEEDED;
11103            }
11104
11105            if (temp) {
11106                createCopyFile();
11107            } else {
11108                /*
11109                 * Pre-emptively destroy the container since it's destroyed if
11110                 * copying fails due to it existing anyway.
11111                 */
11112                PackageHelper.destroySdDir(cid);
11113            }
11114
11115            final String newMountPath = imcs.copyPackageToContainer(
11116                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11117                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11118
11119            if (newMountPath != null) {
11120                setMountPath(newMountPath);
11121                return PackageManager.INSTALL_SUCCEEDED;
11122            } else {
11123                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11124            }
11125        }
11126
11127        @Override
11128        String getCodePath() {
11129            return packagePath;
11130        }
11131
11132        @Override
11133        String getResourcePath() {
11134            return resourcePath;
11135        }
11136
11137        int doPreInstall(int status) {
11138            if (status != PackageManager.INSTALL_SUCCEEDED) {
11139                // Destroy container
11140                PackageHelper.destroySdDir(cid);
11141            } else {
11142                boolean mounted = PackageHelper.isContainerMounted(cid);
11143                if (!mounted) {
11144                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11145                            Process.SYSTEM_UID);
11146                    if (newMountPath != null) {
11147                        setMountPath(newMountPath);
11148                    } else {
11149                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11150                    }
11151                }
11152            }
11153            return status;
11154        }
11155
11156        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11157            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11158            String newMountPath = null;
11159            if (PackageHelper.isContainerMounted(cid)) {
11160                // Unmount the container
11161                if (!PackageHelper.unMountSdDir(cid)) {
11162                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11163                    return false;
11164                }
11165            }
11166            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11167                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11168                        " which might be stale. Will try to clean up.");
11169                // Clean up the stale container and proceed to recreate.
11170                if (!PackageHelper.destroySdDir(newCacheId)) {
11171                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11172                    return false;
11173                }
11174                // Successfully cleaned up stale container. Try to rename again.
11175                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11176                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11177                            + " inspite of cleaning it up.");
11178                    return false;
11179                }
11180            }
11181            if (!PackageHelper.isContainerMounted(newCacheId)) {
11182                Slog.w(TAG, "Mounting container " + newCacheId);
11183                newMountPath = PackageHelper.mountSdDir(newCacheId,
11184                        getEncryptKey(), Process.SYSTEM_UID);
11185            } else {
11186                newMountPath = PackageHelper.getSdDir(newCacheId);
11187            }
11188            if (newMountPath == null) {
11189                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11190                return false;
11191            }
11192            Log.i(TAG, "Succesfully renamed " + cid +
11193                    " to " + newCacheId +
11194                    " at new path: " + newMountPath);
11195            cid = newCacheId;
11196
11197            final File beforeCodeFile = new File(packagePath);
11198            setMountPath(newMountPath);
11199            final File afterCodeFile = new File(packagePath);
11200
11201            // Reflect the rename in scanned details
11202            pkg.codePath = afterCodeFile.getAbsolutePath();
11203            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11204                    pkg.baseCodePath);
11205            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11206                    pkg.splitCodePaths);
11207
11208            // Reflect the rename in app info
11209            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11210            pkg.applicationInfo.setCodePath(pkg.codePath);
11211            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11212            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11213            pkg.applicationInfo.setResourcePath(pkg.codePath);
11214            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11215            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11216
11217            return true;
11218        }
11219
11220        private void setMountPath(String mountPath) {
11221            final File mountFile = new File(mountPath);
11222
11223            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11224            if (monolithicFile.exists()) {
11225                packagePath = monolithicFile.getAbsolutePath();
11226                if (isFwdLocked()) {
11227                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11228                } else {
11229                    resourcePath = packagePath;
11230                }
11231            } else {
11232                packagePath = mountFile.getAbsolutePath();
11233                resourcePath = packagePath;
11234            }
11235        }
11236
11237        int doPostInstall(int status, int uid) {
11238            if (status != PackageManager.INSTALL_SUCCEEDED) {
11239                cleanUp();
11240            } else {
11241                final int groupOwner;
11242                final String protectedFile;
11243                if (isFwdLocked()) {
11244                    groupOwner = UserHandle.getSharedAppGid(uid);
11245                    protectedFile = RES_FILE_NAME;
11246                } else {
11247                    groupOwner = -1;
11248                    protectedFile = null;
11249                }
11250
11251                if (uid < Process.FIRST_APPLICATION_UID
11252                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11253                    Slog.e(TAG, "Failed to finalize " + cid);
11254                    PackageHelper.destroySdDir(cid);
11255                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11256                }
11257
11258                boolean mounted = PackageHelper.isContainerMounted(cid);
11259                if (!mounted) {
11260                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11261                }
11262            }
11263            return status;
11264        }
11265
11266        private void cleanUp() {
11267            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11268
11269            // Destroy secure container
11270            PackageHelper.destroySdDir(cid);
11271        }
11272
11273        private List<String> getAllCodePaths() {
11274            final File codeFile = new File(getCodePath());
11275            if (codeFile != null && codeFile.exists()) {
11276                try {
11277                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11278                    return pkg.getAllCodePaths();
11279                } catch (PackageParserException e) {
11280                    // Ignored; we tried our best
11281                }
11282            }
11283            return Collections.EMPTY_LIST;
11284        }
11285
11286        void cleanUpResourcesLI() {
11287            // Enumerate all code paths before deleting
11288            cleanUpResourcesLI(getAllCodePaths());
11289        }
11290
11291        private void cleanUpResourcesLI(List<String> allCodePaths) {
11292            cleanUp();
11293            removeDexFiles(allCodePaths, instructionSets);
11294        }
11295
11296        String getPackageName() {
11297            return getAsecPackageName(cid);
11298        }
11299
11300        boolean doPostDeleteLI(boolean delete) {
11301            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11302            final List<String> allCodePaths = getAllCodePaths();
11303            boolean mounted = PackageHelper.isContainerMounted(cid);
11304            if (mounted) {
11305                // Unmount first
11306                if (PackageHelper.unMountSdDir(cid)) {
11307                    mounted = false;
11308                }
11309            }
11310            if (!mounted && delete) {
11311                cleanUpResourcesLI(allCodePaths);
11312            }
11313            return !mounted;
11314        }
11315
11316        @Override
11317        int doPreCopy() {
11318            if (isFwdLocked()) {
11319                if (!PackageHelper.fixSdPermissions(cid,
11320                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11321                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11322                }
11323            }
11324
11325            return PackageManager.INSTALL_SUCCEEDED;
11326        }
11327
11328        @Override
11329        int doPostCopy(int uid) {
11330            if (isFwdLocked()) {
11331                if (uid < Process.FIRST_APPLICATION_UID
11332                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11333                                RES_FILE_NAME)) {
11334                    Slog.e(TAG, "Failed to finalize " + cid);
11335                    PackageHelper.destroySdDir(cid);
11336                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11337                }
11338            }
11339
11340            return PackageManager.INSTALL_SUCCEEDED;
11341        }
11342    }
11343
11344    /**
11345     * Logic to handle movement of existing installed applications.
11346     */
11347    class MoveInstallArgs extends InstallArgs {
11348        private File codeFile;
11349        private File resourceFile;
11350
11351        /** New install */
11352        MoveInstallArgs(InstallParams params) {
11353            super(params.origin, params.move, params.observer, params.installFlags,
11354                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11355                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11356        }
11357
11358        int copyApk(IMediaContainerService imcs, boolean temp) {
11359            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11360                    + move.fromUuid + " to " + move.toUuid);
11361            synchronized (mInstaller) {
11362                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11363                        move.dataAppName, move.appId, move.seinfo) != 0) {
11364                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11365                }
11366            }
11367
11368            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11369            resourceFile = codeFile;
11370            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11371
11372            return PackageManager.INSTALL_SUCCEEDED;
11373        }
11374
11375        int doPreInstall(int status) {
11376            if (status != PackageManager.INSTALL_SUCCEEDED) {
11377                cleanUp(move.toUuid);
11378            }
11379            return status;
11380        }
11381
11382        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11383            if (status != PackageManager.INSTALL_SUCCEEDED) {
11384                cleanUp(move.toUuid);
11385                return false;
11386            }
11387
11388            // Reflect the move in app info
11389            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11390            pkg.applicationInfo.setCodePath(pkg.codePath);
11391            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11392            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11393            pkg.applicationInfo.setResourcePath(pkg.codePath);
11394            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11395            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11396
11397            return true;
11398        }
11399
11400        int doPostInstall(int status, int uid) {
11401            if (status == PackageManager.INSTALL_SUCCEEDED) {
11402                cleanUp(move.fromUuid);
11403            } else {
11404                cleanUp(move.toUuid);
11405            }
11406            return status;
11407        }
11408
11409        @Override
11410        String getCodePath() {
11411            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11412        }
11413
11414        @Override
11415        String getResourcePath() {
11416            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11417        }
11418
11419        private boolean cleanUp(String volumeUuid) {
11420            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11421                    move.dataAppName);
11422            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11423            synchronized (mInstallLock) {
11424                // Clean up both app data and code
11425                removeDataDirsLI(volumeUuid, move.packageName);
11426                if (codeFile.isDirectory()) {
11427                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11428                } else {
11429                    codeFile.delete();
11430                }
11431            }
11432            return true;
11433        }
11434
11435        void cleanUpResourcesLI() {
11436            throw new UnsupportedOperationException();
11437        }
11438
11439        boolean doPostDeleteLI(boolean delete) {
11440            throw new UnsupportedOperationException();
11441        }
11442    }
11443
11444    static String getAsecPackageName(String packageCid) {
11445        int idx = packageCid.lastIndexOf("-");
11446        if (idx == -1) {
11447            return packageCid;
11448        }
11449        return packageCid.substring(0, idx);
11450    }
11451
11452    // Utility method used to create code paths based on package name and available index.
11453    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11454        String idxStr = "";
11455        int idx = 1;
11456        // Fall back to default value of idx=1 if prefix is not
11457        // part of oldCodePath
11458        if (oldCodePath != null) {
11459            String subStr = oldCodePath;
11460            // Drop the suffix right away
11461            if (suffix != null && subStr.endsWith(suffix)) {
11462                subStr = subStr.substring(0, subStr.length() - suffix.length());
11463            }
11464            // If oldCodePath already contains prefix find out the
11465            // ending index to either increment or decrement.
11466            int sidx = subStr.lastIndexOf(prefix);
11467            if (sidx != -1) {
11468                subStr = subStr.substring(sidx + prefix.length());
11469                if (subStr != null) {
11470                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11471                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11472                    }
11473                    try {
11474                        idx = Integer.parseInt(subStr);
11475                        if (idx <= 1) {
11476                            idx++;
11477                        } else {
11478                            idx--;
11479                        }
11480                    } catch(NumberFormatException e) {
11481                    }
11482                }
11483            }
11484        }
11485        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11486        return prefix + idxStr;
11487    }
11488
11489    private File getNextCodePath(File targetDir, String packageName) {
11490        int suffix = 1;
11491        File result;
11492        do {
11493            result = new File(targetDir, packageName + "-" + suffix);
11494            suffix++;
11495        } while (result.exists());
11496        return result;
11497    }
11498
11499    // Utility method that returns the relative package path with respect
11500    // to the installation directory. Like say for /data/data/com.test-1.apk
11501    // string com.test-1 is returned.
11502    static String deriveCodePathName(String codePath) {
11503        if (codePath == null) {
11504            return null;
11505        }
11506        final File codeFile = new File(codePath);
11507        final String name = codeFile.getName();
11508        if (codeFile.isDirectory()) {
11509            return name;
11510        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11511            final int lastDot = name.lastIndexOf('.');
11512            return name.substring(0, lastDot);
11513        } else {
11514            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11515            return null;
11516        }
11517    }
11518
11519    class PackageInstalledInfo {
11520        String name;
11521        int uid;
11522        // The set of users that originally had this package installed.
11523        int[] origUsers;
11524        // The set of users that now have this package installed.
11525        int[] newUsers;
11526        PackageParser.Package pkg;
11527        int returnCode;
11528        String returnMsg;
11529        PackageRemovedInfo removedInfo;
11530
11531        public void setError(int code, String msg) {
11532            returnCode = code;
11533            returnMsg = msg;
11534            Slog.w(TAG, msg);
11535        }
11536
11537        public void setError(String msg, PackageParserException e) {
11538            returnCode = e.error;
11539            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11540            Slog.w(TAG, msg, e);
11541        }
11542
11543        public void setError(String msg, PackageManagerException e) {
11544            returnCode = e.error;
11545            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11546            Slog.w(TAG, msg, e);
11547        }
11548
11549        // In some error cases we want to convey more info back to the observer
11550        String origPackage;
11551        String origPermission;
11552    }
11553
11554    /*
11555     * Install a non-existing package.
11556     */
11557    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11558            UserHandle user, String installerPackageName, String volumeUuid,
11559            PackageInstalledInfo res) {
11560        // Remember this for later, in case we need to rollback this install
11561        String pkgName = pkg.packageName;
11562
11563        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11564        final boolean dataDirExists = Environment
11565                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11566        synchronized(mPackages) {
11567            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11568                // A package with the same name is already installed, though
11569                // it has been renamed to an older name.  The package we
11570                // are trying to install should be installed as an update to
11571                // the existing one, but that has not been requested, so bail.
11572                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11573                        + " without first uninstalling package running as "
11574                        + mSettings.mRenamedPackages.get(pkgName));
11575                return;
11576            }
11577            if (mPackages.containsKey(pkgName)) {
11578                // Don't allow installation over an existing package with the same name.
11579                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11580                        + " without first uninstalling.");
11581                return;
11582            }
11583        }
11584
11585        try {
11586            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11587                    System.currentTimeMillis(), user);
11588
11589            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11590            // delete the partially installed application. the data directory will have to be
11591            // restored if it was already existing
11592            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11593                // remove package from internal structures.  Note that we want deletePackageX to
11594                // delete the package data and cache directories that it created in
11595                // scanPackageLocked, unless those directories existed before we even tried to
11596                // install.
11597                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11598                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11599                                res.removedInfo, true);
11600            }
11601
11602        } catch (PackageManagerException e) {
11603            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11604        }
11605    }
11606
11607    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11608        // Can't rotate keys during boot or if sharedUser.
11609        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11610                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11611            return false;
11612        }
11613        // app is using upgradeKeySets; make sure all are valid
11614        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11615        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11616        for (int i = 0; i < upgradeKeySets.length; i++) {
11617            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11618                Slog.wtf(TAG, "Package "
11619                         + (oldPs.name != null ? oldPs.name : "<null>")
11620                         + " contains upgrade-key-set reference to unknown key-set: "
11621                         + upgradeKeySets[i]
11622                         + " reverting to signatures check.");
11623                return false;
11624            }
11625        }
11626        return true;
11627    }
11628
11629    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11630        // Upgrade keysets are being used.  Determine if new package has a superset of the
11631        // required keys.
11632        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11633        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11634        for (int i = 0; i < upgradeKeySets.length; i++) {
11635            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11636            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11637                return true;
11638            }
11639        }
11640        return false;
11641    }
11642
11643    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11644            UserHandle user, String installerPackageName, String volumeUuid,
11645            PackageInstalledInfo res) {
11646        final PackageParser.Package oldPackage;
11647        final String pkgName = pkg.packageName;
11648        final int[] allUsers;
11649        final boolean[] perUserInstalled;
11650        final boolean weFroze;
11651
11652        // First find the old package info and check signatures
11653        synchronized(mPackages) {
11654            oldPackage = mPackages.get(pkgName);
11655            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11656            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11657            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11658                if(!checkUpgradeKeySetLP(ps, pkg)) {
11659                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11660                            "New package not signed by keys specified by upgrade-keysets: "
11661                            + pkgName);
11662                    return;
11663                }
11664            } else {
11665                // default to original signature matching
11666                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11667                    != PackageManager.SIGNATURE_MATCH) {
11668                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11669                            "New package has a different signature: " + pkgName);
11670                    return;
11671                }
11672            }
11673
11674            // In case of rollback, remember per-user/profile install state
11675            allUsers = sUserManager.getUserIds();
11676            perUserInstalled = new boolean[allUsers.length];
11677            for (int i = 0; i < allUsers.length; i++) {
11678                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11679            }
11680
11681            // Mark the app as frozen to prevent launching during the upgrade
11682            // process, and then kill all running instances
11683            if (!ps.frozen) {
11684                ps.frozen = true;
11685                weFroze = true;
11686            } else {
11687                weFroze = false;
11688            }
11689        }
11690
11691        // Now that we're guarded by frozen state, kill app during upgrade
11692        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11693
11694        try {
11695            boolean sysPkg = (isSystemApp(oldPackage));
11696            if (sysPkg) {
11697                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11698                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11699            } else {
11700                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11701                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11702            }
11703        } finally {
11704            // Regardless of success or failure of upgrade steps above, always
11705            // unfreeze the package if we froze it
11706            if (weFroze) {
11707                unfreezePackage(pkgName);
11708            }
11709        }
11710    }
11711
11712    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11713            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11714            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11715            String volumeUuid, PackageInstalledInfo res) {
11716        String pkgName = deletedPackage.packageName;
11717        boolean deletedPkg = true;
11718        boolean updatedSettings = false;
11719
11720        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11721                + deletedPackage);
11722        long origUpdateTime;
11723        if (pkg.mExtras != null) {
11724            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11725        } else {
11726            origUpdateTime = 0;
11727        }
11728
11729        // First delete the existing package while retaining the data directory
11730        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11731                res.removedInfo, true)) {
11732            // If the existing package wasn't successfully deleted
11733            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11734            deletedPkg = false;
11735        } else {
11736            // Successfully deleted the old package; proceed with replace.
11737
11738            // If deleted package lived in a container, give users a chance to
11739            // relinquish resources before killing.
11740            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11741                if (DEBUG_INSTALL) {
11742                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11743                }
11744                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11745                final ArrayList<String> pkgList = new ArrayList<String>(1);
11746                pkgList.add(deletedPackage.applicationInfo.packageName);
11747                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11748            }
11749
11750            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11751            try {
11752                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11753                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11754                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11755                        perUserInstalled, res, user);
11756                updatedSettings = true;
11757            } catch (PackageManagerException e) {
11758                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11759            }
11760        }
11761
11762        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11763            // remove package from internal structures.  Note that we want deletePackageX to
11764            // delete the package data and cache directories that it created in
11765            // scanPackageLocked, unless those directories existed before we even tried to
11766            // install.
11767            if(updatedSettings) {
11768                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11769                deletePackageLI(
11770                        pkgName, null, true, allUsers, perUserInstalled,
11771                        PackageManager.DELETE_KEEP_DATA,
11772                                res.removedInfo, true);
11773            }
11774            // Since we failed to install the new package we need to restore the old
11775            // package that we deleted.
11776            if (deletedPkg) {
11777                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11778                File restoreFile = new File(deletedPackage.codePath);
11779                // Parse old package
11780                boolean oldExternal = isExternal(deletedPackage);
11781                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11782                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11783                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11784                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11785                try {
11786                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11787                } catch (PackageManagerException e) {
11788                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11789                            + e.getMessage());
11790                    return;
11791                }
11792                // Restore of old package succeeded. Update permissions.
11793                // writer
11794                synchronized (mPackages) {
11795                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11796                            UPDATE_PERMISSIONS_ALL);
11797                    // can downgrade to reader
11798                    mSettings.writeLPr();
11799                }
11800                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11801            }
11802        }
11803    }
11804
11805    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11806            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11807            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11808            String volumeUuid, PackageInstalledInfo res) {
11809        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11810                + ", old=" + deletedPackage);
11811        boolean disabledSystem = false;
11812        boolean updatedSettings = false;
11813        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11814        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11815                != 0) {
11816            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11817        }
11818        String packageName = deletedPackage.packageName;
11819        if (packageName == null) {
11820            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11821                    "Attempt to delete null packageName.");
11822            return;
11823        }
11824        PackageParser.Package oldPkg;
11825        PackageSetting oldPkgSetting;
11826        // reader
11827        synchronized (mPackages) {
11828            oldPkg = mPackages.get(packageName);
11829            oldPkgSetting = mSettings.mPackages.get(packageName);
11830            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11831                    (oldPkgSetting == null)) {
11832                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11833                        "Couldn't find package:" + packageName + " information");
11834                return;
11835            }
11836        }
11837
11838        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11839        res.removedInfo.removedPackage = packageName;
11840        // Remove existing system package
11841        removePackageLI(oldPkgSetting, true);
11842        // writer
11843        synchronized (mPackages) {
11844            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11845            if (!disabledSystem && deletedPackage != null) {
11846                // We didn't need to disable the .apk as a current system package,
11847                // which means we are replacing another update that is already
11848                // installed.  We need to make sure to delete the older one's .apk.
11849                res.removedInfo.args = createInstallArgsForExisting(0,
11850                        deletedPackage.applicationInfo.getCodePath(),
11851                        deletedPackage.applicationInfo.getResourcePath(),
11852                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11853            } else {
11854                res.removedInfo.args = null;
11855            }
11856        }
11857
11858        // Successfully disabled the old package. Now proceed with re-installation
11859        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11860
11861        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11862        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11863
11864        PackageParser.Package newPackage = null;
11865        try {
11866            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11867            if (newPackage.mExtras != null) {
11868                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11869                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11870                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11871
11872                // is the update attempting to change shared user? that isn't going to work...
11873                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11874                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11875                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11876                            + " to " + newPkgSetting.sharedUser);
11877                    updatedSettings = true;
11878                }
11879            }
11880
11881            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11882                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11883                        perUserInstalled, res, user);
11884                updatedSettings = true;
11885            }
11886
11887        } catch (PackageManagerException e) {
11888            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11889        }
11890
11891        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11892            // Re installation failed. Restore old information
11893            // Remove new pkg information
11894            if (newPackage != null) {
11895                removeInstalledPackageLI(newPackage, true);
11896            }
11897            // Add back the old system package
11898            try {
11899                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11900            } catch (PackageManagerException e) {
11901                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11902            }
11903            // Restore the old system information in Settings
11904            synchronized (mPackages) {
11905                if (disabledSystem) {
11906                    mSettings.enableSystemPackageLPw(packageName);
11907                }
11908                if (updatedSettings) {
11909                    mSettings.setInstallerPackageName(packageName,
11910                            oldPkgSetting.installerPackageName);
11911                }
11912                mSettings.writeLPr();
11913            }
11914        }
11915    }
11916
11917    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11918            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11919            UserHandle user) {
11920        String pkgName = newPackage.packageName;
11921        synchronized (mPackages) {
11922            //write settings. the installStatus will be incomplete at this stage.
11923            //note that the new package setting would have already been
11924            //added to mPackages. It hasn't been persisted yet.
11925            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11926            mSettings.writeLPr();
11927        }
11928
11929        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11930
11931        synchronized (mPackages) {
11932            updatePermissionsLPw(newPackage.packageName, newPackage,
11933                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11934                            ? UPDATE_PERMISSIONS_ALL : 0));
11935            // For system-bundled packages, we assume that installing an upgraded version
11936            // of the package implies that the user actually wants to run that new code,
11937            // so we enable the package.
11938            PackageSetting ps = mSettings.mPackages.get(pkgName);
11939            if (ps != null) {
11940                if (isSystemApp(newPackage)) {
11941                    // NB: implicit assumption that system package upgrades apply to all users
11942                    if (DEBUG_INSTALL) {
11943                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11944                    }
11945                    if (res.origUsers != null) {
11946                        for (int userHandle : res.origUsers) {
11947                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11948                                    userHandle, installerPackageName);
11949                        }
11950                    }
11951                    // Also convey the prior install/uninstall state
11952                    if (allUsers != null && perUserInstalled != null) {
11953                        for (int i = 0; i < allUsers.length; i++) {
11954                            if (DEBUG_INSTALL) {
11955                                Slog.d(TAG, "    user " + allUsers[i]
11956                                        + " => " + perUserInstalled[i]);
11957                            }
11958                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11959                        }
11960                        // these install state changes will be persisted in the
11961                        // upcoming call to mSettings.writeLPr().
11962                    }
11963                }
11964                // It's implied that when a user requests installation, they want the app to be
11965                // installed and enabled.
11966                int userId = user.getIdentifier();
11967                if (userId != UserHandle.USER_ALL) {
11968                    ps.setInstalled(true, userId);
11969                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11970                }
11971            }
11972            res.name = pkgName;
11973            res.uid = newPackage.applicationInfo.uid;
11974            res.pkg = newPackage;
11975            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11976            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11977            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11978            //to update install status
11979            mSettings.writeLPr();
11980        }
11981    }
11982
11983    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11984        final int installFlags = args.installFlags;
11985        final String installerPackageName = args.installerPackageName;
11986        final String volumeUuid = args.volumeUuid;
11987        final File tmpPackageFile = new File(args.getCodePath());
11988        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11989        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11990                || (args.volumeUuid != null));
11991        boolean replace = false;
11992        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11993        if (args.move != null) {
11994            // moving a complete application; perfom an initial scan on the new install location
11995            scanFlags |= SCAN_INITIAL;
11996        }
11997        // Result object to be returned
11998        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11999
12000        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12001        // Retrieve PackageSettings and parse package
12002        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12003                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12004                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12005        PackageParser pp = new PackageParser();
12006        pp.setSeparateProcesses(mSeparateProcesses);
12007        pp.setDisplayMetrics(mMetrics);
12008
12009        final PackageParser.Package pkg;
12010        try {
12011            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12012        } catch (PackageParserException e) {
12013            res.setError("Failed parse during installPackageLI", e);
12014            return;
12015        }
12016
12017        // Mark that we have an install time CPU ABI override.
12018        pkg.cpuAbiOverride = args.abiOverride;
12019
12020        String pkgName = res.name = pkg.packageName;
12021        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12022            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12023                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12024                return;
12025            }
12026        }
12027
12028        try {
12029            pp.collectCertificates(pkg, parseFlags);
12030            pp.collectManifestDigest(pkg);
12031        } catch (PackageParserException e) {
12032            res.setError("Failed collect during installPackageLI", e);
12033            return;
12034        }
12035
12036        /* If the installer passed in a manifest digest, compare it now. */
12037        if (args.manifestDigest != null) {
12038            if (DEBUG_INSTALL) {
12039                final String parsedManifest = pkg.manifestDigest == null ? "null"
12040                        : pkg.manifestDigest.toString();
12041                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12042                        + parsedManifest);
12043            }
12044
12045            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12046                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12047                return;
12048            }
12049        } else if (DEBUG_INSTALL) {
12050            final String parsedManifest = pkg.manifestDigest == null
12051                    ? "null" : pkg.manifestDigest.toString();
12052            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12053        }
12054
12055        // Get rid of all references to package scan path via parser.
12056        pp = null;
12057        String oldCodePath = null;
12058        boolean systemApp = false;
12059        synchronized (mPackages) {
12060            // Check if installing already existing package
12061            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12062                String oldName = mSettings.mRenamedPackages.get(pkgName);
12063                if (pkg.mOriginalPackages != null
12064                        && pkg.mOriginalPackages.contains(oldName)
12065                        && mPackages.containsKey(oldName)) {
12066                    // This package is derived from an original package,
12067                    // and this device has been updating from that original
12068                    // name.  We must continue using the original name, so
12069                    // rename the new package here.
12070                    pkg.setPackageName(oldName);
12071                    pkgName = pkg.packageName;
12072                    replace = true;
12073                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12074                            + oldName + " pkgName=" + pkgName);
12075                } else if (mPackages.containsKey(pkgName)) {
12076                    // This package, under its official name, already exists
12077                    // on the device; we should replace it.
12078                    replace = true;
12079                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12080                }
12081
12082                // Prevent apps opting out from runtime permissions
12083                if (replace) {
12084                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12085                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12086                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12087                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12088                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12089                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12090                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12091                                        + " doesn't support runtime permissions but the old"
12092                                        + " target SDK " + oldTargetSdk + " does.");
12093                        return;
12094                    }
12095                }
12096            }
12097
12098            PackageSetting ps = mSettings.mPackages.get(pkgName);
12099            if (ps != null) {
12100                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12101
12102                // Quick sanity check that we're signed correctly if updating;
12103                // we'll check this again later when scanning, but we want to
12104                // bail early here before tripping over redefined permissions.
12105                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12106                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12107                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12108                                + pkg.packageName + " upgrade keys do not match the "
12109                                + "previously installed version");
12110                        return;
12111                    }
12112                } else {
12113                    try {
12114                        verifySignaturesLP(ps, pkg);
12115                    } catch (PackageManagerException e) {
12116                        res.setError(e.error, e.getMessage());
12117                        return;
12118                    }
12119                }
12120
12121                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12122                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12123                    systemApp = (ps.pkg.applicationInfo.flags &
12124                            ApplicationInfo.FLAG_SYSTEM) != 0;
12125                }
12126                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12127            }
12128
12129            // Check whether the newly-scanned package wants to define an already-defined perm
12130            int N = pkg.permissions.size();
12131            for (int i = N-1; i >= 0; i--) {
12132                PackageParser.Permission perm = pkg.permissions.get(i);
12133                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12134                if (bp != null) {
12135                    // If the defining package is signed with our cert, it's okay.  This
12136                    // also includes the "updating the same package" case, of course.
12137                    // "updating same package" could also involve key-rotation.
12138                    final boolean sigsOk;
12139                    if (bp.sourcePackage.equals(pkg.packageName)
12140                            && (bp.packageSetting instanceof PackageSetting)
12141                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12142                                    scanFlags))) {
12143                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12144                    } else {
12145                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12146                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12147                    }
12148                    if (!sigsOk) {
12149                        // If the owning package is the system itself, we log but allow
12150                        // install to proceed; we fail the install on all other permission
12151                        // redefinitions.
12152                        if (!bp.sourcePackage.equals("android")) {
12153                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12154                                    + pkg.packageName + " attempting to redeclare permission "
12155                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12156                            res.origPermission = perm.info.name;
12157                            res.origPackage = bp.sourcePackage;
12158                            return;
12159                        } else {
12160                            Slog.w(TAG, "Package " + pkg.packageName
12161                                    + " attempting to redeclare system permission "
12162                                    + perm.info.name + "; ignoring new declaration");
12163                            pkg.permissions.remove(i);
12164                        }
12165                    }
12166                }
12167            }
12168
12169        }
12170
12171        if (systemApp && onExternal) {
12172            // Disable updates to system apps on sdcard
12173            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12174                    "Cannot install updates to system apps on sdcard");
12175            return;
12176        }
12177
12178        if (args.move != null) {
12179            // We did an in-place move, so dex is ready to roll
12180            scanFlags |= SCAN_NO_DEX;
12181            scanFlags |= SCAN_MOVE;
12182        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12183            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12184            scanFlags |= SCAN_NO_DEX;
12185
12186            try {
12187                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12188                        true /* extract libs */);
12189            } catch (PackageManagerException pme) {
12190                Slog.e(TAG, "Error deriving application ABI", pme);
12191                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12192                return;
12193            }
12194
12195            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12196            int result = mPackageDexOptimizer
12197                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12198                            false /* defer */, false /* inclDependencies */);
12199            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12200                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12201                return;
12202            }
12203        }
12204
12205        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12206            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12207            return;
12208        }
12209
12210        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12211
12212        if (replace) {
12213            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12214                    installerPackageName, volumeUuid, res);
12215        } else {
12216            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12217                    args.user, installerPackageName, volumeUuid, res);
12218        }
12219        synchronized (mPackages) {
12220            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12221            if (ps != null) {
12222                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12223            }
12224        }
12225    }
12226
12227    private void startIntentFilterVerifications(int userId, boolean replacing,
12228            PackageParser.Package pkg) {
12229        if (mIntentFilterVerifierComponent == null) {
12230            Slog.w(TAG, "No IntentFilter verification will not be done as "
12231                    + "there is no IntentFilterVerifier available!");
12232            return;
12233        }
12234
12235        final int verifierUid = getPackageUid(
12236                mIntentFilterVerifierComponent.getPackageName(),
12237                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12238
12239        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12240        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12241        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12242        mHandler.sendMessage(msg);
12243    }
12244
12245    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12246            PackageParser.Package pkg) {
12247        int size = pkg.activities.size();
12248        if (size == 0) {
12249            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12250                    "No activity, so no need to verify any IntentFilter!");
12251            return;
12252        }
12253
12254        final boolean hasDomainURLs = hasDomainURLs(pkg);
12255        if (!hasDomainURLs) {
12256            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12257                    "No domain URLs, so no need to verify any IntentFilter!");
12258            return;
12259        }
12260
12261        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12262                + " if any IntentFilter from the " + size
12263                + " Activities needs verification ...");
12264
12265        int count = 0;
12266        final String packageName = pkg.packageName;
12267
12268        synchronized (mPackages) {
12269            // If this is a new install and we see that we've already run verification for this
12270            // package, we have nothing to do: it means the state was restored from backup.
12271            if (!replacing) {
12272                IntentFilterVerificationInfo ivi =
12273                        mSettings.getIntentFilterVerificationLPr(packageName);
12274                if (ivi != null) {
12275                    if (DEBUG_DOMAIN_VERIFICATION) {
12276                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12277                                + ivi.getStatusString());
12278                    }
12279                    return;
12280                }
12281            }
12282
12283            // If any filters need to be verified, then all need to be.
12284            boolean needToVerify = false;
12285            for (PackageParser.Activity a : pkg.activities) {
12286                for (ActivityIntentInfo filter : a.intents) {
12287                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12288                        if (DEBUG_DOMAIN_VERIFICATION) {
12289                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12290                        }
12291                        needToVerify = true;
12292                        break;
12293                    }
12294                }
12295            }
12296
12297            if (needToVerify) {
12298                final int verificationId = mIntentFilterVerificationToken++;
12299                for (PackageParser.Activity a : pkg.activities) {
12300                    for (ActivityIntentInfo filter : a.intents) {
12301                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12302                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12303                                    "Verification needed for IntentFilter:" + filter.toString());
12304                            mIntentFilterVerifier.addOneIntentFilterVerification(
12305                                    verifierUid, userId, verificationId, filter, packageName);
12306                            count++;
12307                        }
12308                    }
12309                }
12310            }
12311        }
12312
12313        if (count > 0) {
12314            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12315                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12316                    +  " for userId:" + userId);
12317            mIntentFilterVerifier.startVerifications(userId);
12318        } else {
12319            if (DEBUG_DOMAIN_VERIFICATION) {
12320                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12321            }
12322        }
12323    }
12324
12325    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12326        final ComponentName cn  = filter.activity.getComponentName();
12327        final String packageName = cn.getPackageName();
12328
12329        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12330                packageName);
12331        if (ivi == null) {
12332            return true;
12333        }
12334        int status = ivi.getStatus();
12335        switch (status) {
12336            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12337            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12338                return true;
12339
12340            default:
12341                // Nothing to do
12342                return false;
12343        }
12344    }
12345
12346    private static boolean isMultiArch(PackageSetting ps) {
12347        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12348    }
12349
12350    private static boolean isMultiArch(ApplicationInfo info) {
12351        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12352    }
12353
12354    private static boolean isExternal(PackageParser.Package pkg) {
12355        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12356    }
12357
12358    private static boolean isExternal(PackageSetting ps) {
12359        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12360    }
12361
12362    private static boolean isExternal(ApplicationInfo info) {
12363        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12364    }
12365
12366    private static boolean isSystemApp(PackageParser.Package pkg) {
12367        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12368    }
12369
12370    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12371        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12372    }
12373
12374    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12375        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12376    }
12377
12378    private static boolean isSystemApp(PackageSetting ps) {
12379        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12380    }
12381
12382    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12383        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12384    }
12385
12386    private int packageFlagsToInstallFlags(PackageSetting ps) {
12387        int installFlags = 0;
12388        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12389            // This existing package was an external ASEC install when we have
12390            // the external flag without a UUID
12391            installFlags |= PackageManager.INSTALL_EXTERNAL;
12392        }
12393        if (ps.isForwardLocked()) {
12394            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12395        }
12396        return installFlags;
12397    }
12398
12399    private void deleteTempPackageFiles() {
12400        final FilenameFilter filter = new FilenameFilter() {
12401            public boolean accept(File dir, String name) {
12402                return name.startsWith("vmdl") && name.endsWith(".tmp");
12403            }
12404        };
12405        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12406            file.delete();
12407        }
12408    }
12409
12410    @Override
12411    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12412            int flags) {
12413        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12414                flags);
12415    }
12416
12417    @Override
12418    public void deletePackage(final String packageName,
12419            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12420        mContext.enforceCallingOrSelfPermission(
12421                android.Manifest.permission.DELETE_PACKAGES, null);
12422        Preconditions.checkNotNull(packageName);
12423        Preconditions.checkNotNull(observer);
12424        final int uid = Binder.getCallingUid();
12425        if (UserHandle.getUserId(uid) != userId) {
12426            mContext.enforceCallingPermission(
12427                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12428                    "deletePackage for user " + userId);
12429        }
12430        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12431            try {
12432                observer.onPackageDeleted(packageName,
12433                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12434            } catch (RemoteException re) {
12435            }
12436            return;
12437        }
12438
12439        boolean uninstallBlocked = false;
12440        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12441            int[] users = sUserManager.getUserIds();
12442            for (int i = 0; i < users.length; ++i) {
12443                if (getBlockUninstallForUser(packageName, users[i])) {
12444                    uninstallBlocked = true;
12445                    break;
12446                }
12447            }
12448        } else {
12449            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12450        }
12451        if (uninstallBlocked) {
12452            try {
12453                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12454                        null);
12455            } catch (RemoteException re) {
12456            }
12457            return;
12458        }
12459
12460        if (DEBUG_REMOVE) {
12461            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12462        }
12463        // Queue up an async operation since the package deletion may take a little while.
12464        mHandler.post(new Runnable() {
12465            public void run() {
12466                mHandler.removeCallbacks(this);
12467                final int returnCode = deletePackageX(packageName, userId, flags);
12468                if (observer != null) {
12469                    try {
12470                        observer.onPackageDeleted(packageName, returnCode, null);
12471                    } catch (RemoteException e) {
12472                        Log.i(TAG, "Observer no longer exists.");
12473                    } //end catch
12474                } //end if
12475            } //end run
12476        });
12477    }
12478
12479    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12480        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12481                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12482        try {
12483            if (dpm != null) {
12484                if (dpm.isDeviceOwner(packageName)) {
12485                    return true;
12486                }
12487                int[] users;
12488                if (userId == UserHandle.USER_ALL) {
12489                    users = sUserManager.getUserIds();
12490                } else {
12491                    users = new int[]{userId};
12492                }
12493                for (int i = 0; i < users.length; ++i) {
12494                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12495                        return true;
12496                    }
12497                }
12498            }
12499        } catch (RemoteException e) {
12500        }
12501        return false;
12502    }
12503
12504    /**
12505     *  This method is an internal method that could be get invoked either
12506     *  to delete an installed package or to clean up a failed installation.
12507     *  After deleting an installed package, a broadcast is sent to notify any
12508     *  listeners that the package has been installed. For cleaning up a failed
12509     *  installation, the broadcast is not necessary since the package's
12510     *  installation wouldn't have sent the initial broadcast either
12511     *  The key steps in deleting a package are
12512     *  deleting the package information in internal structures like mPackages,
12513     *  deleting the packages base directories through installd
12514     *  updating mSettings to reflect current status
12515     *  persisting settings for later use
12516     *  sending a broadcast if necessary
12517     */
12518    private int deletePackageX(String packageName, int userId, int flags) {
12519        final PackageRemovedInfo info = new PackageRemovedInfo();
12520        final boolean res;
12521
12522        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12523                ? UserHandle.ALL : new UserHandle(userId);
12524
12525        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12526            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12527            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12528        }
12529
12530        boolean removedForAllUsers = false;
12531        boolean systemUpdate = false;
12532
12533        // for the uninstall-updates case and restricted profiles, remember the per-
12534        // userhandle installed state
12535        int[] allUsers;
12536        boolean[] perUserInstalled;
12537        synchronized (mPackages) {
12538            PackageSetting ps = mSettings.mPackages.get(packageName);
12539            allUsers = sUserManager.getUserIds();
12540            perUserInstalled = new boolean[allUsers.length];
12541            for (int i = 0; i < allUsers.length; i++) {
12542                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12543            }
12544        }
12545
12546        synchronized (mInstallLock) {
12547            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12548            res = deletePackageLI(packageName, removeForUser,
12549                    true, allUsers, perUserInstalled,
12550                    flags | REMOVE_CHATTY, info, true);
12551            systemUpdate = info.isRemovedPackageSystemUpdate;
12552            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12553                removedForAllUsers = true;
12554            }
12555            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12556                    + " removedForAllUsers=" + removedForAllUsers);
12557        }
12558
12559        if (res) {
12560            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12561
12562            // If the removed package was a system update, the old system package
12563            // was re-enabled; we need to broadcast this information
12564            if (systemUpdate) {
12565                Bundle extras = new Bundle(1);
12566                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12567                        ? info.removedAppId : info.uid);
12568                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12569
12570                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12571                        extras, null, null, null);
12572                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12573                        extras, null, null, null);
12574                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12575                        null, packageName, null, null);
12576            }
12577        }
12578        // Force a gc here.
12579        Runtime.getRuntime().gc();
12580        // Delete the resources here after sending the broadcast to let
12581        // other processes clean up before deleting resources.
12582        if (info.args != null) {
12583            synchronized (mInstallLock) {
12584                info.args.doPostDeleteLI(true);
12585            }
12586        }
12587
12588        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12589    }
12590
12591    class PackageRemovedInfo {
12592        String removedPackage;
12593        int uid = -1;
12594        int removedAppId = -1;
12595        int[] removedUsers = null;
12596        boolean isRemovedPackageSystemUpdate = false;
12597        // Clean up resources deleted packages.
12598        InstallArgs args = null;
12599
12600        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12601            Bundle extras = new Bundle(1);
12602            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12603            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12604            if (replacing) {
12605                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12606            }
12607            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12608            if (removedPackage != null) {
12609                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12610                        extras, null, null, removedUsers);
12611                if (fullRemove && !replacing) {
12612                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12613                            extras, null, null, removedUsers);
12614                }
12615            }
12616            if (removedAppId >= 0) {
12617                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12618                        removedUsers);
12619            }
12620        }
12621    }
12622
12623    /*
12624     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12625     * flag is not set, the data directory is removed as well.
12626     * make sure this flag is set for partially installed apps. If not its meaningless to
12627     * delete a partially installed application.
12628     */
12629    private void removePackageDataLI(PackageSetting ps,
12630            int[] allUserHandles, boolean[] perUserInstalled,
12631            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12632        String packageName = ps.name;
12633        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12634        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12635        // Retrieve object to delete permissions for shared user later on
12636        final PackageSetting deletedPs;
12637        // reader
12638        synchronized (mPackages) {
12639            deletedPs = mSettings.mPackages.get(packageName);
12640            if (outInfo != null) {
12641                outInfo.removedPackage = packageName;
12642                outInfo.removedUsers = deletedPs != null
12643                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12644                        : null;
12645            }
12646        }
12647        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12648            removeDataDirsLI(ps.volumeUuid, packageName);
12649            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12650        }
12651        // writer
12652        synchronized (mPackages) {
12653            if (deletedPs != null) {
12654                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12655                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12656                    clearDefaultBrowserIfNeeded(packageName);
12657                    if (outInfo != null) {
12658                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12659                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12660                    }
12661                    updatePermissionsLPw(deletedPs.name, null, 0);
12662                    if (deletedPs.sharedUser != null) {
12663                        // Remove permissions associated with package. Since runtime
12664                        // permissions are per user we have to kill the removed package
12665                        // or packages running under the shared user of the removed
12666                        // package if revoking the permissions requested only by the removed
12667                        // package is successful and this causes a change in gids.
12668                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12669                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12670                                    userId);
12671                            if (userIdToKill == UserHandle.USER_ALL
12672                                    || userIdToKill >= UserHandle.USER_OWNER) {
12673                                // If gids changed for this user, kill all affected packages.
12674                                mHandler.post(new Runnable() {
12675                                    @Override
12676                                    public void run() {
12677                                        // This has to happen with no lock held.
12678                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12679                                                KILL_APP_REASON_GIDS_CHANGED);
12680                                    }
12681                                });
12682                                break;
12683                            }
12684                        }
12685                    }
12686                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12687                }
12688                // make sure to preserve per-user disabled state if this removal was just
12689                // a downgrade of a system app to the factory package
12690                if (allUserHandles != null && perUserInstalled != null) {
12691                    if (DEBUG_REMOVE) {
12692                        Slog.d(TAG, "Propagating install state across downgrade");
12693                    }
12694                    for (int i = 0; i < allUserHandles.length; i++) {
12695                        if (DEBUG_REMOVE) {
12696                            Slog.d(TAG, "    user " + allUserHandles[i]
12697                                    + " => " + perUserInstalled[i]);
12698                        }
12699                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12700                    }
12701                }
12702            }
12703            // can downgrade to reader
12704            if (writeSettings) {
12705                // Save settings now
12706                mSettings.writeLPr();
12707            }
12708        }
12709        if (outInfo != null) {
12710            // A user ID was deleted here. Go through all users and remove it
12711            // from KeyStore.
12712            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12713        }
12714    }
12715
12716    static boolean locationIsPrivileged(File path) {
12717        try {
12718            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12719                    .getCanonicalPath();
12720            return path.getCanonicalPath().startsWith(privilegedAppDir);
12721        } catch (IOException e) {
12722            Slog.e(TAG, "Unable to access code path " + path);
12723        }
12724        return false;
12725    }
12726
12727    /*
12728     * Tries to delete system package.
12729     */
12730    private boolean deleteSystemPackageLI(PackageSetting newPs,
12731            int[] allUserHandles, boolean[] perUserInstalled,
12732            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12733        final boolean applyUserRestrictions
12734                = (allUserHandles != null) && (perUserInstalled != null);
12735        PackageSetting disabledPs = null;
12736        // Confirm if the system package has been updated
12737        // An updated system app can be deleted. This will also have to restore
12738        // the system pkg from system partition
12739        // reader
12740        synchronized (mPackages) {
12741            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12742        }
12743        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12744                + " disabledPs=" + disabledPs);
12745        if (disabledPs == null) {
12746            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12747            return false;
12748        } else if (DEBUG_REMOVE) {
12749            Slog.d(TAG, "Deleting system pkg from data partition");
12750        }
12751        if (DEBUG_REMOVE) {
12752            if (applyUserRestrictions) {
12753                Slog.d(TAG, "Remembering install states:");
12754                for (int i = 0; i < allUserHandles.length; i++) {
12755                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12756                }
12757            }
12758        }
12759        // Delete the updated package
12760        outInfo.isRemovedPackageSystemUpdate = true;
12761        if (disabledPs.versionCode < newPs.versionCode) {
12762            // Delete data for downgrades
12763            flags &= ~PackageManager.DELETE_KEEP_DATA;
12764        } else {
12765            // Preserve data by setting flag
12766            flags |= PackageManager.DELETE_KEEP_DATA;
12767        }
12768        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12769                allUserHandles, perUserInstalled, outInfo, writeSettings);
12770        if (!ret) {
12771            return false;
12772        }
12773        // writer
12774        synchronized (mPackages) {
12775            // Reinstate the old system package
12776            mSettings.enableSystemPackageLPw(newPs.name);
12777            // Remove any native libraries from the upgraded package.
12778            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12779        }
12780        // Install the system package
12781        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12782        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12783        if (locationIsPrivileged(disabledPs.codePath)) {
12784            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12785        }
12786
12787        final PackageParser.Package newPkg;
12788        try {
12789            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12790        } catch (PackageManagerException e) {
12791            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12792            return false;
12793        }
12794
12795        // writer
12796        synchronized (mPackages) {
12797            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12798
12799            // Propagate the permissions state as we do want to drop on the floor
12800            // runtime permissions. The update permissions method below will take
12801            // care of removing obsolete permissions and grant install permissions.
12802            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12803            updatePermissionsLPw(newPkg.packageName, newPkg,
12804                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12805
12806            if (applyUserRestrictions) {
12807                if (DEBUG_REMOVE) {
12808                    Slog.d(TAG, "Propagating install state across reinstall");
12809                }
12810                for (int i = 0; i < allUserHandles.length; i++) {
12811                    if (DEBUG_REMOVE) {
12812                        Slog.d(TAG, "    user " + allUserHandles[i]
12813                                + " => " + perUserInstalled[i]);
12814                    }
12815                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12816                }
12817                // Regardless of writeSettings we need to ensure that this restriction
12818                // state propagation is persisted
12819                mSettings.writeAllUsersPackageRestrictionsLPr();
12820            }
12821            // can downgrade to reader here
12822            if (writeSettings) {
12823                mSettings.writeLPr();
12824            }
12825        }
12826        return true;
12827    }
12828
12829    private boolean deleteInstalledPackageLI(PackageSetting ps,
12830            boolean deleteCodeAndResources, int flags,
12831            int[] allUserHandles, boolean[] perUserInstalled,
12832            PackageRemovedInfo outInfo, boolean writeSettings) {
12833        if (outInfo != null) {
12834            outInfo.uid = ps.appId;
12835        }
12836
12837        // Delete package data from internal structures and also remove data if flag is set
12838        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12839
12840        // Delete application code and resources
12841        if (deleteCodeAndResources && (outInfo != null)) {
12842            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12843                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12844            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12845        }
12846        return true;
12847    }
12848
12849    @Override
12850    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12851            int userId) {
12852        mContext.enforceCallingOrSelfPermission(
12853                android.Manifest.permission.DELETE_PACKAGES, null);
12854        synchronized (mPackages) {
12855            PackageSetting ps = mSettings.mPackages.get(packageName);
12856            if (ps == null) {
12857                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12858                return false;
12859            }
12860            if (!ps.getInstalled(userId)) {
12861                // Can't block uninstall for an app that is not installed or enabled.
12862                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12863                return false;
12864            }
12865            ps.setBlockUninstall(blockUninstall, userId);
12866            mSettings.writePackageRestrictionsLPr(userId);
12867        }
12868        return true;
12869    }
12870
12871    @Override
12872    public boolean getBlockUninstallForUser(String packageName, int userId) {
12873        synchronized (mPackages) {
12874            PackageSetting ps = mSettings.mPackages.get(packageName);
12875            if (ps == null) {
12876                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12877                return false;
12878            }
12879            return ps.getBlockUninstall(userId);
12880        }
12881    }
12882
12883    /*
12884     * This method handles package deletion in general
12885     */
12886    private boolean deletePackageLI(String packageName, UserHandle user,
12887            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12888            int flags, PackageRemovedInfo outInfo,
12889            boolean writeSettings) {
12890        if (packageName == null) {
12891            Slog.w(TAG, "Attempt to delete null packageName.");
12892            return false;
12893        }
12894        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12895        PackageSetting ps;
12896        boolean dataOnly = false;
12897        int removeUser = -1;
12898        int appId = -1;
12899        synchronized (mPackages) {
12900            ps = mSettings.mPackages.get(packageName);
12901            if (ps == null) {
12902                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12903                return false;
12904            }
12905            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12906                    && user.getIdentifier() != UserHandle.USER_ALL) {
12907                // The caller is asking that the package only be deleted for a single
12908                // user.  To do this, we just mark its uninstalled state and delete
12909                // its data.  If this is a system app, we only allow this to happen if
12910                // they have set the special DELETE_SYSTEM_APP which requests different
12911                // semantics than normal for uninstalling system apps.
12912                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12913                ps.setUserState(user.getIdentifier(),
12914                        COMPONENT_ENABLED_STATE_DEFAULT,
12915                        false, //installed
12916                        true,  //stopped
12917                        true,  //notLaunched
12918                        false, //hidden
12919                        null, null, null,
12920                        false, // blockUninstall
12921                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12922                if (!isSystemApp(ps)) {
12923                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12924                        // Other user still have this package installed, so all
12925                        // we need to do is clear this user's data and save that
12926                        // it is uninstalled.
12927                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12928                        removeUser = user.getIdentifier();
12929                        appId = ps.appId;
12930                        scheduleWritePackageRestrictionsLocked(removeUser);
12931                    } else {
12932                        // We need to set it back to 'installed' so the uninstall
12933                        // broadcasts will be sent correctly.
12934                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12935                        ps.setInstalled(true, user.getIdentifier());
12936                    }
12937                } else {
12938                    // This is a system app, so we assume that the
12939                    // other users still have this package installed, so all
12940                    // we need to do is clear this user's data and save that
12941                    // it is uninstalled.
12942                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12943                    removeUser = user.getIdentifier();
12944                    appId = ps.appId;
12945                    scheduleWritePackageRestrictionsLocked(removeUser);
12946                }
12947            }
12948        }
12949
12950        if (removeUser >= 0) {
12951            // From above, we determined that we are deleting this only
12952            // for a single user.  Continue the work here.
12953            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12954            if (outInfo != null) {
12955                outInfo.removedPackage = packageName;
12956                outInfo.removedAppId = appId;
12957                outInfo.removedUsers = new int[] {removeUser};
12958            }
12959            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12960            removeKeystoreDataIfNeeded(removeUser, appId);
12961            schedulePackageCleaning(packageName, removeUser, false);
12962            synchronized (mPackages) {
12963                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12964                    scheduleWritePackageRestrictionsLocked(removeUser);
12965                }
12966                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
12967            }
12968            return true;
12969        }
12970
12971        if (dataOnly) {
12972            // Delete application data first
12973            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12974            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12975            return true;
12976        }
12977
12978        boolean ret = false;
12979        if (isSystemApp(ps)) {
12980            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12981            // When an updated system application is deleted we delete the existing resources as well and
12982            // fall back to existing code in system partition
12983            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12984                    flags, outInfo, writeSettings);
12985        } else {
12986            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12987            // Kill application pre-emptively especially for apps on sd.
12988            killApplication(packageName, ps.appId, "uninstall pkg");
12989            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12990                    allUserHandles, perUserInstalled,
12991                    outInfo, writeSettings);
12992        }
12993
12994        return ret;
12995    }
12996
12997    private final class ClearStorageConnection implements ServiceConnection {
12998        IMediaContainerService mContainerService;
12999
13000        @Override
13001        public void onServiceConnected(ComponentName name, IBinder service) {
13002            synchronized (this) {
13003                mContainerService = IMediaContainerService.Stub.asInterface(service);
13004                notifyAll();
13005            }
13006        }
13007
13008        @Override
13009        public void onServiceDisconnected(ComponentName name) {
13010        }
13011    }
13012
13013    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13014        final boolean mounted;
13015        if (Environment.isExternalStorageEmulated()) {
13016            mounted = true;
13017        } else {
13018            final String status = Environment.getExternalStorageState();
13019
13020            mounted = status.equals(Environment.MEDIA_MOUNTED)
13021                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13022        }
13023
13024        if (!mounted) {
13025            return;
13026        }
13027
13028        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13029        int[] users;
13030        if (userId == UserHandle.USER_ALL) {
13031            users = sUserManager.getUserIds();
13032        } else {
13033            users = new int[] { userId };
13034        }
13035        final ClearStorageConnection conn = new ClearStorageConnection();
13036        if (mContext.bindServiceAsUser(
13037                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13038            try {
13039                for (int curUser : users) {
13040                    long timeout = SystemClock.uptimeMillis() + 5000;
13041                    synchronized (conn) {
13042                        long now = SystemClock.uptimeMillis();
13043                        while (conn.mContainerService == null && now < timeout) {
13044                            try {
13045                                conn.wait(timeout - now);
13046                            } catch (InterruptedException e) {
13047                            }
13048                        }
13049                    }
13050                    if (conn.mContainerService == null) {
13051                        return;
13052                    }
13053
13054                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13055                    clearDirectory(conn.mContainerService,
13056                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13057                    if (allData) {
13058                        clearDirectory(conn.mContainerService,
13059                                userEnv.buildExternalStorageAppDataDirs(packageName));
13060                        clearDirectory(conn.mContainerService,
13061                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13062                    }
13063                }
13064            } finally {
13065                mContext.unbindService(conn);
13066            }
13067        }
13068    }
13069
13070    @Override
13071    public void clearApplicationUserData(final String packageName,
13072            final IPackageDataObserver observer, final int userId) {
13073        mContext.enforceCallingOrSelfPermission(
13074                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13075        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13076        // Queue up an async operation since the package deletion may take a little while.
13077        mHandler.post(new Runnable() {
13078            public void run() {
13079                mHandler.removeCallbacks(this);
13080                final boolean succeeded;
13081                synchronized (mInstallLock) {
13082                    succeeded = clearApplicationUserDataLI(packageName, userId);
13083                }
13084                clearExternalStorageDataSync(packageName, userId, true);
13085                if (succeeded) {
13086                    // invoke DeviceStorageMonitor's update method to clear any notifications
13087                    DeviceStorageMonitorInternal
13088                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13089                    if (dsm != null) {
13090                        dsm.checkMemory();
13091                    }
13092                }
13093                if(observer != null) {
13094                    try {
13095                        observer.onRemoveCompleted(packageName, succeeded);
13096                    } catch (RemoteException e) {
13097                        Log.i(TAG, "Observer no longer exists.");
13098                    }
13099                } //end if observer
13100            } //end run
13101        });
13102    }
13103
13104    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13105        if (packageName == null) {
13106            Slog.w(TAG, "Attempt to delete null packageName.");
13107            return false;
13108        }
13109
13110        // Try finding details about the requested package
13111        PackageParser.Package pkg;
13112        synchronized (mPackages) {
13113            pkg = mPackages.get(packageName);
13114            if (pkg == null) {
13115                final PackageSetting ps = mSettings.mPackages.get(packageName);
13116                if (ps != null) {
13117                    pkg = ps.pkg;
13118                }
13119            }
13120
13121            if (pkg == null) {
13122                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13123                return false;
13124            }
13125
13126            PackageSetting ps = (PackageSetting) pkg.mExtras;
13127            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13128        }
13129
13130        // Always delete data directories for package, even if we found no other
13131        // record of app. This helps users recover from UID mismatches without
13132        // resorting to a full data wipe.
13133        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13134        if (retCode < 0) {
13135            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13136            return false;
13137        }
13138
13139        final int appId = pkg.applicationInfo.uid;
13140        removeKeystoreDataIfNeeded(userId, appId);
13141
13142        // Create a native library symlink only if we have native libraries
13143        // and if the native libraries are 32 bit libraries. We do not provide
13144        // this symlink for 64 bit libraries.
13145        if (pkg.applicationInfo.primaryCpuAbi != null &&
13146                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13147            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13148            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13149                    nativeLibPath, userId) < 0) {
13150                Slog.w(TAG, "Failed linking native library dir");
13151                return false;
13152            }
13153        }
13154
13155        return true;
13156    }
13157
13158    /**
13159     * Reverts user permission state changes (permissions and flags).
13160     *
13161     * @param ps The package for which to reset.
13162     * @param userId The device user for which to do a reset.
13163     */
13164    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13165            final PackageSetting ps, final int userId) {
13166        if (ps.pkg == null) {
13167            return;
13168        }
13169
13170        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13171                | FLAG_PERMISSION_USER_FIXED
13172                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13173
13174        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13175                | FLAG_PERMISSION_POLICY_FIXED;
13176
13177        boolean writeInstallPermissions = false;
13178        boolean writeRuntimePermissions = false;
13179
13180        final int permissionCount = ps.pkg.requestedPermissions.size();
13181        for (int i = 0; i < permissionCount; i++) {
13182            String permission = ps.pkg.requestedPermissions.get(i);
13183
13184            BasePermission bp = mSettings.mPermissions.get(permission);
13185            if (bp == null) {
13186                continue;
13187            }
13188
13189            // If shared user we just reset the state to which only this app contributed.
13190            if (ps.sharedUser != null) {
13191                boolean used = false;
13192                final int packageCount = ps.sharedUser.packages.size();
13193                for (int j = 0; j < packageCount; j++) {
13194                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13195                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13196                            && pkg.pkg.requestedPermissions.contains(permission)) {
13197                        used = true;
13198                        break;
13199                    }
13200                }
13201                if (used) {
13202                    continue;
13203                }
13204            }
13205
13206            PermissionsState permissionsState = ps.getPermissionsState();
13207
13208            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13209
13210            // Always clear the user settable flags.
13211            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13212                    bp.name) != null;
13213            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13214                if (hasInstallState) {
13215                    writeInstallPermissions = true;
13216                } else {
13217                    writeRuntimePermissions = true;
13218                }
13219            }
13220
13221            // Below is only runtime permission handling.
13222            if (!bp.isRuntime()) {
13223                continue;
13224            }
13225
13226            // Never clobber system or policy.
13227            if ((oldFlags & policyOrSystemFlags) != 0) {
13228                continue;
13229            }
13230
13231            // If this permission was granted by default, make sure it is.
13232            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13233                if (permissionsState.grantRuntimePermission(bp, userId)
13234                        != PERMISSION_OPERATION_FAILURE) {
13235                    writeRuntimePermissions = true;
13236                }
13237            } else {
13238                // Otherwise, reset the permission.
13239                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13240                switch (revokeResult) {
13241                    case PERMISSION_OPERATION_SUCCESS: {
13242                        writeRuntimePermissions = true;
13243                    } break;
13244
13245                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13246                        writeRuntimePermissions = true;
13247                        // If gids changed for this user, kill all affected packages.
13248                        mHandler.post(new Runnable() {
13249                            @Override
13250                            public void run() {
13251                                // This has to happen with no lock held.
13252                                killSettingPackagesForUser(ps, userId,
13253                                        KILL_APP_REASON_GIDS_CHANGED);
13254                            }
13255                        });
13256                    } break;
13257                }
13258            }
13259        }
13260
13261        // Synchronously write as we are taking permissions away.
13262        if (writeRuntimePermissions) {
13263            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13264        }
13265
13266        // Synchronously write as we are taking permissions away.
13267        if (writeInstallPermissions) {
13268            mSettings.writeLPr();
13269        }
13270    }
13271
13272    /**
13273     * Remove entries from the keystore daemon. Will only remove it if the
13274     * {@code appId} is valid.
13275     */
13276    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13277        if (appId < 0) {
13278            return;
13279        }
13280
13281        final KeyStore keyStore = KeyStore.getInstance();
13282        if (keyStore != null) {
13283            if (userId == UserHandle.USER_ALL) {
13284                for (final int individual : sUserManager.getUserIds()) {
13285                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13286                }
13287            } else {
13288                keyStore.clearUid(UserHandle.getUid(userId, appId));
13289            }
13290        } else {
13291            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13292        }
13293    }
13294
13295    @Override
13296    public void deleteApplicationCacheFiles(final String packageName,
13297            final IPackageDataObserver observer) {
13298        mContext.enforceCallingOrSelfPermission(
13299                android.Manifest.permission.DELETE_CACHE_FILES, null);
13300        // Queue up an async operation since the package deletion may take a little while.
13301        final int userId = UserHandle.getCallingUserId();
13302        mHandler.post(new Runnable() {
13303            public void run() {
13304                mHandler.removeCallbacks(this);
13305                final boolean succeded;
13306                synchronized (mInstallLock) {
13307                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13308                }
13309                clearExternalStorageDataSync(packageName, userId, false);
13310                if (observer != null) {
13311                    try {
13312                        observer.onRemoveCompleted(packageName, succeded);
13313                    } catch (RemoteException e) {
13314                        Log.i(TAG, "Observer no longer exists.");
13315                    }
13316                } //end if observer
13317            } //end run
13318        });
13319    }
13320
13321    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13322        if (packageName == null) {
13323            Slog.w(TAG, "Attempt to delete null packageName.");
13324            return false;
13325        }
13326        PackageParser.Package p;
13327        synchronized (mPackages) {
13328            p = mPackages.get(packageName);
13329        }
13330        if (p == null) {
13331            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13332            return false;
13333        }
13334        final ApplicationInfo applicationInfo = p.applicationInfo;
13335        if (applicationInfo == null) {
13336            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13337            return false;
13338        }
13339        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13340        if (retCode < 0) {
13341            Slog.w(TAG, "Couldn't remove cache files for package: "
13342                       + packageName + " u" + userId);
13343            return false;
13344        }
13345        return true;
13346    }
13347
13348    @Override
13349    public void getPackageSizeInfo(final String packageName, int userHandle,
13350            final IPackageStatsObserver observer) {
13351        mContext.enforceCallingOrSelfPermission(
13352                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13353        if (packageName == null) {
13354            throw new IllegalArgumentException("Attempt to get size of null packageName");
13355        }
13356
13357        PackageStats stats = new PackageStats(packageName, userHandle);
13358
13359        /*
13360         * Queue up an async operation since the package measurement may take a
13361         * little while.
13362         */
13363        Message msg = mHandler.obtainMessage(INIT_COPY);
13364        msg.obj = new MeasureParams(stats, observer);
13365        mHandler.sendMessage(msg);
13366    }
13367
13368    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13369            PackageStats pStats) {
13370        if (packageName == null) {
13371            Slog.w(TAG, "Attempt to get size of null packageName.");
13372            return false;
13373        }
13374        PackageParser.Package p;
13375        boolean dataOnly = false;
13376        String libDirRoot = null;
13377        String asecPath = null;
13378        PackageSetting ps = null;
13379        synchronized (mPackages) {
13380            p = mPackages.get(packageName);
13381            ps = mSettings.mPackages.get(packageName);
13382            if(p == null) {
13383                dataOnly = true;
13384                if((ps == null) || (ps.pkg == null)) {
13385                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13386                    return false;
13387                }
13388                p = ps.pkg;
13389            }
13390            if (ps != null) {
13391                libDirRoot = ps.legacyNativeLibraryPathString;
13392            }
13393            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13394                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13395                if (secureContainerId != null) {
13396                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13397                }
13398            }
13399        }
13400        String publicSrcDir = null;
13401        if(!dataOnly) {
13402            final ApplicationInfo applicationInfo = p.applicationInfo;
13403            if (applicationInfo == null) {
13404                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13405                return false;
13406            }
13407            if (p.isForwardLocked()) {
13408                publicSrcDir = applicationInfo.getBaseResourcePath();
13409            }
13410        }
13411        // TODO: extend to measure size of split APKs
13412        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13413        // not just the first level.
13414        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13415        // just the primary.
13416        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13417        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13418                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13419        if (res < 0) {
13420            return false;
13421        }
13422
13423        // Fix-up for forward-locked applications in ASEC containers.
13424        if (!isExternal(p)) {
13425            pStats.codeSize += pStats.externalCodeSize;
13426            pStats.externalCodeSize = 0L;
13427        }
13428
13429        return true;
13430    }
13431
13432
13433    @Override
13434    public void addPackageToPreferred(String packageName) {
13435        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13436    }
13437
13438    @Override
13439    public void removePackageFromPreferred(String packageName) {
13440        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13441    }
13442
13443    @Override
13444    public List<PackageInfo> getPreferredPackages(int flags) {
13445        return new ArrayList<PackageInfo>();
13446    }
13447
13448    private int getUidTargetSdkVersionLockedLPr(int uid) {
13449        Object obj = mSettings.getUserIdLPr(uid);
13450        if (obj instanceof SharedUserSetting) {
13451            final SharedUserSetting sus = (SharedUserSetting) obj;
13452            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13453            final Iterator<PackageSetting> it = sus.packages.iterator();
13454            while (it.hasNext()) {
13455                final PackageSetting ps = it.next();
13456                if (ps.pkg != null) {
13457                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13458                    if (v < vers) vers = v;
13459                }
13460            }
13461            return vers;
13462        } else if (obj instanceof PackageSetting) {
13463            final PackageSetting ps = (PackageSetting) obj;
13464            if (ps.pkg != null) {
13465                return ps.pkg.applicationInfo.targetSdkVersion;
13466            }
13467        }
13468        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13469    }
13470
13471    @Override
13472    public void addPreferredActivity(IntentFilter filter, int match,
13473            ComponentName[] set, ComponentName activity, int userId) {
13474        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13475                "Adding preferred");
13476    }
13477
13478    private void addPreferredActivityInternal(IntentFilter filter, int match,
13479            ComponentName[] set, ComponentName activity, boolean always, int userId,
13480            String opname) {
13481        // writer
13482        int callingUid = Binder.getCallingUid();
13483        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13484        if (filter.countActions() == 0) {
13485            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13486            return;
13487        }
13488        synchronized (mPackages) {
13489            if (mContext.checkCallingOrSelfPermission(
13490                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13491                    != PackageManager.PERMISSION_GRANTED) {
13492                if (getUidTargetSdkVersionLockedLPr(callingUid)
13493                        < Build.VERSION_CODES.FROYO) {
13494                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13495                            + callingUid);
13496                    return;
13497                }
13498                mContext.enforceCallingOrSelfPermission(
13499                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13500            }
13501
13502            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13503            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13504                    + userId + ":");
13505            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13506            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13507            scheduleWritePackageRestrictionsLocked(userId);
13508        }
13509    }
13510
13511    @Override
13512    public void replacePreferredActivity(IntentFilter filter, int match,
13513            ComponentName[] set, ComponentName activity, int userId) {
13514        if (filter.countActions() != 1) {
13515            throw new IllegalArgumentException(
13516                    "replacePreferredActivity expects filter to have only 1 action.");
13517        }
13518        if (filter.countDataAuthorities() != 0
13519                || filter.countDataPaths() != 0
13520                || filter.countDataSchemes() > 1
13521                || filter.countDataTypes() != 0) {
13522            throw new IllegalArgumentException(
13523                    "replacePreferredActivity expects filter to have no data authorities, " +
13524                    "paths, or types; and at most one scheme.");
13525        }
13526
13527        final int callingUid = Binder.getCallingUid();
13528        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13529        synchronized (mPackages) {
13530            if (mContext.checkCallingOrSelfPermission(
13531                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13532                    != PackageManager.PERMISSION_GRANTED) {
13533                if (getUidTargetSdkVersionLockedLPr(callingUid)
13534                        < Build.VERSION_CODES.FROYO) {
13535                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13536                            + Binder.getCallingUid());
13537                    return;
13538                }
13539                mContext.enforceCallingOrSelfPermission(
13540                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13541            }
13542
13543            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13544            if (pir != null) {
13545                // Get all of the existing entries that exactly match this filter.
13546                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13547                if (existing != null && existing.size() == 1) {
13548                    PreferredActivity cur = existing.get(0);
13549                    if (DEBUG_PREFERRED) {
13550                        Slog.i(TAG, "Checking replace of preferred:");
13551                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13552                        if (!cur.mPref.mAlways) {
13553                            Slog.i(TAG, "  -- CUR; not mAlways!");
13554                        } else {
13555                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13556                            Slog.i(TAG, "  -- CUR: mSet="
13557                                    + Arrays.toString(cur.mPref.mSetComponents));
13558                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13559                            Slog.i(TAG, "  -- NEW: mMatch="
13560                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13561                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13562                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13563                        }
13564                    }
13565                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13566                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13567                            && cur.mPref.sameSet(set)) {
13568                        // Setting the preferred activity to what it happens to be already
13569                        if (DEBUG_PREFERRED) {
13570                            Slog.i(TAG, "Replacing with same preferred activity "
13571                                    + cur.mPref.mShortComponent + " for user "
13572                                    + userId + ":");
13573                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13574                        }
13575                        return;
13576                    }
13577                }
13578
13579                if (existing != null) {
13580                    if (DEBUG_PREFERRED) {
13581                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13582                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13583                    }
13584                    for (int i = 0; i < existing.size(); i++) {
13585                        PreferredActivity pa = existing.get(i);
13586                        if (DEBUG_PREFERRED) {
13587                            Slog.i(TAG, "Removing existing preferred activity "
13588                                    + pa.mPref.mComponent + ":");
13589                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13590                        }
13591                        pir.removeFilter(pa);
13592                    }
13593                }
13594            }
13595            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13596                    "Replacing preferred");
13597        }
13598    }
13599
13600    @Override
13601    public void clearPackagePreferredActivities(String packageName) {
13602        final int uid = Binder.getCallingUid();
13603        // writer
13604        synchronized (mPackages) {
13605            PackageParser.Package pkg = mPackages.get(packageName);
13606            if (pkg == null || pkg.applicationInfo.uid != uid) {
13607                if (mContext.checkCallingOrSelfPermission(
13608                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13609                        != PackageManager.PERMISSION_GRANTED) {
13610                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13611                            < Build.VERSION_CODES.FROYO) {
13612                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13613                                + Binder.getCallingUid());
13614                        return;
13615                    }
13616                    mContext.enforceCallingOrSelfPermission(
13617                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13618                }
13619            }
13620
13621            int user = UserHandle.getCallingUserId();
13622            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13623                scheduleWritePackageRestrictionsLocked(user);
13624            }
13625        }
13626    }
13627
13628    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13629    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13630        ArrayList<PreferredActivity> removed = null;
13631        boolean changed = false;
13632        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13633            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13634            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13635            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13636                continue;
13637            }
13638            Iterator<PreferredActivity> it = pir.filterIterator();
13639            while (it.hasNext()) {
13640                PreferredActivity pa = it.next();
13641                // Mark entry for removal only if it matches the package name
13642                // and the entry is of type "always".
13643                if (packageName == null ||
13644                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13645                                && pa.mPref.mAlways)) {
13646                    if (removed == null) {
13647                        removed = new ArrayList<PreferredActivity>();
13648                    }
13649                    removed.add(pa);
13650                }
13651            }
13652            if (removed != null) {
13653                for (int j=0; j<removed.size(); j++) {
13654                    PreferredActivity pa = removed.get(j);
13655                    pir.removeFilter(pa);
13656                }
13657                changed = true;
13658            }
13659        }
13660        return changed;
13661    }
13662
13663    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13664    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13665        if (userId == UserHandle.USER_ALL) {
13666            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13667                    sUserManager.getUserIds())) {
13668                for (int oneUserId : sUserManager.getUserIds()) {
13669                    scheduleWritePackageRestrictionsLocked(oneUserId);
13670                }
13671            }
13672        } else {
13673            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13674                scheduleWritePackageRestrictionsLocked(userId);
13675            }
13676        }
13677    }
13678
13679
13680    void clearDefaultBrowserIfNeeded(String packageName) {
13681        for (int oneUserId : sUserManager.getUserIds()) {
13682            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13683            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13684            if (packageName.equals(defaultBrowserPackageName)) {
13685                setDefaultBrowserPackageName(null, oneUserId);
13686            }
13687        }
13688    }
13689
13690    @Override
13691    public void resetPreferredActivities(int userId) {
13692        mContext.enforceCallingOrSelfPermission(
13693                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13694        // writer
13695        synchronized (mPackages) {
13696            clearPackagePreferredActivitiesLPw(null, userId);
13697            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13698            applyFactoryDefaultBrowserLPw(userId);
13699            primeDomainVerificationsLPw(userId);
13700
13701            scheduleWritePackageRestrictionsLocked(userId);
13702        }
13703    }
13704
13705    @Override
13706    public int getPreferredActivities(List<IntentFilter> outFilters,
13707            List<ComponentName> outActivities, String packageName) {
13708
13709        int num = 0;
13710        final int userId = UserHandle.getCallingUserId();
13711        // reader
13712        synchronized (mPackages) {
13713            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13714            if (pir != null) {
13715                final Iterator<PreferredActivity> it = pir.filterIterator();
13716                while (it.hasNext()) {
13717                    final PreferredActivity pa = it.next();
13718                    if (packageName == null
13719                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13720                                    && pa.mPref.mAlways)) {
13721                        if (outFilters != null) {
13722                            outFilters.add(new IntentFilter(pa));
13723                        }
13724                        if (outActivities != null) {
13725                            outActivities.add(pa.mPref.mComponent);
13726                        }
13727                    }
13728                }
13729            }
13730        }
13731
13732        return num;
13733    }
13734
13735    @Override
13736    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13737            int userId) {
13738        int callingUid = Binder.getCallingUid();
13739        if (callingUid != Process.SYSTEM_UID) {
13740            throw new SecurityException(
13741                    "addPersistentPreferredActivity can only be run by the system");
13742        }
13743        if (filter.countActions() == 0) {
13744            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13745            return;
13746        }
13747        synchronized (mPackages) {
13748            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13749                    " :");
13750            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13751            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13752                    new PersistentPreferredActivity(filter, activity));
13753            scheduleWritePackageRestrictionsLocked(userId);
13754        }
13755    }
13756
13757    @Override
13758    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13759        int callingUid = Binder.getCallingUid();
13760        if (callingUid != Process.SYSTEM_UID) {
13761            throw new SecurityException(
13762                    "clearPackagePersistentPreferredActivities can only be run by the system");
13763        }
13764        ArrayList<PersistentPreferredActivity> removed = null;
13765        boolean changed = false;
13766        synchronized (mPackages) {
13767            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13768                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13769                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13770                        .valueAt(i);
13771                if (userId != thisUserId) {
13772                    continue;
13773                }
13774                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13775                while (it.hasNext()) {
13776                    PersistentPreferredActivity ppa = it.next();
13777                    // Mark entry for removal only if it matches the package name.
13778                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13779                        if (removed == null) {
13780                            removed = new ArrayList<PersistentPreferredActivity>();
13781                        }
13782                        removed.add(ppa);
13783                    }
13784                }
13785                if (removed != null) {
13786                    for (int j=0; j<removed.size(); j++) {
13787                        PersistentPreferredActivity ppa = removed.get(j);
13788                        ppir.removeFilter(ppa);
13789                    }
13790                    changed = true;
13791                }
13792            }
13793
13794            if (changed) {
13795                scheduleWritePackageRestrictionsLocked(userId);
13796            }
13797        }
13798    }
13799
13800    /**
13801     * Common machinery for picking apart a restored XML blob and passing
13802     * it to a caller-supplied functor to be applied to the running system.
13803     */
13804    private void restoreFromXml(XmlPullParser parser, int userId,
13805            String expectedStartTag, BlobXmlRestorer functor)
13806            throws IOException, XmlPullParserException {
13807        int type;
13808        while ((type = parser.next()) != XmlPullParser.START_TAG
13809                && type != XmlPullParser.END_DOCUMENT) {
13810        }
13811        if (type != XmlPullParser.START_TAG) {
13812            // oops didn't find a start tag?!
13813            if (DEBUG_BACKUP) {
13814                Slog.e(TAG, "Didn't find start tag during restore");
13815            }
13816            return;
13817        }
13818
13819        // this is supposed to be TAG_PREFERRED_BACKUP
13820        if (!expectedStartTag.equals(parser.getName())) {
13821            if (DEBUG_BACKUP) {
13822                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13823            }
13824            return;
13825        }
13826
13827        // skip interfering stuff, then we're aligned with the backing implementation
13828        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13829        functor.apply(parser, userId);
13830    }
13831
13832    private interface BlobXmlRestorer {
13833        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13834    }
13835
13836    /**
13837     * Non-Binder method, support for the backup/restore mechanism: write the
13838     * full set of preferred activities in its canonical XML format.  Returns the
13839     * XML output as a byte array, or null if there is none.
13840     */
13841    @Override
13842    public byte[] getPreferredActivityBackup(int userId) {
13843        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13844            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13845        }
13846
13847        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13848        try {
13849            final XmlSerializer serializer = new FastXmlSerializer();
13850            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13851            serializer.startDocument(null, true);
13852            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13853
13854            synchronized (mPackages) {
13855                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13856            }
13857
13858            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13859            serializer.endDocument();
13860            serializer.flush();
13861        } catch (Exception e) {
13862            if (DEBUG_BACKUP) {
13863                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13864            }
13865            return null;
13866        }
13867
13868        return dataStream.toByteArray();
13869    }
13870
13871    @Override
13872    public void restorePreferredActivities(byte[] backup, int userId) {
13873        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13874            throw new SecurityException("Only the system may call restorePreferredActivities()");
13875        }
13876
13877        try {
13878            final XmlPullParser parser = Xml.newPullParser();
13879            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13880            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13881                    new BlobXmlRestorer() {
13882                        @Override
13883                        public void apply(XmlPullParser parser, int userId)
13884                                throws XmlPullParserException, IOException {
13885                            synchronized (mPackages) {
13886                                mSettings.readPreferredActivitiesLPw(parser, userId);
13887                            }
13888                        }
13889                    } );
13890        } catch (Exception e) {
13891            if (DEBUG_BACKUP) {
13892                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13893            }
13894        }
13895    }
13896
13897    /**
13898     * Non-Binder method, support for the backup/restore mechanism: write the
13899     * default browser (etc) settings in its canonical XML format.  Returns the default
13900     * browser XML representation as a byte array, or null if there is none.
13901     */
13902    @Override
13903    public byte[] getDefaultAppsBackup(int userId) {
13904        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13905            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13906        }
13907
13908        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13909        try {
13910            final XmlSerializer serializer = new FastXmlSerializer();
13911            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13912            serializer.startDocument(null, true);
13913            serializer.startTag(null, TAG_DEFAULT_APPS);
13914
13915            synchronized (mPackages) {
13916                mSettings.writeDefaultAppsLPr(serializer, userId);
13917            }
13918
13919            serializer.endTag(null, TAG_DEFAULT_APPS);
13920            serializer.endDocument();
13921            serializer.flush();
13922        } catch (Exception e) {
13923            if (DEBUG_BACKUP) {
13924                Slog.e(TAG, "Unable to write default apps for backup", e);
13925            }
13926            return null;
13927        }
13928
13929        return dataStream.toByteArray();
13930    }
13931
13932    @Override
13933    public void restoreDefaultApps(byte[] backup, int userId) {
13934        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13935            throw new SecurityException("Only the system may call restoreDefaultApps()");
13936        }
13937
13938        try {
13939            final XmlPullParser parser = Xml.newPullParser();
13940            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13941            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13942                    new BlobXmlRestorer() {
13943                        @Override
13944                        public void apply(XmlPullParser parser, int userId)
13945                                throws XmlPullParserException, IOException {
13946                            synchronized (mPackages) {
13947                                mSettings.readDefaultAppsLPw(parser, userId);
13948                            }
13949                        }
13950                    } );
13951        } catch (Exception e) {
13952            if (DEBUG_BACKUP) {
13953                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13954            }
13955        }
13956    }
13957
13958    @Override
13959    public byte[] getIntentFilterVerificationBackup(int userId) {
13960        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13961            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13962        }
13963
13964        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13965        try {
13966            final XmlSerializer serializer = new FastXmlSerializer();
13967            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13968            serializer.startDocument(null, true);
13969            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13970
13971            synchronized (mPackages) {
13972                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13973            }
13974
13975            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13976            serializer.endDocument();
13977            serializer.flush();
13978        } catch (Exception e) {
13979            if (DEBUG_BACKUP) {
13980                Slog.e(TAG, "Unable to write default apps for backup", e);
13981            }
13982            return null;
13983        }
13984
13985        return dataStream.toByteArray();
13986    }
13987
13988    @Override
13989    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13990        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13991            throw new SecurityException("Only the system may call restorePreferredActivities()");
13992        }
13993
13994        try {
13995            final XmlPullParser parser = Xml.newPullParser();
13996            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13997            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13998                    new BlobXmlRestorer() {
13999                        @Override
14000                        public void apply(XmlPullParser parser, int userId)
14001                                throws XmlPullParserException, IOException {
14002                            synchronized (mPackages) {
14003                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14004                                mSettings.writeLPr();
14005                            }
14006                        }
14007                    } );
14008        } catch (Exception e) {
14009            if (DEBUG_BACKUP) {
14010                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14011            }
14012        }
14013    }
14014
14015    @Override
14016    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14017            int sourceUserId, int targetUserId, int flags) {
14018        mContext.enforceCallingOrSelfPermission(
14019                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14020        int callingUid = Binder.getCallingUid();
14021        enforceOwnerRights(ownerPackage, callingUid);
14022        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14023        if (intentFilter.countActions() == 0) {
14024            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14025            return;
14026        }
14027        synchronized (mPackages) {
14028            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14029                    ownerPackage, targetUserId, flags);
14030            CrossProfileIntentResolver resolver =
14031                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14032            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14033            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14034            if (existing != null) {
14035                int size = existing.size();
14036                for (int i = 0; i < size; i++) {
14037                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14038                        return;
14039                    }
14040                }
14041            }
14042            resolver.addFilter(newFilter);
14043            scheduleWritePackageRestrictionsLocked(sourceUserId);
14044        }
14045    }
14046
14047    @Override
14048    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14049        mContext.enforceCallingOrSelfPermission(
14050                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14051        int callingUid = Binder.getCallingUid();
14052        enforceOwnerRights(ownerPackage, callingUid);
14053        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14054        synchronized (mPackages) {
14055            CrossProfileIntentResolver resolver =
14056                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14057            ArraySet<CrossProfileIntentFilter> set =
14058                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14059            for (CrossProfileIntentFilter filter : set) {
14060                if (filter.getOwnerPackage().equals(ownerPackage)) {
14061                    resolver.removeFilter(filter);
14062                }
14063            }
14064            scheduleWritePackageRestrictionsLocked(sourceUserId);
14065        }
14066    }
14067
14068    // Enforcing that callingUid is owning pkg on userId
14069    private void enforceOwnerRights(String pkg, int callingUid) {
14070        // The system owns everything.
14071        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14072            return;
14073        }
14074        int callingUserId = UserHandle.getUserId(callingUid);
14075        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14076        if (pi == null) {
14077            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14078                    + callingUserId);
14079        }
14080        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14081            throw new SecurityException("Calling uid " + callingUid
14082                    + " does not own package " + pkg);
14083        }
14084    }
14085
14086    @Override
14087    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14088        Intent intent = new Intent(Intent.ACTION_MAIN);
14089        intent.addCategory(Intent.CATEGORY_HOME);
14090
14091        final int callingUserId = UserHandle.getCallingUserId();
14092        List<ResolveInfo> list = queryIntentActivities(intent, null,
14093                PackageManager.GET_META_DATA, callingUserId);
14094        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14095                true, false, false, callingUserId);
14096
14097        allHomeCandidates.clear();
14098        if (list != null) {
14099            for (ResolveInfo ri : list) {
14100                allHomeCandidates.add(ri);
14101            }
14102        }
14103        return (preferred == null || preferred.activityInfo == null)
14104                ? null
14105                : new ComponentName(preferred.activityInfo.packageName,
14106                        preferred.activityInfo.name);
14107    }
14108
14109    @Override
14110    public void setApplicationEnabledSetting(String appPackageName,
14111            int newState, int flags, int userId, String callingPackage) {
14112        if (!sUserManager.exists(userId)) return;
14113        if (callingPackage == null) {
14114            callingPackage = Integer.toString(Binder.getCallingUid());
14115        }
14116        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14117    }
14118
14119    @Override
14120    public void setComponentEnabledSetting(ComponentName componentName,
14121            int newState, int flags, int userId) {
14122        if (!sUserManager.exists(userId)) return;
14123        setEnabledSetting(componentName.getPackageName(),
14124                componentName.getClassName(), newState, flags, userId, null);
14125    }
14126
14127    private void setEnabledSetting(final String packageName, String className, int newState,
14128            final int flags, int userId, String callingPackage) {
14129        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14130              || newState == COMPONENT_ENABLED_STATE_ENABLED
14131              || newState == COMPONENT_ENABLED_STATE_DISABLED
14132              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14133              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14134            throw new IllegalArgumentException("Invalid new component state: "
14135                    + newState);
14136        }
14137        PackageSetting pkgSetting;
14138        final int uid = Binder.getCallingUid();
14139        final int permission = mContext.checkCallingOrSelfPermission(
14140                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14141        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14142        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14143        boolean sendNow = false;
14144        boolean isApp = (className == null);
14145        String componentName = isApp ? packageName : className;
14146        int packageUid = -1;
14147        ArrayList<String> components;
14148
14149        // writer
14150        synchronized (mPackages) {
14151            pkgSetting = mSettings.mPackages.get(packageName);
14152            if (pkgSetting == null) {
14153                if (className == null) {
14154                    throw new IllegalArgumentException(
14155                            "Unknown package: " + packageName);
14156                }
14157                throw new IllegalArgumentException(
14158                        "Unknown component: " + packageName
14159                        + "/" + className);
14160            }
14161            // Allow root and verify that userId is not being specified by a different user
14162            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14163                throw new SecurityException(
14164                        "Permission Denial: attempt to change component state from pid="
14165                        + Binder.getCallingPid()
14166                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14167            }
14168            if (className == null) {
14169                // We're dealing with an application/package level state change
14170                if (pkgSetting.getEnabled(userId) == newState) {
14171                    // Nothing to do
14172                    return;
14173                }
14174                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14175                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14176                    // Don't care about who enables an app.
14177                    callingPackage = null;
14178                }
14179                pkgSetting.setEnabled(newState, userId, callingPackage);
14180                // pkgSetting.pkg.mSetEnabled = newState;
14181            } else {
14182                // We're dealing with a component level state change
14183                // First, verify that this is a valid class name.
14184                PackageParser.Package pkg = pkgSetting.pkg;
14185                if (pkg == null || !pkg.hasComponentClassName(className)) {
14186                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14187                        throw new IllegalArgumentException("Component class " + className
14188                                + " does not exist in " + packageName);
14189                    } else {
14190                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14191                                + className + " does not exist in " + packageName);
14192                    }
14193                }
14194                switch (newState) {
14195                case COMPONENT_ENABLED_STATE_ENABLED:
14196                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14197                        return;
14198                    }
14199                    break;
14200                case COMPONENT_ENABLED_STATE_DISABLED:
14201                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14202                        return;
14203                    }
14204                    break;
14205                case COMPONENT_ENABLED_STATE_DEFAULT:
14206                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14207                        return;
14208                    }
14209                    break;
14210                default:
14211                    Slog.e(TAG, "Invalid new component state: " + newState);
14212                    return;
14213                }
14214            }
14215            scheduleWritePackageRestrictionsLocked(userId);
14216            components = mPendingBroadcasts.get(userId, packageName);
14217            final boolean newPackage = components == null;
14218            if (newPackage) {
14219                components = new ArrayList<String>();
14220            }
14221            if (!components.contains(componentName)) {
14222                components.add(componentName);
14223            }
14224            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14225                sendNow = true;
14226                // Purge entry from pending broadcast list if another one exists already
14227                // since we are sending one right away.
14228                mPendingBroadcasts.remove(userId, packageName);
14229            } else {
14230                if (newPackage) {
14231                    mPendingBroadcasts.put(userId, packageName, components);
14232                }
14233                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14234                    // Schedule a message
14235                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14236                }
14237            }
14238        }
14239
14240        long callingId = Binder.clearCallingIdentity();
14241        try {
14242            if (sendNow) {
14243                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14244                sendPackageChangedBroadcast(packageName,
14245                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14246            }
14247        } finally {
14248            Binder.restoreCallingIdentity(callingId);
14249        }
14250    }
14251
14252    private void sendPackageChangedBroadcast(String packageName,
14253            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14254        if (DEBUG_INSTALL)
14255            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14256                    + componentNames);
14257        Bundle extras = new Bundle(4);
14258        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14259        String nameList[] = new String[componentNames.size()];
14260        componentNames.toArray(nameList);
14261        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14262        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14263        extras.putInt(Intent.EXTRA_UID, packageUid);
14264        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14265                new int[] {UserHandle.getUserId(packageUid)});
14266    }
14267
14268    @Override
14269    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14270        if (!sUserManager.exists(userId)) return;
14271        final int uid = Binder.getCallingUid();
14272        final int permission = mContext.checkCallingOrSelfPermission(
14273                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14274        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14275        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14276        // writer
14277        synchronized (mPackages) {
14278            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14279                    allowedByPermission, uid, userId)) {
14280                scheduleWritePackageRestrictionsLocked(userId);
14281            }
14282        }
14283    }
14284
14285    @Override
14286    public String getInstallerPackageName(String packageName) {
14287        // reader
14288        synchronized (mPackages) {
14289            return mSettings.getInstallerPackageNameLPr(packageName);
14290        }
14291    }
14292
14293    @Override
14294    public int getApplicationEnabledSetting(String packageName, int userId) {
14295        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14296        int uid = Binder.getCallingUid();
14297        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14298        // reader
14299        synchronized (mPackages) {
14300            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14301        }
14302    }
14303
14304    @Override
14305    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14306        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14307        int uid = Binder.getCallingUid();
14308        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14309        // reader
14310        synchronized (mPackages) {
14311            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14312        }
14313    }
14314
14315    @Override
14316    public void enterSafeMode() {
14317        enforceSystemOrRoot("Only the system can request entering safe mode");
14318
14319        if (!mSystemReady) {
14320            mSafeMode = true;
14321        }
14322    }
14323
14324    @Override
14325    public void systemReady() {
14326        mSystemReady = true;
14327
14328        // Read the compatibilty setting when the system is ready.
14329        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14330                mContext.getContentResolver(),
14331                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14332        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14333        if (DEBUG_SETTINGS) {
14334            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14335        }
14336
14337        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14338
14339        synchronized (mPackages) {
14340            // Verify that all of the preferred activity components actually
14341            // exist.  It is possible for applications to be updated and at
14342            // that point remove a previously declared activity component that
14343            // had been set as a preferred activity.  We try to clean this up
14344            // the next time we encounter that preferred activity, but it is
14345            // possible for the user flow to never be able to return to that
14346            // situation so here we do a sanity check to make sure we haven't
14347            // left any junk around.
14348            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14349            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14350                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14351                removed.clear();
14352                for (PreferredActivity pa : pir.filterSet()) {
14353                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14354                        removed.add(pa);
14355                    }
14356                }
14357                if (removed.size() > 0) {
14358                    for (int r=0; r<removed.size(); r++) {
14359                        PreferredActivity pa = removed.get(r);
14360                        Slog.w(TAG, "Removing dangling preferred activity: "
14361                                + pa.mPref.mComponent);
14362                        pir.removeFilter(pa);
14363                    }
14364                    mSettings.writePackageRestrictionsLPr(
14365                            mSettings.mPreferredActivities.keyAt(i));
14366                }
14367            }
14368
14369            for (int userId : UserManagerService.getInstance().getUserIds()) {
14370                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14371                    grantPermissionsUserIds = ArrayUtils.appendInt(
14372                            grantPermissionsUserIds, userId);
14373                }
14374            }
14375        }
14376        sUserManager.systemReady();
14377
14378        // If we upgraded grant all default permissions before kicking off.
14379        for (int userId : grantPermissionsUserIds) {
14380            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14381        }
14382
14383        // Kick off any messages waiting for system ready
14384        if (mPostSystemReadyMessages != null) {
14385            for (Message msg : mPostSystemReadyMessages) {
14386                msg.sendToTarget();
14387            }
14388            mPostSystemReadyMessages = null;
14389        }
14390
14391        // Watch for external volumes that come and go over time
14392        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14393        storage.registerListener(mStorageListener);
14394
14395        mInstallerService.systemReady();
14396        mPackageDexOptimizer.systemReady();
14397    }
14398
14399    @Override
14400    public boolean isSafeMode() {
14401        return mSafeMode;
14402    }
14403
14404    @Override
14405    public boolean hasSystemUidErrors() {
14406        return mHasSystemUidErrors;
14407    }
14408
14409    static String arrayToString(int[] array) {
14410        StringBuffer buf = new StringBuffer(128);
14411        buf.append('[');
14412        if (array != null) {
14413            for (int i=0; i<array.length; i++) {
14414                if (i > 0) buf.append(", ");
14415                buf.append(array[i]);
14416            }
14417        }
14418        buf.append(']');
14419        return buf.toString();
14420    }
14421
14422    static class DumpState {
14423        public static final int DUMP_LIBS = 1 << 0;
14424        public static final int DUMP_FEATURES = 1 << 1;
14425        public static final int DUMP_RESOLVERS = 1 << 2;
14426        public static final int DUMP_PERMISSIONS = 1 << 3;
14427        public static final int DUMP_PACKAGES = 1 << 4;
14428        public static final int DUMP_SHARED_USERS = 1 << 5;
14429        public static final int DUMP_MESSAGES = 1 << 6;
14430        public static final int DUMP_PROVIDERS = 1 << 7;
14431        public static final int DUMP_VERIFIERS = 1 << 8;
14432        public static final int DUMP_PREFERRED = 1 << 9;
14433        public static final int DUMP_PREFERRED_XML = 1 << 10;
14434        public static final int DUMP_KEYSETS = 1 << 11;
14435        public static final int DUMP_VERSION = 1 << 12;
14436        public static final int DUMP_INSTALLS = 1 << 13;
14437        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14438        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14439
14440        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14441
14442        private int mTypes;
14443
14444        private int mOptions;
14445
14446        private boolean mTitlePrinted;
14447
14448        private SharedUserSetting mSharedUser;
14449
14450        public boolean isDumping(int type) {
14451            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14452                return true;
14453            }
14454
14455            return (mTypes & type) != 0;
14456        }
14457
14458        public void setDump(int type) {
14459            mTypes |= type;
14460        }
14461
14462        public boolean isOptionEnabled(int option) {
14463            return (mOptions & option) != 0;
14464        }
14465
14466        public void setOptionEnabled(int option) {
14467            mOptions |= option;
14468        }
14469
14470        public boolean onTitlePrinted() {
14471            final boolean printed = mTitlePrinted;
14472            mTitlePrinted = true;
14473            return printed;
14474        }
14475
14476        public boolean getTitlePrinted() {
14477            return mTitlePrinted;
14478        }
14479
14480        public void setTitlePrinted(boolean enabled) {
14481            mTitlePrinted = enabled;
14482        }
14483
14484        public SharedUserSetting getSharedUser() {
14485            return mSharedUser;
14486        }
14487
14488        public void setSharedUser(SharedUserSetting user) {
14489            mSharedUser = user;
14490        }
14491    }
14492
14493    @Override
14494    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14495        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14496                != PackageManager.PERMISSION_GRANTED) {
14497            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14498                    + Binder.getCallingPid()
14499                    + ", uid=" + Binder.getCallingUid()
14500                    + " without permission "
14501                    + android.Manifest.permission.DUMP);
14502            return;
14503        }
14504
14505        DumpState dumpState = new DumpState();
14506        boolean fullPreferred = false;
14507        boolean checkin = false;
14508
14509        String packageName = null;
14510        ArraySet<String> permissionNames = null;
14511
14512        int opti = 0;
14513        while (opti < args.length) {
14514            String opt = args[opti];
14515            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14516                break;
14517            }
14518            opti++;
14519
14520            if ("-a".equals(opt)) {
14521                // Right now we only know how to print all.
14522            } else if ("-h".equals(opt)) {
14523                pw.println("Package manager dump options:");
14524                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14525                pw.println("    --checkin: dump for a checkin");
14526                pw.println("    -f: print details of intent filters");
14527                pw.println("    -h: print this help");
14528                pw.println("  cmd may be one of:");
14529                pw.println("    l[ibraries]: list known shared libraries");
14530                pw.println("    f[ibraries]: list device features");
14531                pw.println("    k[eysets]: print known keysets");
14532                pw.println("    r[esolvers]: dump intent resolvers");
14533                pw.println("    perm[issions]: dump permissions");
14534                pw.println("    permission [name ...]: dump declaration and use of given permission");
14535                pw.println("    pref[erred]: print preferred package settings");
14536                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14537                pw.println("    prov[iders]: dump content providers");
14538                pw.println("    p[ackages]: dump installed packages");
14539                pw.println("    s[hared-users]: dump shared user IDs");
14540                pw.println("    m[essages]: print collected runtime messages");
14541                pw.println("    v[erifiers]: print package verifier info");
14542                pw.println("    version: print database version info");
14543                pw.println("    write: write current settings now");
14544                pw.println("    <package.name>: info about given package");
14545                pw.println("    installs: details about install sessions");
14546                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14547                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14548                return;
14549            } else if ("--checkin".equals(opt)) {
14550                checkin = true;
14551            } else if ("-f".equals(opt)) {
14552                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14553            } else {
14554                pw.println("Unknown argument: " + opt + "; use -h for help");
14555            }
14556        }
14557
14558        // Is the caller requesting to dump a particular piece of data?
14559        if (opti < args.length) {
14560            String cmd = args[opti];
14561            opti++;
14562            // Is this a package name?
14563            if ("android".equals(cmd) || cmd.contains(".")) {
14564                packageName = cmd;
14565                // When dumping a single package, we always dump all of its
14566                // filter information since the amount of data will be reasonable.
14567                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14568            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14569                dumpState.setDump(DumpState.DUMP_LIBS);
14570            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14571                dumpState.setDump(DumpState.DUMP_FEATURES);
14572            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14573                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14574            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14575                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14576            } else if ("permission".equals(cmd)) {
14577                if (opti >= args.length) {
14578                    pw.println("Error: permission requires permission name");
14579                    return;
14580                }
14581                permissionNames = new ArraySet<>();
14582                while (opti < args.length) {
14583                    permissionNames.add(args[opti]);
14584                    opti++;
14585                }
14586                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14587                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14588            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14589                dumpState.setDump(DumpState.DUMP_PREFERRED);
14590            } else if ("preferred-xml".equals(cmd)) {
14591                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14592                if (opti < args.length && "--full".equals(args[opti])) {
14593                    fullPreferred = true;
14594                    opti++;
14595                }
14596            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14597                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14598            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14599                dumpState.setDump(DumpState.DUMP_PACKAGES);
14600            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14601                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14602            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14603                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14604            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14605                dumpState.setDump(DumpState.DUMP_MESSAGES);
14606            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14607                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14608            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14609                    || "intent-filter-verifiers".equals(cmd)) {
14610                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14611            } else if ("version".equals(cmd)) {
14612                dumpState.setDump(DumpState.DUMP_VERSION);
14613            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14614                dumpState.setDump(DumpState.DUMP_KEYSETS);
14615            } else if ("installs".equals(cmd)) {
14616                dumpState.setDump(DumpState.DUMP_INSTALLS);
14617            } else if ("write".equals(cmd)) {
14618                synchronized (mPackages) {
14619                    mSettings.writeLPr();
14620                    pw.println("Settings written.");
14621                    return;
14622                }
14623            }
14624        }
14625
14626        if (checkin) {
14627            pw.println("vers,1");
14628        }
14629
14630        // reader
14631        synchronized (mPackages) {
14632            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14633                if (!checkin) {
14634                    if (dumpState.onTitlePrinted())
14635                        pw.println();
14636                    pw.println("Database versions:");
14637                    pw.print("  SDK Version:");
14638                    pw.print(" internal=");
14639                    pw.print(mSettings.mInternalSdkPlatform);
14640                    pw.print(" external=");
14641                    pw.println(mSettings.mExternalSdkPlatform);
14642                    pw.print("  DB Version:");
14643                    pw.print(" internal=");
14644                    pw.print(mSettings.mInternalDatabaseVersion);
14645                    pw.print(" external=");
14646                    pw.println(mSettings.mExternalDatabaseVersion);
14647                }
14648            }
14649
14650            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14651                if (!checkin) {
14652                    if (dumpState.onTitlePrinted())
14653                        pw.println();
14654                    pw.println("Verifiers:");
14655                    pw.print("  Required: ");
14656                    pw.print(mRequiredVerifierPackage);
14657                    pw.print(" (uid=");
14658                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14659                    pw.println(")");
14660                } else if (mRequiredVerifierPackage != null) {
14661                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14662                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14663                }
14664            }
14665
14666            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14667                    packageName == null) {
14668                if (mIntentFilterVerifierComponent != null) {
14669                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14670                    if (!checkin) {
14671                        if (dumpState.onTitlePrinted())
14672                            pw.println();
14673                        pw.println("Intent Filter Verifier:");
14674                        pw.print("  Using: ");
14675                        pw.print(verifierPackageName);
14676                        pw.print(" (uid=");
14677                        pw.print(getPackageUid(verifierPackageName, 0));
14678                        pw.println(")");
14679                    } else if (verifierPackageName != null) {
14680                        pw.print("ifv,"); pw.print(verifierPackageName);
14681                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14682                    }
14683                } else {
14684                    pw.println();
14685                    pw.println("No Intent Filter Verifier available!");
14686                }
14687            }
14688
14689            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14690                boolean printedHeader = false;
14691                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14692                while (it.hasNext()) {
14693                    String name = it.next();
14694                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14695                    if (!checkin) {
14696                        if (!printedHeader) {
14697                            if (dumpState.onTitlePrinted())
14698                                pw.println();
14699                            pw.println("Libraries:");
14700                            printedHeader = true;
14701                        }
14702                        pw.print("  ");
14703                    } else {
14704                        pw.print("lib,");
14705                    }
14706                    pw.print(name);
14707                    if (!checkin) {
14708                        pw.print(" -> ");
14709                    }
14710                    if (ent.path != null) {
14711                        if (!checkin) {
14712                            pw.print("(jar) ");
14713                            pw.print(ent.path);
14714                        } else {
14715                            pw.print(",jar,");
14716                            pw.print(ent.path);
14717                        }
14718                    } else {
14719                        if (!checkin) {
14720                            pw.print("(apk) ");
14721                            pw.print(ent.apk);
14722                        } else {
14723                            pw.print(",apk,");
14724                            pw.print(ent.apk);
14725                        }
14726                    }
14727                    pw.println();
14728                }
14729            }
14730
14731            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14732                if (dumpState.onTitlePrinted())
14733                    pw.println();
14734                if (!checkin) {
14735                    pw.println("Features:");
14736                }
14737                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14738                while (it.hasNext()) {
14739                    String name = it.next();
14740                    if (!checkin) {
14741                        pw.print("  ");
14742                    } else {
14743                        pw.print("feat,");
14744                    }
14745                    pw.println(name);
14746                }
14747            }
14748
14749            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14750                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14751                        : "Activity Resolver Table:", "  ", packageName,
14752                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14753                    dumpState.setTitlePrinted(true);
14754                }
14755                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14756                        : "Receiver Resolver Table:", "  ", packageName,
14757                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14758                    dumpState.setTitlePrinted(true);
14759                }
14760                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14761                        : "Service Resolver Table:", "  ", packageName,
14762                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14763                    dumpState.setTitlePrinted(true);
14764                }
14765                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14766                        : "Provider Resolver Table:", "  ", packageName,
14767                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14768                    dumpState.setTitlePrinted(true);
14769                }
14770            }
14771
14772            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14773                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14774                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14775                    int user = mSettings.mPreferredActivities.keyAt(i);
14776                    if (pir.dump(pw,
14777                            dumpState.getTitlePrinted()
14778                                ? "\nPreferred Activities User " + user + ":"
14779                                : "Preferred Activities User " + user + ":", "  ",
14780                            packageName, true, false)) {
14781                        dumpState.setTitlePrinted(true);
14782                    }
14783                }
14784            }
14785
14786            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14787                pw.flush();
14788                FileOutputStream fout = new FileOutputStream(fd);
14789                BufferedOutputStream str = new BufferedOutputStream(fout);
14790                XmlSerializer serializer = new FastXmlSerializer();
14791                try {
14792                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14793                    serializer.startDocument(null, true);
14794                    serializer.setFeature(
14795                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14796                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14797                    serializer.endDocument();
14798                    serializer.flush();
14799                } catch (IllegalArgumentException e) {
14800                    pw.println("Failed writing: " + e);
14801                } catch (IllegalStateException e) {
14802                    pw.println("Failed writing: " + e);
14803                } catch (IOException e) {
14804                    pw.println("Failed writing: " + e);
14805                }
14806            }
14807
14808            if (!checkin
14809                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14810                    && packageName == null) {
14811                pw.println();
14812                int count = mSettings.mPackages.size();
14813                if (count == 0) {
14814                    pw.println("No applications!");
14815                    pw.println();
14816                } else {
14817                    final String prefix = "  ";
14818                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14819                    if (allPackageSettings.size() == 0) {
14820                        pw.println("No domain preferred apps!");
14821                        pw.println();
14822                    } else {
14823                        pw.println("App verification status:");
14824                        pw.println();
14825                        count = 0;
14826                        for (PackageSetting ps : allPackageSettings) {
14827                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14828                            if (ivi == null || ivi.getPackageName() == null) continue;
14829                            pw.println(prefix + "Package: " + ivi.getPackageName());
14830                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14831                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14832                            pw.println();
14833                            count++;
14834                        }
14835                        if (count == 0) {
14836                            pw.println(prefix + "No app verification established.");
14837                            pw.println();
14838                        }
14839                        for (int userId : sUserManager.getUserIds()) {
14840                            pw.println("App linkages for user " + userId + ":");
14841                            pw.println();
14842                            count = 0;
14843                            for (PackageSetting ps : allPackageSettings) {
14844                                final int status = ps.getDomainVerificationStatusForUser(userId);
14845                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14846                                    continue;
14847                                }
14848                                pw.println(prefix + "Package: " + ps.name);
14849                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14850                                String statusStr = IntentFilterVerificationInfo.
14851                                        getStatusStringFromValue(status);
14852                                pw.println(prefix + "Status:  " + statusStr);
14853                                pw.println();
14854                                count++;
14855                            }
14856                            if (count == 0) {
14857                                pw.println(prefix + "No configured app linkages.");
14858                                pw.println();
14859                            }
14860                        }
14861                    }
14862                }
14863            }
14864
14865            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14866                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14867                if (packageName == null && permissionNames == null) {
14868                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14869                        if (iperm == 0) {
14870                            if (dumpState.onTitlePrinted())
14871                                pw.println();
14872                            pw.println("AppOp Permissions:");
14873                        }
14874                        pw.print("  AppOp Permission ");
14875                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14876                        pw.println(":");
14877                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14878                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14879                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14880                        }
14881                    }
14882                }
14883            }
14884
14885            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14886                boolean printedSomething = false;
14887                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14888                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14889                        continue;
14890                    }
14891                    if (!printedSomething) {
14892                        if (dumpState.onTitlePrinted())
14893                            pw.println();
14894                        pw.println("Registered ContentProviders:");
14895                        printedSomething = true;
14896                    }
14897                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14898                    pw.print("    "); pw.println(p.toString());
14899                }
14900                printedSomething = false;
14901                for (Map.Entry<String, PackageParser.Provider> entry :
14902                        mProvidersByAuthority.entrySet()) {
14903                    PackageParser.Provider p = entry.getValue();
14904                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14905                        continue;
14906                    }
14907                    if (!printedSomething) {
14908                        if (dumpState.onTitlePrinted())
14909                            pw.println();
14910                        pw.println("ContentProvider Authorities:");
14911                        printedSomething = true;
14912                    }
14913                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14914                    pw.print("    "); pw.println(p.toString());
14915                    if (p.info != null && p.info.applicationInfo != null) {
14916                        final String appInfo = p.info.applicationInfo.toString();
14917                        pw.print("      applicationInfo="); pw.println(appInfo);
14918                    }
14919                }
14920            }
14921
14922            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14923                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14924            }
14925
14926            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14927                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14928            }
14929
14930            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14931                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14932            }
14933
14934            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14935                // XXX should handle packageName != null by dumping only install data that
14936                // the given package is involved with.
14937                if (dumpState.onTitlePrinted()) pw.println();
14938                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14939            }
14940
14941            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14942                if (dumpState.onTitlePrinted()) pw.println();
14943                mSettings.dumpReadMessagesLPr(pw, dumpState);
14944
14945                pw.println();
14946                pw.println("Package warning messages:");
14947                BufferedReader in = null;
14948                String line = null;
14949                try {
14950                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14951                    while ((line = in.readLine()) != null) {
14952                        if (line.contains("ignored: updated version")) continue;
14953                        pw.println(line);
14954                    }
14955                } catch (IOException ignored) {
14956                } finally {
14957                    IoUtils.closeQuietly(in);
14958                }
14959            }
14960
14961            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14962                BufferedReader in = null;
14963                String line = null;
14964                try {
14965                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14966                    while ((line = in.readLine()) != null) {
14967                        if (line.contains("ignored: updated version")) continue;
14968                        pw.print("msg,");
14969                        pw.println(line);
14970                    }
14971                } catch (IOException ignored) {
14972                } finally {
14973                    IoUtils.closeQuietly(in);
14974                }
14975            }
14976        }
14977    }
14978
14979    private String dumpDomainString(String packageName) {
14980        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
14981        List<IntentFilter> filters = getAllIntentFilters(packageName);
14982
14983        ArraySet<String> result = new ArraySet<>();
14984        if (iviList.size() > 0) {
14985            for (IntentFilterVerificationInfo ivi : iviList) {
14986                for (String host : ivi.getDomains()) {
14987                    result.add(host);
14988                }
14989            }
14990        }
14991        if (filters != null && filters.size() > 0) {
14992            for (IntentFilter filter : filters) {
14993                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
14994                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
14995                    result.addAll(filter.getHostsList());
14996                }
14997            }
14998        }
14999
15000        StringBuilder sb = new StringBuilder(result.size() * 16);
15001        for (String domain : result) {
15002            if (sb.length() > 0) sb.append(" ");
15003            sb.append(domain);
15004        }
15005        return sb.toString();
15006    }
15007
15008    // ------- apps on sdcard specific code -------
15009    static final boolean DEBUG_SD_INSTALL = false;
15010
15011    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15012
15013    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15014
15015    private boolean mMediaMounted = false;
15016
15017    static String getEncryptKey() {
15018        try {
15019            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15020                    SD_ENCRYPTION_KEYSTORE_NAME);
15021            if (sdEncKey == null) {
15022                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15023                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15024                if (sdEncKey == null) {
15025                    Slog.e(TAG, "Failed to create encryption keys");
15026                    return null;
15027                }
15028            }
15029            return sdEncKey;
15030        } catch (NoSuchAlgorithmException nsae) {
15031            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15032            return null;
15033        } catch (IOException ioe) {
15034            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15035            return null;
15036        }
15037    }
15038
15039    /*
15040     * Update media status on PackageManager.
15041     */
15042    @Override
15043    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15044        int callingUid = Binder.getCallingUid();
15045        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15046            throw new SecurityException("Media status can only be updated by the system");
15047        }
15048        // reader; this apparently protects mMediaMounted, but should probably
15049        // be a different lock in that case.
15050        synchronized (mPackages) {
15051            Log.i(TAG, "Updating external media status from "
15052                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15053                    + (mediaStatus ? "mounted" : "unmounted"));
15054            if (DEBUG_SD_INSTALL)
15055                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15056                        + ", mMediaMounted=" + mMediaMounted);
15057            if (mediaStatus == mMediaMounted) {
15058                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15059                        : 0, -1);
15060                mHandler.sendMessage(msg);
15061                return;
15062            }
15063            mMediaMounted = mediaStatus;
15064        }
15065        // Queue up an async operation since the package installation may take a
15066        // little while.
15067        mHandler.post(new Runnable() {
15068            public void run() {
15069                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15070            }
15071        });
15072    }
15073
15074    /**
15075     * Called by MountService when the initial ASECs to scan are available.
15076     * Should block until all the ASEC containers are finished being scanned.
15077     */
15078    public void scanAvailableAsecs() {
15079        updateExternalMediaStatusInner(true, false, false);
15080        if (mShouldRestoreconData) {
15081            SELinuxMMAC.setRestoreconDone();
15082            mShouldRestoreconData = false;
15083        }
15084    }
15085
15086    /*
15087     * Collect information of applications on external media, map them against
15088     * existing containers and update information based on current mount status.
15089     * Please note that we always have to report status if reportStatus has been
15090     * set to true especially when unloading packages.
15091     */
15092    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15093            boolean externalStorage) {
15094        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15095        int[] uidArr = EmptyArray.INT;
15096
15097        final String[] list = PackageHelper.getSecureContainerList();
15098        if (ArrayUtils.isEmpty(list)) {
15099            Log.i(TAG, "No secure containers found");
15100        } else {
15101            // Process list of secure containers and categorize them
15102            // as active or stale based on their package internal state.
15103
15104            // reader
15105            synchronized (mPackages) {
15106                for (String cid : list) {
15107                    // Leave stages untouched for now; installer service owns them
15108                    if (PackageInstallerService.isStageName(cid)) continue;
15109
15110                    if (DEBUG_SD_INSTALL)
15111                        Log.i(TAG, "Processing container " + cid);
15112                    String pkgName = getAsecPackageName(cid);
15113                    if (pkgName == null) {
15114                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15115                        continue;
15116                    }
15117                    if (DEBUG_SD_INSTALL)
15118                        Log.i(TAG, "Looking for pkg : " + pkgName);
15119
15120                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15121                    if (ps == null) {
15122                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15123                        continue;
15124                    }
15125
15126                    /*
15127                     * Skip packages that are not external if we're unmounting
15128                     * external storage.
15129                     */
15130                    if (externalStorage && !isMounted && !isExternal(ps)) {
15131                        continue;
15132                    }
15133
15134                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15135                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15136                    // The package status is changed only if the code path
15137                    // matches between settings and the container id.
15138                    if (ps.codePathString != null
15139                            && ps.codePathString.startsWith(args.getCodePath())) {
15140                        if (DEBUG_SD_INSTALL) {
15141                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15142                                    + " at code path: " + ps.codePathString);
15143                        }
15144
15145                        // We do have a valid package installed on sdcard
15146                        processCids.put(args, ps.codePathString);
15147                        final int uid = ps.appId;
15148                        if (uid != -1) {
15149                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15150                        }
15151                    } else {
15152                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15153                                + ps.codePathString);
15154                    }
15155                }
15156            }
15157
15158            Arrays.sort(uidArr);
15159        }
15160
15161        // Process packages with valid entries.
15162        if (isMounted) {
15163            if (DEBUG_SD_INSTALL)
15164                Log.i(TAG, "Loading packages");
15165            loadMediaPackages(processCids, uidArr);
15166            startCleaningPackages();
15167            mInstallerService.onSecureContainersAvailable();
15168        } else {
15169            if (DEBUG_SD_INSTALL)
15170                Log.i(TAG, "Unloading packages");
15171            unloadMediaPackages(processCids, uidArr, reportStatus);
15172        }
15173    }
15174
15175    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15176            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15177        final int size = infos.size();
15178        final String[] packageNames = new String[size];
15179        final int[] packageUids = new int[size];
15180        for (int i = 0; i < size; i++) {
15181            final ApplicationInfo info = infos.get(i);
15182            packageNames[i] = info.packageName;
15183            packageUids[i] = info.uid;
15184        }
15185        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15186                finishedReceiver);
15187    }
15188
15189    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15190            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15191        sendResourcesChangedBroadcast(mediaStatus, replacing,
15192                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15193    }
15194
15195    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15196            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15197        int size = pkgList.length;
15198        if (size > 0) {
15199            // Send broadcasts here
15200            Bundle extras = new Bundle();
15201            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15202            if (uidArr != null) {
15203                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15204            }
15205            if (replacing) {
15206                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15207            }
15208            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15209                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15210            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15211        }
15212    }
15213
15214   /*
15215     * Look at potentially valid container ids from processCids If package
15216     * information doesn't match the one on record or package scanning fails,
15217     * the cid is added to list of removeCids. We currently don't delete stale
15218     * containers.
15219     */
15220    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15221        ArrayList<String> pkgList = new ArrayList<String>();
15222        Set<AsecInstallArgs> keys = processCids.keySet();
15223
15224        for (AsecInstallArgs args : keys) {
15225            String codePath = processCids.get(args);
15226            if (DEBUG_SD_INSTALL)
15227                Log.i(TAG, "Loading container : " + args.cid);
15228            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15229            try {
15230                // Make sure there are no container errors first.
15231                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15232                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15233                            + " when installing from sdcard");
15234                    continue;
15235                }
15236                // Check code path here.
15237                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15238                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15239                            + " does not match one in settings " + codePath);
15240                    continue;
15241                }
15242                // Parse package
15243                int parseFlags = mDefParseFlags;
15244                if (args.isExternalAsec()) {
15245                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15246                }
15247                if (args.isFwdLocked()) {
15248                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15249                }
15250
15251                synchronized (mInstallLock) {
15252                    PackageParser.Package pkg = null;
15253                    try {
15254                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15255                    } catch (PackageManagerException e) {
15256                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15257                    }
15258                    // Scan the package
15259                    if (pkg != null) {
15260                        /*
15261                         * TODO why is the lock being held? doPostInstall is
15262                         * called in other places without the lock. This needs
15263                         * to be straightened out.
15264                         */
15265                        // writer
15266                        synchronized (mPackages) {
15267                            retCode = PackageManager.INSTALL_SUCCEEDED;
15268                            pkgList.add(pkg.packageName);
15269                            // Post process args
15270                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15271                                    pkg.applicationInfo.uid);
15272                        }
15273                    } else {
15274                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15275                    }
15276                }
15277
15278            } finally {
15279                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15280                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15281                }
15282            }
15283        }
15284        // writer
15285        synchronized (mPackages) {
15286            // If the platform SDK has changed since the last time we booted,
15287            // we need to re-grant app permission to catch any new ones that
15288            // appear. This is really a hack, and means that apps can in some
15289            // cases get permissions that the user didn't initially explicitly
15290            // allow... it would be nice to have some better way to handle
15291            // this situation.
15292            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15293            if (regrantPermissions)
15294                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15295                        + mSdkVersion + "; regranting permissions for external storage");
15296            mSettings.mExternalSdkPlatform = mSdkVersion;
15297
15298            // Make sure group IDs have been assigned, and any permission
15299            // changes in other apps are accounted for
15300            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15301                    | (regrantPermissions
15302                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15303                            : 0));
15304
15305            mSettings.updateExternalDatabaseVersion();
15306
15307            // can downgrade to reader
15308            // Persist settings
15309            mSettings.writeLPr();
15310        }
15311        // Send a broadcast to let everyone know we are done processing
15312        if (pkgList.size() > 0) {
15313            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15314        }
15315    }
15316
15317   /*
15318     * Utility method to unload a list of specified containers
15319     */
15320    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15321        // Just unmount all valid containers.
15322        for (AsecInstallArgs arg : cidArgs) {
15323            synchronized (mInstallLock) {
15324                arg.doPostDeleteLI(false);
15325           }
15326       }
15327   }
15328
15329    /*
15330     * Unload packages mounted on external media. This involves deleting package
15331     * data from internal structures, sending broadcasts about diabled packages,
15332     * gc'ing to free up references, unmounting all secure containers
15333     * corresponding to packages on external media, and posting a
15334     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15335     * that we always have to post this message if status has been requested no
15336     * matter what.
15337     */
15338    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15339            final boolean reportStatus) {
15340        if (DEBUG_SD_INSTALL)
15341            Log.i(TAG, "unloading media packages");
15342        ArrayList<String> pkgList = new ArrayList<String>();
15343        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15344        final Set<AsecInstallArgs> keys = processCids.keySet();
15345        for (AsecInstallArgs args : keys) {
15346            String pkgName = args.getPackageName();
15347            if (DEBUG_SD_INSTALL)
15348                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15349            // Delete package internally
15350            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15351            synchronized (mInstallLock) {
15352                boolean res = deletePackageLI(pkgName, null, false, null, null,
15353                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15354                if (res) {
15355                    pkgList.add(pkgName);
15356                } else {
15357                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15358                    failedList.add(args);
15359                }
15360            }
15361        }
15362
15363        // reader
15364        synchronized (mPackages) {
15365            // We didn't update the settings after removing each package;
15366            // write them now for all packages.
15367            mSettings.writeLPr();
15368        }
15369
15370        // We have to absolutely send UPDATED_MEDIA_STATUS only
15371        // after confirming that all the receivers processed the ordered
15372        // broadcast when packages get disabled, force a gc to clean things up.
15373        // and unload all the containers.
15374        if (pkgList.size() > 0) {
15375            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15376                    new IIntentReceiver.Stub() {
15377                public void performReceive(Intent intent, int resultCode, String data,
15378                        Bundle extras, boolean ordered, boolean sticky,
15379                        int sendingUser) throws RemoteException {
15380                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15381                            reportStatus ? 1 : 0, 1, keys);
15382                    mHandler.sendMessage(msg);
15383                }
15384            });
15385        } else {
15386            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15387                    keys);
15388            mHandler.sendMessage(msg);
15389        }
15390    }
15391
15392    private void loadPrivatePackages(VolumeInfo vol) {
15393        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15394        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15395        synchronized (mInstallLock) {
15396        synchronized (mPackages) {
15397            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15398            for (PackageSetting ps : packages) {
15399                final PackageParser.Package pkg;
15400                try {
15401                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15402                    loaded.add(pkg.applicationInfo);
15403                } catch (PackageManagerException e) {
15404                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15405                }
15406            }
15407
15408            // TODO: regrant any permissions that changed based since original install
15409
15410            mSettings.writeLPr();
15411        }
15412        }
15413
15414        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15415        sendResourcesChangedBroadcast(true, false, loaded, null);
15416    }
15417
15418    private void unloadPrivatePackages(VolumeInfo vol) {
15419        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15420        synchronized (mInstallLock) {
15421        synchronized (mPackages) {
15422            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15423            for (PackageSetting ps : packages) {
15424                if (ps.pkg == null) continue;
15425
15426                final ApplicationInfo info = ps.pkg.applicationInfo;
15427                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15428                if (deletePackageLI(ps.name, null, false, null, null,
15429                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15430                    unloaded.add(info);
15431                } else {
15432                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15433                }
15434            }
15435
15436            mSettings.writeLPr();
15437        }
15438        }
15439
15440        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15441        sendResourcesChangedBroadcast(false, false, unloaded, null);
15442    }
15443
15444    /**
15445     * Examine all users present on given mounted volume, and destroy data
15446     * belonging to users that are no longer valid, or whose user ID has been
15447     * recycled.
15448     */
15449    private void reconcileUsers(String volumeUuid) {
15450        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15451        if (ArrayUtils.isEmpty(files)) {
15452            Slog.d(TAG, "No users found on " + volumeUuid);
15453            return;
15454        }
15455
15456        for (File file : files) {
15457            if (!file.isDirectory()) continue;
15458
15459            final int userId;
15460            final UserInfo info;
15461            try {
15462                userId = Integer.parseInt(file.getName());
15463                info = sUserManager.getUserInfo(userId);
15464            } catch (NumberFormatException e) {
15465                Slog.w(TAG, "Invalid user directory " + file);
15466                continue;
15467            }
15468
15469            boolean destroyUser = false;
15470            if (info == null) {
15471                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15472                        + " because no matching user was found");
15473                destroyUser = true;
15474            } else {
15475                try {
15476                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15477                } catch (IOException e) {
15478                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15479                            + " because we failed to enforce serial number: " + e);
15480                    destroyUser = true;
15481                }
15482            }
15483
15484            if (destroyUser) {
15485                synchronized (mInstallLock) {
15486                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15487                }
15488            }
15489        }
15490
15491        final UserManager um = mContext.getSystemService(UserManager.class);
15492        for (UserInfo user : um.getUsers()) {
15493            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15494            if (userDir.exists()) continue;
15495
15496            try {
15497                UserManagerService.prepareUserDirectory(userDir);
15498                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15499            } catch (IOException e) {
15500                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15501            }
15502        }
15503    }
15504
15505    /**
15506     * Examine all apps present on given mounted volume, and destroy apps that
15507     * aren't expected, either due to uninstallation or reinstallation on
15508     * another volume.
15509     */
15510    private void reconcileApps(String volumeUuid) {
15511        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15512        if (ArrayUtils.isEmpty(files)) {
15513            Slog.d(TAG, "No apps found on " + volumeUuid);
15514            return;
15515        }
15516
15517        for (File file : files) {
15518            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15519                    && !PackageInstallerService.isStageName(file.getName());
15520            if (!isPackage) {
15521                // Ignore entries which are not packages
15522                continue;
15523            }
15524
15525            boolean destroyApp = false;
15526            String packageName = null;
15527            try {
15528                final PackageLite pkg = PackageParser.parsePackageLite(file,
15529                        PackageParser.PARSE_MUST_BE_APK);
15530                packageName = pkg.packageName;
15531
15532                synchronized (mPackages) {
15533                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15534                    if (ps == null) {
15535                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15536                                + volumeUuid + " because we found no install record");
15537                        destroyApp = true;
15538                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15539                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15540                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15541                        destroyApp = true;
15542                    }
15543                }
15544
15545            } catch (PackageParserException e) {
15546                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15547                destroyApp = true;
15548            }
15549
15550            if (destroyApp) {
15551                synchronized (mInstallLock) {
15552                    if (packageName != null) {
15553                        removeDataDirsLI(volumeUuid, packageName);
15554                    }
15555                    if (file.isDirectory()) {
15556                        mInstaller.rmPackageDir(file.getAbsolutePath());
15557                    } else {
15558                        file.delete();
15559                    }
15560                }
15561            }
15562        }
15563    }
15564
15565    private void unfreezePackage(String packageName) {
15566        synchronized (mPackages) {
15567            final PackageSetting ps = mSettings.mPackages.get(packageName);
15568            if (ps != null) {
15569                ps.frozen = false;
15570            }
15571        }
15572    }
15573
15574    @Override
15575    public int movePackage(final String packageName, final String volumeUuid) {
15576        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15577
15578        final int moveId = mNextMoveId.getAndIncrement();
15579        try {
15580            movePackageInternal(packageName, volumeUuid, moveId);
15581        } catch (PackageManagerException e) {
15582            Slog.w(TAG, "Failed to move " + packageName, e);
15583            mMoveCallbacks.notifyStatusChanged(moveId,
15584                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15585        }
15586        return moveId;
15587    }
15588
15589    private void movePackageInternal(final String packageName, final String volumeUuid,
15590            final int moveId) throws PackageManagerException {
15591        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15592        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15593        final PackageManager pm = mContext.getPackageManager();
15594
15595        final boolean currentAsec;
15596        final String currentVolumeUuid;
15597        final File codeFile;
15598        final String installerPackageName;
15599        final String packageAbiOverride;
15600        final int appId;
15601        final String seinfo;
15602        final String label;
15603
15604        // reader
15605        synchronized (mPackages) {
15606            final PackageParser.Package pkg = mPackages.get(packageName);
15607            final PackageSetting ps = mSettings.mPackages.get(packageName);
15608            if (pkg == null || ps == null) {
15609                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15610            }
15611
15612            if (pkg.applicationInfo.isSystemApp()) {
15613                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15614                        "Cannot move system application");
15615            }
15616
15617            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15618                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15619                        "Package already moved to " + volumeUuid);
15620            }
15621
15622            final File probe = new File(pkg.codePath);
15623            final File probeOat = new File(probe, "oat");
15624            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15625                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15626                        "Move only supported for modern cluster style installs");
15627            }
15628
15629            if (ps.frozen) {
15630                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15631                        "Failed to move already frozen package");
15632            }
15633            ps.frozen = true;
15634
15635            currentAsec = pkg.applicationInfo.isForwardLocked()
15636                    || pkg.applicationInfo.isExternalAsec();
15637            currentVolumeUuid = ps.volumeUuid;
15638            codeFile = new File(pkg.codePath);
15639            installerPackageName = ps.installerPackageName;
15640            packageAbiOverride = ps.cpuAbiOverrideString;
15641            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15642            seinfo = pkg.applicationInfo.seinfo;
15643            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15644        }
15645
15646        // Now that we're guarded by frozen state, kill app during move
15647        killApplication(packageName, appId, "move pkg");
15648
15649        final Bundle extras = new Bundle();
15650        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15651        extras.putString(Intent.EXTRA_TITLE, label);
15652        mMoveCallbacks.notifyCreated(moveId, extras);
15653
15654        int installFlags;
15655        final boolean moveCompleteApp;
15656        final File measurePath;
15657
15658        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15659            installFlags = INSTALL_INTERNAL;
15660            moveCompleteApp = !currentAsec;
15661            measurePath = Environment.getDataAppDirectory(volumeUuid);
15662        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15663            installFlags = INSTALL_EXTERNAL;
15664            moveCompleteApp = false;
15665            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15666        } else {
15667            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15668            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15669                    || !volume.isMountedWritable()) {
15670                unfreezePackage(packageName);
15671                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15672                        "Move location not mounted private volume");
15673            }
15674
15675            Preconditions.checkState(!currentAsec);
15676
15677            installFlags = INSTALL_INTERNAL;
15678            moveCompleteApp = true;
15679            measurePath = Environment.getDataAppDirectory(volumeUuid);
15680        }
15681
15682        final PackageStats stats = new PackageStats(null, -1);
15683        synchronized (mInstaller) {
15684            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15685                unfreezePackage(packageName);
15686                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15687                        "Failed to measure package size");
15688            }
15689        }
15690
15691        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15692                + stats.dataSize);
15693
15694        final long startFreeBytes = measurePath.getFreeSpace();
15695        final long sizeBytes;
15696        if (moveCompleteApp) {
15697            sizeBytes = stats.codeSize + stats.dataSize;
15698        } else {
15699            sizeBytes = stats.codeSize;
15700        }
15701
15702        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15703            unfreezePackage(packageName);
15704            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15705                    "Not enough free space to move");
15706        }
15707
15708        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15709
15710        final CountDownLatch installedLatch = new CountDownLatch(1);
15711        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15712            @Override
15713            public void onUserActionRequired(Intent intent) throws RemoteException {
15714                throw new IllegalStateException();
15715            }
15716
15717            @Override
15718            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15719                    Bundle extras) throws RemoteException {
15720                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15721                        + PackageManager.installStatusToString(returnCode, msg));
15722
15723                installedLatch.countDown();
15724
15725                // Regardless of success or failure of the move operation,
15726                // always unfreeze the package
15727                unfreezePackage(packageName);
15728
15729                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15730                switch (status) {
15731                    case PackageInstaller.STATUS_SUCCESS:
15732                        mMoveCallbacks.notifyStatusChanged(moveId,
15733                                PackageManager.MOVE_SUCCEEDED);
15734                        break;
15735                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15736                        mMoveCallbacks.notifyStatusChanged(moveId,
15737                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15738                        break;
15739                    default:
15740                        mMoveCallbacks.notifyStatusChanged(moveId,
15741                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15742                        break;
15743                }
15744            }
15745        };
15746
15747        final MoveInfo move;
15748        if (moveCompleteApp) {
15749            // Kick off a thread to report progress estimates
15750            new Thread() {
15751                @Override
15752                public void run() {
15753                    while (true) {
15754                        try {
15755                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15756                                break;
15757                            }
15758                        } catch (InterruptedException ignored) {
15759                        }
15760
15761                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15762                        final int progress = 10 + (int) MathUtils.constrain(
15763                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15764                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15765                    }
15766                }
15767            }.start();
15768
15769            final String dataAppName = codeFile.getName();
15770            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15771                    dataAppName, appId, seinfo);
15772        } else {
15773            move = null;
15774        }
15775
15776        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15777
15778        final Message msg = mHandler.obtainMessage(INIT_COPY);
15779        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15780        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15781                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15782        mHandler.sendMessage(msg);
15783    }
15784
15785    @Override
15786    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15787        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15788
15789        final int realMoveId = mNextMoveId.getAndIncrement();
15790        final Bundle extras = new Bundle();
15791        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15792        mMoveCallbacks.notifyCreated(realMoveId, extras);
15793
15794        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15795            @Override
15796            public void onCreated(int moveId, Bundle extras) {
15797                // Ignored
15798            }
15799
15800            @Override
15801            public void onStatusChanged(int moveId, int status, long estMillis) {
15802                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15803            }
15804        };
15805
15806        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15807        storage.setPrimaryStorageUuid(volumeUuid, callback);
15808        return realMoveId;
15809    }
15810
15811    @Override
15812    public int getMoveStatus(int moveId) {
15813        mContext.enforceCallingOrSelfPermission(
15814                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15815        return mMoveCallbacks.mLastStatus.get(moveId);
15816    }
15817
15818    @Override
15819    public void registerMoveCallback(IPackageMoveObserver callback) {
15820        mContext.enforceCallingOrSelfPermission(
15821                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15822        mMoveCallbacks.register(callback);
15823    }
15824
15825    @Override
15826    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15827        mContext.enforceCallingOrSelfPermission(
15828                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15829        mMoveCallbacks.unregister(callback);
15830    }
15831
15832    @Override
15833    public boolean setInstallLocation(int loc) {
15834        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15835                null);
15836        if (getInstallLocation() == loc) {
15837            return true;
15838        }
15839        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15840                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15841            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15842                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15843            return true;
15844        }
15845        return false;
15846   }
15847
15848    @Override
15849    public int getInstallLocation() {
15850        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15851                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15852                PackageHelper.APP_INSTALL_AUTO);
15853    }
15854
15855    /** Called by UserManagerService */
15856    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15857        mDirtyUsers.remove(userHandle);
15858        mSettings.removeUserLPw(userHandle);
15859        mPendingBroadcasts.remove(userHandle);
15860        if (mInstaller != null) {
15861            // Technically, we shouldn't be doing this with the package lock
15862            // held.  However, this is very rare, and there is already so much
15863            // other disk I/O going on, that we'll let it slide for now.
15864            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15865            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15866                final String volumeUuid = vol.getFsUuid();
15867                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15868                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15869            }
15870        }
15871        mUserNeedsBadging.delete(userHandle);
15872        removeUnusedPackagesLILPw(userManager, userHandle);
15873    }
15874
15875    /**
15876     * We're removing userHandle and would like to remove any downloaded packages
15877     * that are no longer in use by any other user.
15878     * @param userHandle the user being removed
15879     */
15880    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15881        final boolean DEBUG_CLEAN_APKS = false;
15882        int [] users = userManager.getUserIdsLPr();
15883        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15884        while (psit.hasNext()) {
15885            PackageSetting ps = psit.next();
15886            if (ps.pkg == null) {
15887                continue;
15888            }
15889            final String packageName = ps.pkg.packageName;
15890            // Skip over if system app
15891            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15892                continue;
15893            }
15894            if (DEBUG_CLEAN_APKS) {
15895                Slog.i(TAG, "Checking package " + packageName);
15896            }
15897            boolean keep = false;
15898            for (int i = 0; i < users.length; i++) {
15899                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15900                    keep = true;
15901                    if (DEBUG_CLEAN_APKS) {
15902                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15903                                + users[i]);
15904                    }
15905                    break;
15906                }
15907            }
15908            if (!keep) {
15909                if (DEBUG_CLEAN_APKS) {
15910                    Slog.i(TAG, "  Removing package " + packageName);
15911                }
15912                mHandler.post(new Runnable() {
15913                    public void run() {
15914                        deletePackageX(packageName, userHandle, 0);
15915                    } //end run
15916                });
15917            }
15918        }
15919    }
15920
15921    /** Called by UserManagerService */
15922    void createNewUserLILPw(int userHandle) {
15923        if (mInstaller != null) {
15924            mInstaller.createUserConfig(userHandle);
15925            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15926            applyFactoryDefaultBrowserLPw(userHandle);
15927            primeDomainVerificationsLPw(userHandle);
15928        }
15929    }
15930
15931    void newUserCreated(final int userHandle) {
15932        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15933    }
15934
15935    @Override
15936    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15937        mContext.enforceCallingOrSelfPermission(
15938                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15939                "Only package verification agents can read the verifier device identity");
15940
15941        synchronized (mPackages) {
15942            return mSettings.getVerifierDeviceIdentityLPw();
15943        }
15944    }
15945
15946    @Override
15947    public void setPermissionEnforced(String permission, boolean enforced) {
15948        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15949        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15950            synchronized (mPackages) {
15951                if (mSettings.mReadExternalStorageEnforced == null
15952                        || mSettings.mReadExternalStorageEnforced != enforced) {
15953                    mSettings.mReadExternalStorageEnforced = enforced;
15954                    mSettings.writeLPr();
15955                }
15956            }
15957            // kill any non-foreground processes so we restart them and
15958            // grant/revoke the GID.
15959            final IActivityManager am = ActivityManagerNative.getDefault();
15960            if (am != null) {
15961                final long token = Binder.clearCallingIdentity();
15962                try {
15963                    am.killProcessesBelowForeground("setPermissionEnforcement");
15964                } catch (RemoteException e) {
15965                } finally {
15966                    Binder.restoreCallingIdentity(token);
15967                }
15968            }
15969        } else {
15970            throw new IllegalArgumentException("No selective enforcement for " + permission);
15971        }
15972    }
15973
15974    @Override
15975    @Deprecated
15976    public boolean isPermissionEnforced(String permission) {
15977        return true;
15978    }
15979
15980    @Override
15981    public boolean isStorageLow() {
15982        final long token = Binder.clearCallingIdentity();
15983        try {
15984            final DeviceStorageMonitorInternal
15985                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15986            if (dsm != null) {
15987                return dsm.isMemoryLow();
15988            } else {
15989                return false;
15990            }
15991        } finally {
15992            Binder.restoreCallingIdentity(token);
15993        }
15994    }
15995
15996    @Override
15997    public IPackageInstaller getPackageInstaller() {
15998        return mInstallerService;
15999    }
16000
16001    private boolean userNeedsBadging(int userId) {
16002        int index = mUserNeedsBadging.indexOfKey(userId);
16003        if (index < 0) {
16004            final UserInfo userInfo;
16005            final long token = Binder.clearCallingIdentity();
16006            try {
16007                userInfo = sUserManager.getUserInfo(userId);
16008            } finally {
16009                Binder.restoreCallingIdentity(token);
16010            }
16011            final boolean b;
16012            if (userInfo != null && userInfo.isManagedProfile()) {
16013                b = true;
16014            } else {
16015                b = false;
16016            }
16017            mUserNeedsBadging.put(userId, b);
16018            return b;
16019        }
16020        return mUserNeedsBadging.valueAt(index);
16021    }
16022
16023    @Override
16024    public KeySet getKeySetByAlias(String packageName, String alias) {
16025        if (packageName == null || alias == null) {
16026            return null;
16027        }
16028        synchronized(mPackages) {
16029            final PackageParser.Package pkg = mPackages.get(packageName);
16030            if (pkg == null) {
16031                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16032                throw new IllegalArgumentException("Unknown package: " + packageName);
16033            }
16034            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16035            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16036        }
16037    }
16038
16039    @Override
16040    public KeySet getSigningKeySet(String packageName) {
16041        if (packageName == null) {
16042            return null;
16043        }
16044        synchronized(mPackages) {
16045            final PackageParser.Package pkg = mPackages.get(packageName);
16046            if (pkg == null) {
16047                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16048                throw new IllegalArgumentException("Unknown package: " + packageName);
16049            }
16050            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16051                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16052                throw new SecurityException("May not access signing KeySet of other apps.");
16053            }
16054            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16055            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16056        }
16057    }
16058
16059    @Override
16060    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16061        if (packageName == null || ks == null) {
16062            return false;
16063        }
16064        synchronized(mPackages) {
16065            final PackageParser.Package pkg = mPackages.get(packageName);
16066            if (pkg == null) {
16067                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16068                throw new IllegalArgumentException("Unknown package: " + packageName);
16069            }
16070            IBinder ksh = ks.getToken();
16071            if (ksh instanceof KeySetHandle) {
16072                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16073                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16074            }
16075            return false;
16076        }
16077    }
16078
16079    @Override
16080    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16081        if (packageName == null || ks == null) {
16082            return false;
16083        }
16084        synchronized(mPackages) {
16085            final PackageParser.Package pkg = mPackages.get(packageName);
16086            if (pkg == null) {
16087                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16088                throw new IllegalArgumentException("Unknown package: " + packageName);
16089            }
16090            IBinder ksh = ks.getToken();
16091            if (ksh instanceof KeySetHandle) {
16092                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16093                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16094            }
16095            return false;
16096        }
16097    }
16098
16099    public void getUsageStatsIfNoPackageUsageInfo() {
16100        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16101            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16102            if (usm == null) {
16103                throw new IllegalStateException("UsageStatsManager must be initialized");
16104            }
16105            long now = System.currentTimeMillis();
16106            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16107            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16108                String packageName = entry.getKey();
16109                PackageParser.Package pkg = mPackages.get(packageName);
16110                if (pkg == null) {
16111                    continue;
16112                }
16113                UsageStats usage = entry.getValue();
16114                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16115                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16116            }
16117        }
16118    }
16119
16120    /**
16121     * Check and throw if the given before/after packages would be considered a
16122     * downgrade.
16123     */
16124    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16125            throws PackageManagerException {
16126        if (after.versionCode < before.mVersionCode) {
16127            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16128                    "Update version code " + after.versionCode + " is older than current "
16129                    + before.mVersionCode);
16130        } else if (after.versionCode == before.mVersionCode) {
16131            if (after.baseRevisionCode < before.baseRevisionCode) {
16132                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16133                        "Update base revision code " + after.baseRevisionCode
16134                        + " is older than current " + before.baseRevisionCode);
16135            }
16136
16137            if (!ArrayUtils.isEmpty(after.splitNames)) {
16138                for (int i = 0; i < after.splitNames.length; i++) {
16139                    final String splitName = after.splitNames[i];
16140                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16141                    if (j != -1) {
16142                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16143                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16144                                    "Update split " + splitName + " revision code "
16145                                    + after.splitRevisionCodes[i] + " is older than current "
16146                                    + before.splitRevisionCodes[j]);
16147                        }
16148                    }
16149                }
16150            }
16151        }
16152    }
16153
16154    private static class MoveCallbacks extends Handler {
16155        private static final int MSG_CREATED = 1;
16156        private static final int MSG_STATUS_CHANGED = 2;
16157
16158        private final RemoteCallbackList<IPackageMoveObserver>
16159                mCallbacks = new RemoteCallbackList<>();
16160
16161        private final SparseIntArray mLastStatus = new SparseIntArray();
16162
16163        public MoveCallbacks(Looper looper) {
16164            super(looper);
16165        }
16166
16167        public void register(IPackageMoveObserver callback) {
16168            mCallbacks.register(callback);
16169        }
16170
16171        public void unregister(IPackageMoveObserver callback) {
16172            mCallbacks.unregister(callback);
16173        }
16174
16175        @Override
16176        public void handleMessage(Message msg) {
16177            final SomeArgs args = (SomeArgs) msg.obj;
16178            final int n = mCallbacks.beginBroadcast();
16179            for (int i = 0; i < n; i++) {
16180                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16181                try {
16182                    invokeCallback(callback, msg.what, args);
16183                } catch (RemoteException ignored) {
16184                }
16185            }
16186            mCallbacks.finishBroadcast();
16187            args.recycle();
16188        }
16189
16190        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16191                throws RemoteException {
16192            switch (what) {
16193                case MSG_CREATED: {
16194                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16195                    break;
16196                }
16197                case MSG_STATUS_CHANGED: {
16198                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16199                    break;
16200                }
16201            }
16202        }
16203
16204        private void notifyCreated(int moveId, Bundle extras) {
16205            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16206
16207            final SomeArgs args = SomeArgs.obtain();
16208            args.argi1 = moveId;
16209            args.arg2 = extras;
16210            obtainMessage(MSG_CREATED, args).sendToTarget();
16211        }
16212
16213        private void notifyStatusChanged(int moveId, int status) {
16214            notifyStatusChanged(moveId, status, -1);
16215        }
16216
16217        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16218            Slog.v(TAG, "Move " + moveId + " status " + status);
16219
16220            final SomeArgs args = SomeArgs.obtain();
16221            args.argi1 = moveId;
16222            args.argi2 = status;
16223            args.arg3 = estMillis;
16224            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16225
16226            synchronized (mLastStatus) {
16227                mLastStatus.put(moveId, status);
16228            }
16229        }
16230    }
16231
16232    private final class OnPermissionChangeListeners extends Handler {
16233        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16234
16235        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16236                new RemoteCallbackList<>();
16237
16238        public OnPermissionChangeListeners(Looper looper) {
16239            super(looper);
16240        }
16241
16242        @Override
16243        public void handleMessage(Message msg) {
16244            switch (msg.what) {
16245                case MSG_ON_PERMISSIONS_CHANGED: {
16246                    final int uid = msg.arg1;
16247                    handleOnPermissionsChanged(uid);
16248                } break;
16249            }
16250        }
16251
16252        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16253            mPermissionListeners.register(listener);
16254
16255        }
16256
16257        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16258            mPermissionListeners.unregister(listener);
16259        }
16260
16261        public void onPermissionsChanged(int uid) {
16262            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16263                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16264            }
16265        }
16266
16267        private void handleOnPermissionsChanged(int uid) {
16268            final int count = mPermissionListeners.beginBroadcast();
16269            try {
16270                for (int i = 0; i < count; i++) {
16271                    IOnPermissionsChangeListener callback = mPermissionListeners
16272                            .getBroadcastItem(i);
16273                    try {
16274                        callback.onPermissionsChanged(uid);
16275                    } catch (RemoteException e) {
16276                        Log.e(TAG, "Permission listener is dead", e);
16277                    }
16278                }
16279            } finally {
16280                mPermissionListeners.finishBroadcast();
16281            }
16282        }
16283    }
16284
16285    private class PackageManagerInternalImpl extends PackageManagerInternal {
16286        @Override
16287        public void setLocationPackagesProvider(PackagesProvider provider) {
16288            synchronized (mPackages) {
16289                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16290            }
16291        }
16292
16293        @Override
16294        public void setImePackagesProvider(PackagesProvider provider) {
16295            synchronized (mPackages) {
16296                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16297            }
16298        }
16299
16300        @Override
16301        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16302            synchronized (mPackages) {
16303                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16304            }
16305        }
16306
16307        @Override
16308        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16309            synchronized (mPackages) {
16310                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16311            }
16312        }
16313
16314        @Override
16315        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16316            synchronized (mPackages) {
16317                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16318            }
16319        }
16320
16321        @Override
16322        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16323            synchronized (mPackages) {
16324                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16325            }
16326        }
16327
16328        @Override
16329        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16330            synchronized (mPackages) {
16331                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16332                        packageName, userId);
16333            }
16334        }
16335
16336        @Override
16337        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16338            synchronized (mPackages) {
16339                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16340                        packageName, userId);
16341            }
16342        }
16343    }
16344
16345    @Override
16346    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16347        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16348        synchronized (mPackages) {
16349            final long identity = Binder.clearCallingIdentity();
16350            try {
16351                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16352                        packageNames, userId);
16353            } finally {
16354                Binder.restoreCallingIdentity(identity);
16355            }
16356        }
16357    }
16358
16359    private static void enforceSystemOrPhoneCaller(String tag) {
16360        int callingUid = Binder.getCallingUid();
16361        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16362            throw new SecurityException(
16363                    "Cannot call " + tag + " from UID " + callingUid);
16364        }
16365    }
16366}
16367